id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_bad_5666_7
/* * Synchronous Cryptographic Hash operations. * * Copyright (c) 2008 Herbert Xu <herbert@gondor.apana.org.au> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include <crypto/scatterwalk.h> #include <crypto/internal/hash.h> #include <linux/err.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/seq_file.h> #include <linux/cryptouser.h> #include <net/netlink.h> #include "internal.h" static const struct crypto_type crypto_shash_type; static int shash_no_setkey(struct crypto_shash *tfm, const u8 *key, unsigned int keylen) { return -ENOSYS; } static int shash_setkey_unaligned(struct crypto_shash *tfm, const u8 *key, unsigned int keylen) { struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); unsigned long absize; u8 *buffer, *alignbuffer; int err; absize = keylen + (alignmask & ~(crypto_tfm_ctx_alignment() - 1)); buffer = kmalloc(absize, GFP_KERNEL); if (!buffer) return -ENOMEM; alignbuffer = (u8 *)ALIGN((unsigned long)buffer, alignmask + 1); memcpy(alignbuffer, key, keylen); err = shash->setkey(tfm, alignbuffer, keylen); kzfree(buffer); return err; } int crypto_shash_setkey(struct crypto_shash *tfm, const u8 *key, unsigned int keylen) { struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if ((unsigned long)key & alignmask) return shash_setkey_unaligned(tfm, key, keylen); return shash->setkey(tfm, key, keylen); } EXPORT_SYMBOL_GPL(crypto_shash_setkey); static inline unsigned int shash_align_buffer_size(unsigned len, unsigned long mask) { return len + (mask & ~(__alignof__(u8 __attribute__ ((aligned))) - 1)); } static int shash_update_unaligned(struct shash_desc *desc, const u8 *data, unsigned int len) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); unsigned int unaligned_len = alignmask + 1 - ((unsigned long)data & alignmask); u8 ubuf[shash_align_buffer_size(unaligned_len, alignmask)] __attribute__ ((aligned)); u8 *buf = PTR_ALIGN(&ubuf[0], alignmask + 1); int err; if (unaligned_len > len) unaligned_len = len; memcpy(buf, data, unaligned_len); err = shash->update(desc, buf, unaligned_len); memset(buf, 0, unaligned_len); return err ?: shash->update(desc, data + unaligned_len, len - unaligned_len); } int crypto_shash_update(struct shash_desc *desc, const u8 *data, unsigned int len) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if ((unsigned long)data & alignmask) return shash_update_unaligned(desc, data, len); return shash->update(desc, data, len); } EXPORT_SYMBOL_GPL(crypto_shash_update); static int shash_final_unaligned(struct shash_desc *desc, u8 *out) { struct crypto_shash *tfm = desc->tfm; unsigned long alignmask = crypto_shash_alignmask(tfm); struct shash_alg *shash = crypto_shash_alg(tfm); unsigned int ds = crypto_shash_digestsize(tfm); u8 ubuf[shash_align_buffer_size(ds, alignmask)] __attribute__ ((aligned)); u8 *buf = PTR_ALIGN(&ubuf[0], alignmask + 1); int err; err = shash->final(desc, buf); if (err) goto out; memcpy(out, buf, ds); out: memset(buf, 0, ds); return err; } int crypto_shash_final(struct shash_desc *desc, u8 *out) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if ((unsigned long)out & alignmask) return shash_final_unaligned(desc, out); return shash->final(desc, out); } EXPORT_SYMBOL_GPL(crypto_shash_final); static int shash_finup_unaligned(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out) { return crypto_shash_update(desc, data, len) ?: crypto_shash_final(desc, out); } int crypto_shash_finup(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if (((unsigned long)data | (unsigned long)out) & alignmask) return shash_finup_unaligned(desc, data, len, out); return shash->finup(desc, data, len, out); } EXPORT_SYMBOL_GPL(crypto_shash_finup); static int shash_digest_unaligned(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out) { return crypto_shash_init(desc) ?: crypto_shash_finup(desc, data, len, out); } int crypto_shash_digest(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if (((unsigned long)data | (unsigned long)out) & alignmask) return shash_digest_unaligned(desc, data, len, out); return shash->digest(desc, data, len, out); } EXPORT_SYMBOL_GPL(crypto_shash_digest); static int shash_default_export(struct shash_desc *desc, void *out) { memcpy(out, shash_desc_ctx(desc), crypto_shash_descsize(desc->tfm)); return 0; } static int shash_default_import(struct shash_desc *desc, const void *in) { memcpy(shash_desc_ctx(desc), in, crypto_shash_descsize(desc->tfm)); return 0; } static int shash_async_setkey(struct crypto_ahash *tfm, const u8 *key, unsigned int keylen) { struct crypto_shash **ctx = crypto_ahash_ctx(tfm); return crypto_shash_setkey(*ctx, key, keylen); } static int shash_async_init(struct ahash_request *req) { struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req)); struct shash_desc *desc = ahash_request_ctx(req); desc->tfm = *ctx; desc->flags = req->base.flags; return crypto_shash_init(desc); } int shash_ahash_update(struct ahash_request *req, struct shash_desc *desc) { struct crypto_hash_walk walk; int nbytes; for (nbytes = crypto_hash_walk_first(req, &walk); nbytes > 0; nbytes = crypto_hash_walk_done(&walk, nbytes)) nbytes = crypto_shash_update(desc, walk.data, nbytes); return nbytes; } EXPORT_SYMBOL_GPL(shash_ahash_update); static int shash_async_update(struct ahash_request *req) { return shash_ahash_update(req, ahash_request_ctx(req)); } static int shash_async_final(struct ahash_request *req) { return crypto_shash_final(ahash_request_ctx(req), req->result); } int shash_ahash_finup(struct ahash_request *req, struct shash_desc *desc) { struct crypto_hash_walk walk; int nbytes; nbytes = crypto_hash_walk_first(req, &walk); if (!nbytes) return crypto_shash_final(desc, req->result); do { nbytes = crypto_hash_walk_last(&walk) ? crypto_shash_finup(desc, walk.data, nbytes, req->result) : crypto_shash_update(desc, walk.data, nbytes); nbytes = crypto_hash_walk_done(&walk, nbytes); } while (nbytes > 0); return nbytes; } EXPORT_SYMBOL_GPL(shash_ahash_finup); static int shash_async_finup(struct ahash_request *req) { struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req)); struct shash_desc *desc = ahash_request_ctx(req); desc->tfm = *ctx; desc->flags = req->base.flags; return shash_ahash_finup(req, desc); } int shash_ahash_digest(struct ahash_request *req, struct shash_desc *desc) { struct scatterlist *sg = req->src; unsigned int offset = sg->offset; unsigned int nbytes = req->nbytes; int err; if (nbytes < min(sg->length, ((unsigned int)(PAGE_SIZE)) - offset)) { void *data; data = kmap_atomic(sg_page(sg)); err = crypto_shash_digest(desc, data + offset, nbytes, req->result); kunmap_atomic(data); crypto_yield(desc->flags); } else err = crypto_shash_init(desc) ?: shash_ahash_finup(req, desc); return err; } EXPORT_SYMBOL_GPL(shash_ahash_digest); static int shash_async_digest(struct ahash_request *req) { struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req)); struct shash_desc *desc = ahash_request_ctx(req); desc->tfm = *ctx; desc->flags = req->base.flags; return shash_ahash_digest(req, desc); } static int shash_async_export(struct ahash_request *req, void *out) { return crypto_shash_export(ahash_request_ctx(req), out); } static int shash_async_import(struct ahash_request *req, const void *in) { struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req)); struct shash_desc *desc = ahash_request_ctx(req); desc->tfm = *ctx; desc->flags = req->base.flags; return crypto_shash_import(desc, in); } static void crypto_exit_shash_ops_async(struct crypto_tfm *tfm) { struct crypto_shash **ctx = crypto_tfm_ctx(tfm); crypto_free_shash(*ctx); } int crypto_init_shash_ops_async(struct crypto_tfm *tfm) { struct crypto_alg *calg = tfm->__crt_alg; struct shash_alg *alg = __crypto_shash_alg(calg); struct crypto_ahash *crt = __crypto_ahash_cast(tfm); struct crypto_shash **ctx = crypto_tfm_ctx(tfm); struct crypto_shash *shash; if (!crypto_mod_get(calg)) return -EAGAIN; shash = crypto_create_tfm(calg, &crypto_shash_type); if (IS_ERR(shash)) { crypto_mod_put(calg); return PTR_ERR(shash); } *ctx = shash; tfm->exit = crypto_exit_shash_ops_async; crt->init = shash_async_init; crt->update = shash_async_update; crt->final = shash_async_final; crt->finup = shash_async_finup; crt->digest = shash_async_digest; if (alg->setkey) crt->setkey = shash_async_setkey; if (alg->export) crt->export = shash_async_export; if (alg->import) crt->import = shash_async_import; crt->reqsize = sizeof(struct shash_desc) + crypto_shash_descsize(shash); return 0; } static int shash_compat_setkey(struct crypto_hash *tfm, const u8 *key, unsigned int keylen) { struct shash_desc **descp = crypto_hash_ctx(tfm); struct shash_desc *desc = *descp; return crypto_shash_setkey(desc->tfm, key, keylen); } static int shash_compat_init(struct hash_desc *hdesc) { struct shash_desc **descp = crypto_hash_ctx(hdesc->tfm); struct shash_desc *desc = *descp; desc->flags = hdesc->flags; return crypto_shash_init(desc); } static int shash_compat_update(struct hash_desc *hdesc, struct scatterlist *sg, unsigned int len) { struct shash_desc **descp = crypto_hash_ctx(hdesc->tfm); struct shash_desc *desc = *descp; struct crypto_hash_walk walk; int nbytes; for (nbytes = crypto_hash_walk_first_compat(hdesc, &walk, sg, len); nbytes > 0; nbytes = crypto_hash_walk_done(&walk, nbytes)) nbytes = crypto_shash_update(desc, walk.data, nbytes); return nbytes; } static int shash_compat_final(struct hash_desc *hdesc, u8 *out) { struct shash_desc **descp = crypto_hash_ctx(hdesc->tfm); return crypto_shash_final(*descp, out); } static int shash_compat_digest(struct hash_desc *hdesc, struct scatterlist *sg, unsigned int nbytes, u8 *out) { unsigned int offset = sg->offset; int err; if (nbytes < min(sg->length, ((unsigned int)(PAGE_SIZE)) - offset)) { struct shash_desc **descp = crypto_hash_ctx(hdesc->tfm); struct shash_desc *desc = *descp; void *data; desc->flags = hdesc->flags; data = kmap_atomic(sg_page(sg)); err = crypto_shash_digest(desc, data + offset, nbytes, out); kunmap_atomic(data); crypto_yield(desc->flags); goto out; } err = shash_compat_init(hdesc); if (err) goto out; err = shash_compat_update(hdesc, sg, nbytes); if (err) goto out; err = shash_compat_final(hdesc, out); out: return err; } static void crypto_exit_shash_ops_compat(struct crypto_tfm *tfm) { struct shash_desc **descp = crypto_tfm_ctx(tfm); struct shash_desc *desc = *descp; crypto_free_shash(desc->tfm); kzfree(desc); } static int crypto_init_shash_ops_compat(struct crypto_tfm *tfm) { struct hash_tfm *crt = &tfm->crt_hash; struct crypto_alg *calg = tfm->__crt_alg; struct shash_alg *alg = __crypto_shash_alg(calg); struct shash_desc **descp = crypto_tfm_ctx(tfm); struct crypto_shash *shash; struct shash_desc *desc; if (!crypto_mod_get(calg)) return -EAGAIN; shash = crypto_create_tfm(calg, &crypto_shash_type); if (IS_ERR(shash)) { crypto_mod_put(calg); return PTR_ERR(shash); } desc = kmalloc(sizeof(*desc) + crypto_shash_descsize(shash), GFP_KERNEL); if (!desc) { crypto_free_shash(shash); return -ENOMEM; } *descp = desc; desc->tfm = shash; tfm->exit = crypto_exit_shash_ops_compat; crt->init = shash_compat_init; crt->update = shash_compat_update; crt->final = shash_compat_final; crt->digest = shash_compat_digest; crt->setkey = shash_compat_setkey; crt->digestsize = alg->digestsize; return 0; } static int crypto_init_shash_ops(struct crypto_tfm *tfm, u32 type, u32 mask) { switch (mask & CRYPTO_ALG_TYPE_MASK) { case CRYPTO_ALG_TYPE_HASH_MASK: return crypto_init_shash_ops_compat(tfm); } return -EINVAL; } static unsigned int crypto_shash_ctxsize(struct crypto_alg *alg, u32 type, u32 mask) { switch (mask & CRYPTO_ALG_TYPE_MASK) { case CRYPTO_ALG_TYPE_HASH_MASK: return sizeof(struct shash_desc *); } return 0; } static int crypto_shash_init_tfm(struct crypto_tfm *tfm) { struct crypto_shash *hash = __crypto_shash_cast(tfm); hash->descsize = crypto_shash_alg(hash)->descsize; return 0; } static unsigned int crypto_shash_extsize(struct crypto_alg *alg) { return alg->cra_ctxsize; } #ifdef CONFIG_NET static int crypto_shash_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_hash rhash; struct shash_alg *salg = __crypto_shash_alg(alg); snprintf(rhash.type, CRYPTO_MAX_ALG_NAME, "%s", "shash"); rhash.blocksize = alg->cra_blocksize; rhash.digestsize = salg->digestsize; if (nla_put(skb, CRYPTOCFGA_REPORT_HASH, sizeof(struct crypto_report_hash), &rhash)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } #else static int crypto_shash_report(struct sk_buff *skb, struct crypto_alg *alg) { return -ENOSYS; } #endif static void crypto_shash_show(struct seq_file *m, struct crypto_alg *alg) __attribute__ ((unused)); static void crypto_shash_show(struct seq_file *m, struct crypto_alg *alg) { struct shash_alg *salg = __crypto_shash_alg(alg); seq_printf(m, "type : shash\n"); seq_printf(m, "blocksize : %u\n", alg->cra_blocksize); seq_printf(m, "digestsize : %u\n", salg->digestsize); } static const struct crypto_type crypto_shash_type = { .ctxsize = crypto_shash_ctxsize, .extsize = crypto_shash_extsize, .init = crypto_init_shash_ops, .init_tfm = crypto_shash_init_tfm, #ifdef CONFIG_PROC_FS .show = crypto_shash_show, #endif .report = crypto_shash_report, .maskclear = ~CRYPTO_ALG_TYPE_MASK, .maskset = CRYPTO_ALG_TYPE_MASK, .type = CRYPTO_ALG_TYPE_SHASH, .tfmsize = offsetof(struct crypto_shash, base), }; struct crypto_shash *crypto_alloc_shash(const char *alg_name, u32 type, u32 mask) { return crypto_alloc_tfm(alg_name, &crypto_shash_type, type, mask); } EXPORT_SYMBOL_GPL(crypto_alloc_shash); static int shash_prepare_alg(struct shash_alg *alg) { struct crypto_alg *base = &alg->base; if (alg->digestsize > PAGE_SIZE / 8 || alg->descsize > PAGE_SIZE / 8 || alg->statesize > PAGE_SIZE / 8) return -EINVAL; base->cra_type = &crypto_shash_type; base->cra_flags &= ~CRYPTO_ALG_TYPE_MASK; base->cra_flags |= CRYPTO_ALG_TYPE_SHASH; if (!alg->finup) alg->finup = shash_finup_unaligned; if (!alg->digest) alg->digest = shash_digest_unaligned; if (!alg->export) { alg->export = shash_default_export; alg->import = shash_default_import; alg->statesize = alg->descsize; } if (!alg->setkey) alg->setkey = shash_no_setkey; return 0; } int crypto_register_shash(struct shash_alg *alg) { struct crypto_alg *base = &alg->base; int err; err = shash_prepare_alg(alg); if (err) return err; return crypto_register_alg(base); } EXPORT_SYMBOL_GPL(crypto_register_shash); int crypto_unregister_shash(struct shash_alg *alg) { return crypto_unregister_alg(&alg->base); } EXPORT_SYMBOL_GPL(crypto_unregister_shash); int crypto_register_shashes(struct shash_alg *algs, int count) { int i, ret; for (i = 0; i < count; i++) { ret = crypto_register_shash(&algs[i]); if (ret) goto err; } return 0; err: for (--i; i >= 0; --i) crypto_unregister_shash(&algs[i]); return ret; } EXPORT_SYMBOL_GPL(crypto_register_shashes); int crypto_unregister_shashes(struct shash_alg *algs, int count) { int i, ret; for (i = count - 1; i >= 0; --i) { ret = crypto_unregister_shash(&algs[i]); if (ret) pr_err("Failed to unregister %s %s: %d\n", algs[i].base.cra_driver_name, algs[i].base.cra_name, ret); } return 0; } EXPORT_SYMBOL_GPL(crypto_unregister_shashes); int shash_register_instance(struct crypto_template *tmpl, struct shash_instance *inst) { int err; err = shash_prepare_alg(&inst->alg); if (err) return err; return crypto_register_instance(tmpl, shash_crypto_instance(inst)); } EXPORT_SYMBOL_GPL(shash_register_instance); void shash_free_instance(struct crypto_instance *inst) { crypto_drop_spawn(crypto_instance_ctx(inst)); kfree(shash_instance(inst)); } EXPORT_SYMBOL_GPL(shash_free_instance); int crypto_init_shash_spawn(struct crypto_shash_spawn *spawn, struct shash_alg *alg, struct crypto_instance *inst) { return crypto_init_spawn2(&spawn->base, &alg->base, inst, &crypto_shash_type); } EXPORT_SYMBOL_GPL(crypto_init_shash_spawn); struct shash_alg *shash_attr_alg(struct rtattr *rta, u32 type, u32 mask) { struct crypto_alg *alg; alg = crypto_attr_alg2(rta, &crypto_shash_type, type, mask); return IS_ERR(alg) ? ERR_CAST(alg) : container_of(alg, struct shash_alg, base); } EXPORT_SYMBOL_GPL(shash_attr_alg); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Synchronous cryptographic hash type");
./CrossVul/dataset_final_sorted/CWE-310/c/bad_5666_7
crossvul-cpp_data_good_4932_0
/* Decoder for ASN.1 BER/DER/CER encoded bytestream * * Copyright (C) 2012 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 Licence * as published by the Free Software Foundation; either version * 2 of the Licence, or (at your option) any later version. */ #include <linux/export.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/asn1_decoder.h> #include <linux/asn1_ber_bytecode.h> static const unsigned char asn1_op_lengths[ASN1_OP__NR] = { /* OPC TAG JMP ACT */ [ASN1_OP_MATCH] = 1 + 1, [ASN1_OP_MATCH_OR_SKIP] = 1 + 1, [ASN1_OP_MATCH_ACT] = 1 + 1 + 1, [ASN1_OP_MATCH_ACT_OR_SKIP] = 1 + 1 + 1, [ASN1_OP_MATCH_JUMP] = 1 + 1 + 1, [ASN1_OP_MATCH_JUMP_OR_SKIP] = 1 + 1 + 1, [ASN1_OP_MATCH_ANY] = 1, [ASN1_OP_MATCH_ANY_ACT] = 1 + 1, [ASN1_OP_COND_MATCH_OR_SKIP] = 1 + 1, [ASN1_OP_COND_MATCH_ACT_OR_SKIP] = 1 + 1 + 1, [ASN1_OP_COND_MATCH_JUMP_OR_SKIP] = 1 + 1 + 1, [ASN1_OP_COND_MATCH_ANY] = 1, [ASN1_OP_COND_MATCH_ANY_ACT] = 1 + 1, [ASN1_OP_COND_FAIL] = 1, [ASN1_OP_COMPLETE] = 1, [ASN1_OP_ACT] = 1 + 1, [ASN1_OP_MAYBE_ACT] = 1 + 1, [ASN1_OP_RETURN] = 1, [ASN1_OP_END_SEQ] = 1, [ASN1_OP_END_SEQ_OF] = 1 + 1, [ASN1_OP_END_SET] = 1, [ASN1_OP_END_SET_OF] = 1 + 1, [ASN1_OP_END_SEQ_ACT] = 1 + 1, [ASN1_OP_END_SEQ_OF_ACT] = 1 + 1 + 1, [ASN1_OP_END_SET_ACT] = 1 + 1, [ASN1_OP_END_SET_OF_ACT] = 1 + 1 + 1, }; /* * Find the length of an indefinite length object * @data: The data buffer * @datalen: The end of the innermost containing element in the buffer * @_dp: The data parse cursor (updated before returning) * @_len: Where to return the size of the element. * @_errmsg: Where to return a pointer to an error message on error */ static int asn1_find_indefinite_length(const unsigned char *data, size_t datalen, size_t *_dp, size_t *_len, const char **_errmsg) { unsigned char tag, tmp; size_t dp = *_dp, len, n; int indef_level = 1; next_tag: if (unlikely(datalen - dp < 2)) { if (datalen == dp) goto missing_eoc; goto data_overrun_error; } /* Extract a tag from the data */ tag = data[dp++]; if (tag == 0) { /* It appears to be an EOC. */ if (data[dp++] != 0) goto invalid_eoc; if (--indef_level <= 0) { *_len = dp - *_dp; *_dp = dp; return 0; } goto next_tag; } if (unlikely((tag & 0x1f) == ASN1_LONG_TAG)) { do { if (unlikely(datalen - dp < 2)) goto data_overrun_error; tmp = data[dp++]; } while (tmp & 0x80); } /* Extract the length */ len = data[dp++]; if (len <= 0x7f) { dp += len; goto next_tag; } if (unlikely(len == ASN1_INDEFINITE_LENGTH)) { /* Indefinite length */ if (unlikely((tag & ASN1_CONS_BIT) == ASN1_PRIM << 5)) goto indefinite_len_primitive; indef_level++; goto next_tag; } n = len - 0x80; if (unlikely(n > sizeof(size_t) - 1)) goto length_too_long; if (unlikely(n > datalen - dp)) goto data_overrun_error; for (len = 0; n > 0; n--) { len <<= 8; len |= data[dp++]; } dp += len; goto next_tag; length_too_long: *_errmsg = "Unsupported length"; goto error; indefinite_len_primitive: *_errmsg = "Indefinite len primitive not permitted"; goto error; invalid_eoc: *_errmsg = "Invalid length EOC"; goto error; data_overrun_error: *_errmsg = "Data overrun error"; goto error; missing_eoc: *_errmsg = "Missing EOC in indefinite len cons"; error: *_dp = dp; return -1; } /** * asn1_ber_decoder - Decoder BER/DER/CER ASN.1 according to pattern * @decoder: The decoder definition (produced by asn1_compiler) * @context: The caller's context (to be passed to the action functions) * @data: The encoded data * @datalen: The size of the encoded data * * Decode BER/DER/CER encoded ASN.1 data according to a bytecode pattern * produced by asn1_compiler. Action functions are called on marked tags to * allow the caller to retrieve significant data. * * LIMITATIONS: * * To keep down the amount of stack used by this function, the following limits * have been imposed: * * (1) This won't handle datalen > 65535 without increasing the size of the * cons stack elements and length_too_long checking. * * (2) The stack of constructed types is 10 deep. If the depth of non-leaf * constructed types exceeds this, the decode will fail. * * (3) The SET type (not the SET OF type) isn't really supported as tracking * what members of the set have been seen is a pain. */ int asn1_ber_decoder(const struct asn1_decoder *decoder, void *context, const unsigned char *data, size_t datalen) { const unsigned char *machine = decoder->machine; const asn1_action_t *actions = decoder->actions; size_t machlen = decoder->machlen; enum asn1_opcode op; unsigned char tag = 0, csp = 0, jsp = 0, optag = 0, hdr = 0; const char *errmsg; size_t pc = 0, dp = 0, tdp = 0, len = 0; int ret; unsigned char flags = 0; #define FLAG_INDEFINITE_LENGTH 0x01 #define FLAG_MATCHED 0x02 #define FLAG_LAST_MATCHED 0x04 /* Last tag matched */ #define FLAG_CONS 0x20 /* Corresponds to CONS bit in the opcode tag * - ie. whether or not we are going to parse * a compound type. */ #define NR_CONS_STACK 10 unsigned short cons_dp_stack[NR_CONS_STACK]; unsigned short cons_datalen_stack[NR_CONS_STACK]; unsigned char cons_hdrlen_stack[NR_CONS_STACK]; #define NR_JUMP_STACK 10 unsigned char jump_stack[NR_JUMP_STACK]; if (datalen > 65535) return -EMSGSIZE; next_op: pr_debug("next_op: pc=\e[32m%zu\e[m/%zu dp=\e[33m%zu\e[m/%zu C=%d J=%d\n", pc, machlen, dp, datalen, csp, jsp); if (unlikely(pc >= machlen)) goto machine_overrun_error; op = machine[pc]; if (unlikely(pc + asn1_op_lengths[op] > machlen)) goto machine_overrun_error; /* If this command is meant to match a tag, then do that before * evaluating the command. */ if (op <= ASN1_OP__MATCHES_TAG) { unsigned char tmp; /* Skip conditional matches if possible */ if ((op & ASN1_OP_MATCH__COND && flags & FLAG_MATCHED) || (op & ASN1_OP_MATCH__SKIP && dp == datalen)) { flags &= ~FLAG_LAST_MATCHED; pc += asn1_op_lengths[op]; goto next_op; } flags = 0; hdr = 2; /* Extract a tag from the data */ if (unlikely(dp >= datalen - 1)) goto data_overrun_error; tag = data[dp++]; if (unlikely((tag & 0x1f) == ASN1_LONG_TAG)) goto long_tag_not_supported; if (op & ASN1_OP_MATCH__ANY) { pr_debug("- any %02x\n", tag); } else { /* Extract the tag from the machine * - Either CONS or PRIM are permitted in the data if * CONS is not set in the op stream, otherwise CONS * is mandatory. */ optag = machine[pc + 1]; flags |= optag & FLAG_CONS; /* Determine whether the tag matched */ tmp = optag ^ tag; tmp &= ~(optag & ASN1_CONS_BIT); pr_debug("- match? %02x %02x %02x\n", tag, optag, tmp); if (tmp != 0) { /* All odd-numbered tags are MATCH_OR_SKIP. */ if (op & ASN1_OP_MATCH__SKIP) { pc += asn1_op_lengths[op]; dp--; goto next_op; } goto tag_mismatch; } } flags |= FLAG_MATCHED; len = data[dp++]; if (len > 0x7f) { if (unlikely(len == ASN1_INDEFINITE_LENGTH)) { /* Indefinite length */ if (unlikely(!(tag & ASN1_CONS_BIT))) goto indefinite_len_primitive; flags |= FLAG_INDEFINITE_LENGTH; if (unlikely(2 > datalen - dp)) goto data_overrun_error; } else { int n = len - 0x80; if (unlikely(n > 2)) goto length_too_long; if (unlikely(dp >= datalen - n)) goto data_overrun_error; hdr += n; for (len = 0; n > 0; n--) { len <<= 8; len |= data[dp++]; } if (unlikely(len > datalen - dp)) goto data_overrun_error; } } if (flags & FLAG_CONS) { /* For expected compound forms, we stack the positions * of the start and end of the data. */ if (unlikely(csp >= NR_CONS_STACK)) goto cons_stack_overflow; cons_dp_stack[csp] = dp; cons_hdrlen_stack[csp] = hdr; if (!(flags & FLAG_INDEFINITE_LENGTH)) { cons_datalen_stack[csp] = datalen; datalen = dp + len; } else { cons_datalen_stack[csp] = 0; } csp++; } pr_debug("- TAG: %02x %zu%s\n", tag, len, flags & FLAG_CONS ? " CONS" : ""); tdp = dp; } /* Decide how to handle the operation */ switch (op) { case ASN1_OP_MATCH_ANY_ACT: case ASN1_OP_COND_MATCH_ANY_ACT: ret = actions[machine[pc + 1]](context, hdr, tag, data + dp, len); if (ret < 0) return ret; goto skip_data; case ASN1_OP_MATCH_ACT: case ASN1_OP_MATCH_ACT_OR_SKIP: case ASN1_OP_COND_MATCH_ACT_OR_SKIP: ret = actions[machine[pc + 2]](context, hdr, tag, data + dp, len); if (ret < 0) return ret; goto skip_data; case ASN1_OP_MATCH: case ASN1_OP_MATCH_OR_SKIP: case ASN1_OP_MATCH_ANY: case ASN1_OP_COND_MATCH_OR_SKIP: case ASN1_OP_COND_MATCH_ANY: skip_data: if (!(flags & FLAG_CONS)) { if (flags & FLAG_INDEFINITE_LENGTH) { ret = asn1_find_indefinite_length( data, datalen, &dp, &len, &errmsg); if (ret < 0) goto error; } else { dp += len; } pr_debug("- LEAF: %zu\n", len); } pc += asn1_op_lengths[op]; goto next_op; case ASN1_OP_MATCH_JUMP: case ASN1_OP_MATCH_JUMP_OR_SKIP: case ASN1_OP_COND_MATCH_JUMP_OR_SKIP: pr_debug("- MATCH_JUMP\n"); if (unlikely(jsp == NR_JUMP_STACK)) goto jump_stack_overflow; jump_stack[jsp++] = pc + asn1_op_lengths[op]; pc = machine[pc + 2]; goto next_op; case ASN1_OP_COND_FAIL: if (unlikely(!(flags & FLAG_MATCHED))) goto tag_mismatch; pc += asn1_op_lengths[op]; goto next_op; case ASN1_OP_COMPLETE: if (unlikely(jsp != 0 || csp != 0)) { pr_err("ASN.1 decoder error: Stacks not empty at completion (%u, %u)\n", jsp, csp); return -EBADMSG; } return 0; case ASN1_OP_END_SET: case ASN1_OP_END_SET_ACT: if (unlikely(!(flags & FLAG_MATCHED))) goto tag_mismatch; case ASN1_OP_END_SEQ: case ASN1_OP_END_SET_OF: case ASN1_OP_END_SEQ_OF: case ASN1_OP_END_SEQ_ACT: case ASN1_OP_END_SET_OF_ACT: case ASN1_OP_END_SEQ_OF_ACT: if (unlikely(csp <= 0)) goto cons_stack_underflow; csp--; tdp = cons_dp_stack[csp]; hdr = cons_hdrlen_stack[csp]; len = datalen; datalen = cons_datalen_stack[csp]; pr_debug("- end cons t=%zu dp=%zu l=%zu/%zu\n", tdp, dp, len, datalen); if (datalen == 0) { /* Indefinite length - check for the EOC. */ datalen = len; if (unlikely(datalen - dp < 2)) goto data_overrun_error; if (data[dp++] != 0) { if (op & ASN1_OP_END__OF) { dp--; csp++; pc = machine[pc + 1]; pr_debug("- continue\n"); goto next_op; } goto missing_eoc; } if (data[dp++] != 0) goto invalid_eoc; len = dp - tdp - 2; } else { if (dp < len && (op & ASN1_OP_END__OF)) { datalen = len; csp++; pc = machine[pc + 1]; pr_debug("- continue\n"); goto next_op; } if (dp != len) goto cons_length_error; len -= tdp; pr_debug("- cons len l=%zu d=%zu\n", len, dp - tdp); } if (op & ASN1_OP_END__ACT) { unsigned char act; if (op & ASN1_OP_END__OF) act = machine[pc + 2]; else act = machine[pc + 1]; ret = actions[act](context, hdr, 0, data + tdp, len); } pc += asn1_op_lengths[op]; goto next_op; case ASN1_OP_MAYBE_ACT: if (!(flags & FLAG_LAST_MATCHED)) { pc += asn1_op_lengths[op]; goto next_op; } case ASN1_OP_ACT: ret = actions[machine[pc + 1]](context, hdr, tag, data + tdp, len); if (ret < 0) return ret; pc += asn1_op_lengths[op]; goto next_op; case ASN1_OP_RETURN: if (unlikely(jsp <= 0)) goto jump_stack_underflow; pc = jump_stack[--jsp]; flags |= FLAG_MATCHED | FLAG_LAST_MATCHED; goto next_op; default: break; } /* Shouldn't reach here */ pr_err("ASN.1 decoder error: Found reserved opcode (%u) pc=%zu\n", op, pc); return -EBADMSG; data_overrun_error: errmsg = "Data overrun error"; goto error; machine_overrun_error: errmsg = "Machine overrun error"; goto error; jump_stack_underflow: errmsg = "Jump stack underflow"; goto error; jump_stack_overflow: errmsg = "Jump stack overflow"; goto error; cons_stack_underflow: errmsg = "Cons stack underflow"; goto error; cons_stack_overflow: errmsg = "Cons stack overflow"; goto error; cons_length_error: errmsg = "Cons length error"; goto error; missing_eoc: errmsg = "Missing EOC in indefinite len cons"; goto error; invalid_eoc: errmsg = "Invalid length EOC"; goto error; length_too_long: errmsg = "Unsupported length"; goto error; indefinite_len_primitive: errmsg = "Indefinite len primitive not permitted"; goto error; tag_mismatch: errmsg = "Unexpected tag"; goto error; long_tag_not_supported: errmsg = "Long tag not supported"; error: pr_debug("\nASN1: %s [m=%zu d=%zu ot=%02x t=%02x l=%zu]\n", errmsg, pc, dp, optag, tag, len); return -EBADMSG; } EXPORT_SYMBOL_GPL(asn1_ber_decoder);
./CrossVul/dataset_final_sorted/CWE-310/c/good_4932_0
crossvul-cpp_data_good_5741_0
/* SCTP kernel implementation * (C) Copyright IBM Corp. 2002, 2004 * Copyright (c) 2001 Nokia, Inc. * Copyright (c) 2001 La Monte H.P. Yarroll * Copyright (c) 2002-2003 Intel Corp. * * This file is part of the SCTP kernel implementation * * SCTP over IPv6. * * 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 <linux-sctp@vger.kernel.org> * * Written or modified by: * Le Yanqun <yanqun.le@nokia.com> * Hui Huang <hui.huang@nokia.com> * La Monte H.P. Yarroll <piggy@acm.org> * Sridhar Samudrala <sri@us.ibm.com> * Jon Grimm <jgrimm@us.ibm.com> * Ardelle Fan <ardelle.fan@intel.com> * * Based on: * linux/net/ipv6/tcp_ipv6.c */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/in.h> #include <linux/in6.h> #include <linux/netdevice.h> #include <linux/init.h> #include <linux/ipsec.h> #include <linux/slab.h> #include <linux/ipv6.h> #include <linux/icmpv6.h> #include <linux/random.h> #include <linux/seq_file.h> #include <net/protocol.h> #include <net/ndisc.h> #include <net/ip.h> #include <net/ipv6.h> #include <net/transp_v6.h> #include <net/addrconf.h> #include <net/ip6_route.h> #include <net/inet_common.h> #include <net/inet_ecn.h> #include <net/sctp/sctp.h> #include <asm/uaccess.h> static inline int sctp_v6_addr_match_len(union sctp_addr *s1, union sctp_addr *s2); static void sctp_v6_to_addr(union sctp_addr *addr, struct in6_addr *saddr, __be16 port); static int sctp_v6_cmp_addr(const union sctp_addr *addr1, const union sctp_addr *addr2); /* Event handler for inet6 address addition/deletion events. * The sctp_local_addr_list needs to be protocted by a spin lock since * multiple notifiers (say IPv4 and IPv6) may be running at the same * time and thus corrupt the list. * The reader side is protected with RCU. */ static int sctp_inet6addr_event(struct notifier_block *this, unsigned long ev, void *ptr) { struct inet6_ifaddr *ifa = (struct inet6_ifaddr *)ptr; struct sctp_sockaddr_entry *addr = NULL; struct sctp_sockaddr_entry *temp; struct net *net = dev_net(ifa->idev->dev); int found = 0; switch (ev) { case NETDEV_UP: addr = kmalloc(sizeof(struct sctp_sockaddr_entry), GFP_ATOMIC); if (addr) { addr->a.v6.sin6_family = AF_INET6; addr->a.v6.sin6_port = 0; addr->a.v6.sin6_addr = ifa->addr; addr->a.v6.sin6_scope_id = ifa->idev->dev->ifindex; addr->valid = 1; spin_lock_bh(&net->sctp.local_addr_lock); list_add_tail_rcu(&addr->list, &net->sctp.local_addr_list); sctp_addr_wq_mgmt(net, addr, SCTP_ADDR_NEW); spin_unlock_bh(&net->sctp.local_addr_lock); } break; case NETDEV_DOWN: spin_lock_bh(&net->sctp.local_addr_lock); list_for_each_entry_safe(addr, temp, &net->sctp.local_addr_list, list) { if (addr->a.sa.sa_family == AF_INET6 && ipv6_addr_equal(&addr->a.v6.sin6_addr, &ifa->addr)) { sctp_addr_wq_mgmt(net, addr, SCTP_ADDR_DEL); found = 1; addr->valid = 0; list_del_rcu(&addr->list); break; } } spin_unlock_bh(&net->sctp.local_addr_lock); if (found) kfree_rcu(addr, rcu); break; } return NOTIFY_DONE; } static struct notifier_block sctp_inet6addr_notifier = { .notifier_call = sctp_inet6addr_event, }; /* ICMP error handler. */ static void sctp_v6_err(struct sk_buff *skb, struct inet6_skb_parm *opt, u8 type, u8 code, int offset, __be32 info) { struct inet6_dev *idev; struct sock *sk; struct sctp_association *asoc; struct sctp_transport *transport; struct ipv6_pinfo *np; __u16 saveip, savesctp; int err; struct net *net = dev_net(skb->dev); idev = in6_dev_get(skb->dev); /* Fix up skb to look at the embedded net header. */ saveip = skb->network_header; savesctp = skb->transport_header; skb_reset_network_header(skb); skb_set_transport_header(skb, offset); sk = sctp_err_lookup(net, AF_INET6, skb, sctp_hdr(skb), &asoc, &transport); /* Put back, the original pointers. */ skb->network_header = saveip; skb->transport_header = savesctp; if (!sk) { ICMP6_INC_STATS_BH(net, idev, ICMP6_MIB_INERRORS); goto out; } /* Warning: The sock lock is held. Remember to call * sctp_err_finish! */ switch (type) { case ICMPV6_PKT_TOOBIG: sctp_icmp_frag_needed(sk, asoc, transport, ntohl(info)); goto out_unlock; case ICMPV6_PARAMPROB: if (ICMPV6_UNK_NEXTHDR == code) { sctp_icmp_proto_unreachable(sk, asoc, transport); goto out_unlock; } break; case NDISC_REDIRECT: sctp_icmp_redirect(sk, transport, skb); break; default: break; } np = inet6_sk(sk); icmpv6_err_convert(type, code, &err); if (!sock_owned_by_user(sk) && np->recverr) { sk->sk_err = err; sk->sk_error_report(sk); } else { /* Only an error on timeout */ sk->sk_err_soft = err; } out_unlock: sctp_err_finish(sk, asoc); out: if (likely(idev != NULL)) in6_dev_put(idev); } static int sctp_v6_xmit(struct sk_buff *skb, struct sctp_transport *transport) { struct sock *sk = skb->sk; struct ipv6_pinfo *np = inet6_sk(sk); struct flowi6 *fl6 = &transport->fl.u.ip6; pr_debug("%s: skb:%p, len:%d, src:%pI6 dst:%pI6\n", __func__, skb, skb->len, &fl6->saddr, &fl6->daddr); IP6_ECN_flow_xmit(sk, fl6->flowlabel); if (!(transport->param_flags & SPP_PMTUD_ENABLE)) skb->local_df = 1; SCTP_INC_STATS(sock_net(sk), SCTP_MIB_OUTSCTPPACKS); return ip6_xmit(sk, skb, fl6, np->opt, np->tclass); } /* Returns the dst cache entry for the given source and destination ip * addresses. */ static void sctp_v6_get_dst(struct sctp_transport *t, union sctp_addr *saddr, struct flowi *fl, struct sock *sk) { struct sctp_association *asoc = t->asoc; struct dst_entry *dst = NULL; struct flowi6 *fl6 = &fl->u.ip6; struct sctp_bind_addr *bp; struct ipv6_pinfo *np = inet6_sk(sk); struct sctp_sockaddr_entry *laddr; union sctp_addr *baddr = NULL; union sctp_addr *daddr = &t->ipaddr; union sctp_addr dst_saddr; struct in6_addr *final_p, final; __u8 matchlen = 0; __u8 bmatchlen; sctp_scope_t scope; memset(fl6, 0, sizeof(struct flowi6)); fl6->daddr = daddr->v6.sin6_addr; fl6->fl6_dport = daddr->v6.sin6_port; fl6->flowi6_proto = IPPROTO_SCTP; if (ipv6_addr_type(&daddr->v6.sin6_addr) & IPV6_ADDR_LINKLOCAL) fl6->flowi6_oif = daddr->v6.sin6_scope_id; pr_debug("%s: dst=%pI6 ", __func__, &fl6->daddr); if (asoc) fl6->fl6_sport = htons(asoc->base.bind_addr.port); if (saddr) { fl6->saddr = saddr->v6.sin6_addr; fl6->fl6_sport = saddr->v6.sin6_port; pr_debug("src=%pI6 - ", &fl6->saddr); } final_p = fl6_update_dst(fl6, np->opt, &final); dst = ip6_dst_lookup_flow(sk, fl6, final_p, false); if (!asoc || saddr) goto out; bp = &asoc->base.bind_addr; scope = sctp_scope(daddr); /* ip6_dst_lookup has filled in the fl6->saddr for us. Check * to see if we can use it. */ if (!IS_ERR(dst)) { /* Walk through the bind address list and look for a bind * address that matches the source address of the returned dst. */ sctp_v6_to_addr(&dst_saddr, &fl6->saddr, htons(bp->port)); rcu_read_lock(); list_for_each_entry_rcu(laddr, &bp->address_list, list) { if (!laddr->valid || (laddr->state != SCTP_ADDR_SRC)) continue; /* Do not compare against v4 addrs */ if ((laddr->a.sa.sa_family == AF_INET6) && (sctp_v6_cmp_addr(&dst_saddr, &laddr->a))) { rcu_read_unlock(); goto out; } } rcu_read_unlock(); /* None of the bound addresses match the source address of the * dst. So release it. */ dst_release(dst); dst = NULL; } /* Walk through the bind address list and try to get the * best source address for a given destination. */ rcu_read_lock(); list_for_each_entry_rcu(laddr, &bp->address_list, list) { if (!laddr->valid) continue; if ((laddr->state == SCTP_ADDR_SRC) && (laddr->a.sa.sa_family == AF_INET6) && (scope <= sctp_scope(&laddr->a))) { bmatchlen = sctp_v6_addr_match_len(daddr, &laddr->a); if (!baddr || (matchlen < bmatchlen)) { baddr = &laddr->a; matchlen = bmatchlen; } } } rcu_read_unlock(); if (baddr) { fl6->saddr = baddr->v6.sin6_addr; fl6->fl6_sport = baddr->v6.sin6_port; final_p = fl6_update_dst(fl6, np->opt, &final); dst = ip6_dst_lookup_flow(sk, fl6, final_p, false); } out: if (!IS_ERR_OR_NULL(dst)) { struct rt6_info *rt; rt = (struct rt6_info *)dst; t->dst = dst; t->dst_cookie = rt->rt6i_node ? rt->rt6i_node->fn_sernum : 0; pr_debug("rt6_dst:%pI6 rt6_src:%pI6\n", &rt->rt6i_dst.addr, &fl6->saddr); } else { t->dst = NULL; pr_debug("no route\n"); } } /* Returns the number of consecutive initial bits that match in the 2 ipv6 * addresses. */ static inline int sctp_v6_addr_match_len(union sctp_addr *s1, union sctp_addr *s2) { return ipv6_addr_diff(&s1->v6.sin6_addr, &s2->v6.sin6_addr); } /* Fills in the source address(saddr) based on the destination address(daddr) * and asoc's bind address list. */ static void sctp_v6_get_saddr(struct sctp_sock *sk, struct sctp_transport *t, struct flowi *fl) { struct flowi6 *fl6 = &fl->u.ip6; union sctp_addr *saddr = &t->saddr; pr_debug("%s: asoc:%p dst:%p\n", __func__, t->asoc, t->dst); if (t->dst) { saddr->v6.sin6_family = AF_INET6; saddr->v6.sin6_addr = fl6->saddr; } } /* Make a copy of all potential local addresses. */ static void sctp_v6_copy_addrlist(struct list_head *addrlist, struct net_device *dev) { struct inet6_dev *in6_dev; struct inet6_ifaddr *ifp; struct sctp_sockaddr_entry *addr; rcu_read_lock(); if ((in6_dev = __in6_dev_get(dev)) == NULL) { rcu_read_unlock(); return; } read_lock_bh(&in6_dev->lock); list_for_each_entry(ifp, &in6_dev->addr_list, if_list) { /* Add the address to the local list. */ addr = kzalloc(sizeof(*addr), GFP_ATOMIC); if (addr) { addr->a.v6.sin6_family = AF_INET6; addr->a.v6.sin6_port = 0; addr->a.v6.sin6_addr = ifp->addr; addr->a.v6.sin6_scope_id = dev->ifindex; addr->valid = 1; INIT_LIST_HEAD(&addr->list); list_add_tail(&addr->list, addrlist); } } read_unlock_bh(&in6_dev->lock); rcu_read_unlock(); } /* Initialize a sockaddr_storage from in incoming skb. */ static void sctp_v6_from_skb(union sctp_addr *addr,struct sk_buff *skb, int is_saddr) { __be16 *port; struct sctphdr *sh; port = &addr->v6.sin6_port; addr->v6.sin6_family = AF_INET6; addr->v6.sin6_flowinfo = 0; /* FIXME */ addr->v6.sin6_scope_id = ((struct inet6_skb_parm *)skb->cb)->iif; sh = sctp_hdr(skb); if (is_saddr) { *port = sh->source; addr->v6.sin6_addr = ipv6_hdr(skb)->saddr; } else { *port = sh->dest; addr->v6.sin6_addr = ipv6_hdr(skb)->daddr; } } /* Initialize an sctp_addr from a socket. */ static void sctp_v6_from_sk(union sctp_addr *addr, struct sock *sk) { addr->v6.sin6_family = AF_INET6; addr->v6.sin6_port = 0; addr->v6.sin6_addr = inet6_sk(sk)->rcv_saddr; } /* Initialize sk->sk_rcv_saddr from sctp_addr. */ static void sctp_v6_to_sk_saddr(union sctp_addr *addr, struct sock *sk) { if (addr->sa.sa_family == AF_INET && sctp_sk(sk)->v4mapped) { inet6_sk(sk)->rcv_saddr.s6_addr32[0] = 0; inet6_sk(sk)->rcv_saddr.s6_addr32[1] = 0; inet6_sk(sk)->rcv_saddr.s6_addr32[2] = htonl(0x0000ffff); inet6_sk(sk)->rcv_saddr.s6_addr32[3] = addr->v4.sin_addr.s_addr; } else { inet6_sk(sk)->rcv_saddr = addr->v6.sin6_addr; } } /* Initialize sk->sk_daddr from sctp_addr. */ static void sctp_v6_to_sk_daddr(union sctp_addr *addr, struct sock *sk) { if (addr->sa.sa_family == AF_INET && sctp_sk(sk)->v4mapped) { inet6_sk(sk)->daddr.s6_addr32[0] = 0; inet6_sk(sk)->daddr.s6_addr32[1] = 0; inet6_sk(sk)->daddr.s6_addr32[2] = htonl(0x0000ffff); inet6_sk(sk)->daddr.s6_addr32[3] = addr->v4.sin_addr.s_addr; } else { inet6_sk(sk)->daddr = addr->v6.sin6_addr; } } /* Initialize a sctp_addr from an address parameter. */ static void sctp_v6_from_addr_param(union sctp_addr *addr, union sctp_addr_param *param, __be16 port, int iif) { addr->v6.sin6_family = AF_INET6; addr->v6.sin6_port = port; addr->v6.sin6_flowinfo = 0; /* BUG */ addr->v6.sin6_addr = param->v6.addr; addr->v6.sin6_scope_id = iif; } /* Initialize an address parameter from a sctp_addr and return the length * of the address parameter. */ static int sctp_v6_to_addr_param(const union sctp_addr *addr, union sctp_addr_param *param) { int length = sizeof(sctp_ipv6addr_param_t); param->v6.param_hdr.type = SCTP_PARAM_IPV6_ADDRESS; param->v6.param_hdr.length = htons(length); param->v6.addr = addr->v6.sin6_addr; return length; } /* Initialize a sctp_addr from struct in6_addr. */ static void sctp_v6_to_addr(union sctp_addr *addr, struct in6_addr *saddr, __be16 port) { addr->sa.sa_family = AF_INET6; addr->v6.sin6_port = port; addr->v6.sin6_addr = *saddr; } /* Compare addresses exactly. * v4-mapped-v6 is also in consideration. */ static int sctp_v6_cmp_addr(const union sctp_addr *addr1, const union sctp_addr *addr2) { if (addr1->sa.sa_family != addr2->sa.sa_family) { if (addr1->sa.sa_family == AF_INET && addr2->sa.sa_family == AF_INET6 && ipv6_addr_v4mapped(&addr2->v6.sin6_addr)) { if (addr2->v6.sin6_port == addr1->v4.sin_port && addr2->v6.sin6_addr.s6_addr32[3] == addr1->v4.sin_addr.s_addr) return 1; } if (addr2->sa.sa_family == AF_INET && addr1->sa.sa_family == AF_INET6 && ipv6_addr_v4mapped(&addr1->v6.sin6_addr)) { if (addr1->v6.sin6_port == addr2->v4.sin_port && addr1->v6.sin6_addr.s6_addr32[3] == addr2->v4.sin_addr.s_addr) return 1; } return 0; } if (!ipv6_addr_equal(&addr1->v6.sin6_addr, &addr2->v6.sin6_addr)) return 0; /* If this is a linklocal address, compare the scope_id. */ if (ipv6_addr_type(&addr1->v6.sin6_addr) & IPV6_ADDR_LINKLOCAL) { if (addr1->v6.sin6_scope_id && addr2->v6.sin6_scope_id && (addr1->v6.sin6_scope_id != addr2->v6.sin6_scope_id)) { return 0; } } return 1; } /* Initialize addr struct to INADDR_ANY. */ static void sctp_v6_inaddr_any(union sctp_addr *addr, __be16 port) { memset(addr, 0x00, sizeof(union sctp_addr)); addr->v6.sin6_family = AF_INET6; addr->v6.sin6_port = port; } /* Is this a wildcard address? */ static int sctp_v6_is_any(const union sctp_addr *addr) { return ipv6_addr_any(&addr->v6.sin6_addr); } /* Should this be available for binding? */ static int sctp_v6_available(union sctp_addr *addr, struct sctp_sock *sp) { int type; const struct in6_addr *in6 = (const struct in6_addr *)&addr->v6.sin6_addr; type = ipv6_addr_type(in6); if (IPV6_ADDR_ANY == type) return 1; if (type == IPV6_ADDR_MAPPED) { if (sp && !sp->v4mapped) return 0; if (sp && ipv6_only_sock(sctp_opt2sk(sp))) return 0; sctp_v6_map_v4(addr); return sctp_get_af_specific(AF_INET)->available(addr, sp); } if (!(type & IPV6_ADDR_UNICAST)) return 0; return ipv6_chk_addr(sock_net(&sp->inet.sk), in6, NULL, 0); } /* This function checks if the address is a valid address to be used for * SCTP. * * Output: * Return 0 - If the address is a non-unicast or an illegal address. * Return 1 - If the address is a unicast. */ static int sctp_v6_addr_valid(union sctp_addr *addr, struct sctp_sock *sp, const struct sk_buff *skb) { int ret = ipv6_addr_type(&addr->v6.sin6_addr); /* Support v4-mapped-v6 address. */ if (ret == IPV6_ADDR_MAPPED) { /* Note: This routine is used in input, so v4-mapped-v6 * are disallowed here when there is no sctp_sock. */ if (!sp || !sp->v4mapped) return 0; if (sp && ipv6_only_sock(sctp_opt2sk(sp))) return 0; sctp_v6_map_v4(addr); return sctp_get_af_specific(AF_INET)->addr_valid(addr, sp, skb); } /* Is this a non-unicast address */ if (!(ret & IPV6_ADDR_UNICAST)) return 0; return 1; } /* What is the scope of 'addr'? */ static sctp_scope_t sctp_v6_scope(union sctp_addr *addr) { int v6scope; sctp_scope_t retval; /* The IPv6 scope is really a set of bit fields. * See IFA_* in <net/if_inet6.h>. Map to a generic SCTP scope. */ v6scope = ipv6_addr_scope(&addr->v6.sin6_addr); switch (v6scope) { case IFA_HOST: retval = SCTP_SCOPE_LOOPBACK; break; case IFA_LINK: retval = SCTP_SCOPE_LINK; break; case IFA_SITE: retval = SCTP_SCOPE_PRIVATE; break; default: retval = SCTP_SCOPE_GLOBAL; break; } return retval; } /* Create and initialize a new sk for the socket to be returned by accept(). */ static struct sock *sctp_v6_create_accept_sk(struct sock *sk, struct sctp_association *asoc) { struct sock *newsk; struct ipv6_pinfo *newnp, *np = inet6_sk(sk); struct sctp6_sock *newsctp6sk; newsk = sk_alloc(sock_net(sk), PF_INET6, GFP_KERNEL, sk->sk_prot); if (!newsk) goto out; sock_init_data(NULL, newsk); sctp_copy_sock(newsk, sk, asoc); sock_reset_flag(sk, SOCK_ZAPPED); newsctp6sk = (struct sctp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newsctp6sk->inet6; sctp_sk(newsk)->v4mapped = sctp_sk(sk)->v4mapped; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); /* Initialize sk's sport, dport, rcv_saddr and daddr for getsockname() * and getpeername(). */ sctp_v6_to_sk_daddr(&asoc->peer.primary_addr, newsk); sk_refcnt_debug_inc(newsk); if (newsk->sk_prot->init(newsk)) { sk_common_release(newsk); newsk = NULL; } out: return newsk; } /* Map v4 address to mapped v6 address */ static void sctp_v6_addr_v4map(struct sctp_sock *sp, union sctp_addr *addr) { if (sp->v4mapped && AF_INET == addr->sa.sa_family) sctp_v4_map_v6(addr); } /* Where did this skb come from? */ static int sctp_v6_skb_iif(const struct sk_buff *skb) { struct inet6_skb_parm *opt = (struct inet6_skb_parm *) skb->cb; return opt->iif; } /* Was this packet marked by Explicit Congestion Notification? */ static int sctp_v6_is_ce(const struct sk_buff *skb) { return *((__u32 *)(ipv6_hdr(skb))) & htonl(1 << 20); } /* Dump the v6 addr to the seq file. */ static void sctp_v6_seq_dump_addr(struct seq_file *seq, union sctp_addr *addr) { seq_printf(seq, "%pI6 ", &addr->v6.sin6_addr); } static void sctp_v6_ecn_capable(struct sock *sk) { inet6_sk(sk)->tclass |= INET_ECN_ECT_0; } /* Initialize a PF_INET6 socket msg_name. */ static void sctp_inet6_msgname(char *msgname, int *addr_len) { struct sockaddr_in6 *sin6; sin6 = (struct sockaddr_in6 *)msgname; sin6->sin6_family = AF_INET6; sin6->sin6_flowinfo = 0; sin6->sin6_scope_id = 0; /*FIXME */ *addr_len = sizeof(struct sockaddr_in6); } /* Initialize a PF_INET msgname from a ulpevent. */ static void sctp_inet6_event_msgname(struct sctp_ulpevent *event, char *msgname, int *addrlen) { struct sockaddr_in6 *sin6, *sin6from; if (msgname) { union sctp_addr *addr; struct sctp_association *asoc; asoc = event->asoc; sctp_inet6_msgname(msgname, addrlen); sin6 = (struct sockaddr_in6 *)msgname; sin6->sin6_port = htons(asoc->peer.port); addr = &asoc->peer.primary_addr; /* Note: If we go to a common v6 format, this code * will change. */ /* Map ipv4 address into v4-mapped-on-v6 address. */ if (sctp_sk(asoc->base.sk)->v4mapped && AF_INET == addr->sa.sa_family) { sctp_v4_map_v6((union sctp_addr *)sin6); sin6->sin6_addr.s6_addr32[3] = addr->v4.sin_addr.s_addr; return; } sin6from = &asoc->peer.primary_addr.v6; sin6->sin6_addr = sin6from->sin6_addr; if (ipv6_addr_type(&sin6->sin6_addr) & IPV6_ADDR_LINKLOCAL) sin6->sin6_scope_id = sin6from->sin6_scope_id; } } /* Initialize a msg_name from an inbound skb. */ static void sctp_inet6_skb_msgname(struct sk_buff *skb, char *msgname, int *addr_len) { struct sctphdr *sh; struct sockaddr_in6 *sin6; if (msgname) { sctp_inet6_msgname(msgname, addr_len); sin6 = (struct sockaddr_in6 *)msgname; sh = sctp_hdr(skb); sin6->sin6_port = sh->source; /* Map ipv4 address into v4-mapped-on-v6 address. */ if (sctp_sk(skb->sk)->v4mapped && ip_hdr(skb)->version == 4) { sctp_v4_map_v6((union sctp_addr *)sin6); sin6->sin6_addr.s6_addr32[3] = ip_hdr(skb)->saddr; return; } /* Otherwise, just copy the v6 address. */ sin6->sin6_addr = ipv6_hdr(skb)->saddr; if (ipv6_addr_type(&sin6->sin6_addr) & IPV6_ADDR_LINKLOCAL) { struct sctp_ulpevent *ev = sctp_skb2event(skb); sin6->sin6_scope_id = ev->iif; } } } /* Do we support this AF? */ static int sctp_inet6_af_supported(sa_family_t family, struct sctp_sock *sp) { switch (family) { case AF_INET6: return 1; /* v4-mapped-v6 addresses */ case AF_INET: if (!__ipv6_only_sock(sctp_opt2sk(sp))) return 1; default: return 0; } } /* Address matching with wildcards allowed. This extra level * of indirection lets us choose whether a PF_INET6 should * disallow any v4 addresses if we so choose. */ static int sctp_inet6_cmp_addr(const union sctp_addr *addr1, const union sctp_addr *addr2, struct sctp_sock *opt) { struct sctp_af *af1, *af2; struct sock *sk = sctp_opt2sk(opt); af1 = sctp_get_af_specific(addr1->sa.sa_family); af2 = sctp_get_af_specific(addr2->sa.sa_family); if (!af1 || !af2) return 0; /* If the socket is IPv6 only, v4 addrs will not match */ if (__ipv6_only_sock(sk) && af1 != af2) return 0; /* Today, wildcard AF_INET/AF_INET6. */ if (sctp_is_any(sk, addr1) || sctp_is_any(sk, addr2)) return 1; if (addr1->sa.sa_family != addr2->sa.sa_family) return 0; return af1->cmp_addr(addr1, addr2); } /* Verify that the provided sockaddr looks bindable. Common verification, * has already been taken care of. */ static int sctp_inet6_bind_verify(struct sctp_sock *opt, union sctp_addr *addr) { struct sctp_af *af; /* ASSERT: address family has already been verified. */ if (addr->sa.sa_family != AF_INET6) af = sctp_get_af_specific(addr->sa.sa_family); else { int type = ipv6_addr_type(&addr->v6.sin6_addr); struct net_device *dev; if (type & IPV6_ADDR_LINKLOCAL) { struct net *net; if (!addr->v6.sin6_scope_id) return 0; net = sock_net(&opt->inet.sk); rcu_read_lock(); dev = dev_get_by_index_rcu(net, addr->v6.sin6_scope_id); if (!dev || !ipv6_chk_addr(net, &addr->v6.sin6_addr, dev, 0)) { rcu_read_unlock(); return 0; } rcu_read_unlock(); } else if (type == IPV6_ADDR_MAPPED) { if (!opt->v4mapped) return 0; } af = opt->pf->af; } return af->available(addr, opt); } /* Verify that the provided sockaddr looks sendable. Common verification, * has already been taken care of. */ static int sctp_inet6_send_verify(struct sctp_sock *opt, union sctp_addr *addr) { struct sctp_af *af = NULL; /* ASSERT: address family has already been verified. */ if (addr->sa.sa_family != AF_INET6) af = sctp_get_af_specific(addr->sa.sa_family); else { int type = ipv6_addr_type(&addr->v6.sin6_addr); struct net_device *dev; if (type & IPV6_ADDR_LINKLOCAL) { if (!addr->v6.sin6_scope_id) return 0; rcu_read_lock(); dev = dev_get_by_index_rcu(sock_net(&opt->inet.sk), addr->v6.sin6_scope_id); rcu_read_unlock(); if (!dev) return 0; } af = opt->pf->af; } return af != NULL; } /* Fill in Supported Address Type information for INIT and INIT-ACK * chunks. Note: In the future, we may want to look at sock options * to determine whether a PF_INET6 socket really wants to have IPV4 * addresses. * Returns number of addresses supported. */ static int sctp_inet6_supported_addrs(const struct sctp_sock *opt, __be16 *types) { types[0] = SCTP_PARAM_IPV6_ADDRESS; if (!opt || !ipv6_only_sock(sctp_opt2sk(opt))) { types[1] = SCTP_PARAM_IPV4_ADDRESS; return 2; } return 1; } static const struct proto_ops inet6_seqpacket_ops = { .family = PF_INET6, .owner = THIS_MODULE, .release = inet6_release, .bind = inet6_bind, .connect = inet_dgram_connect, .socketpair = sock_no_socketpair, .accept = inet_accept, .getname = inet6_getname, .poll = sctp_poll, .ioctl = inet6_ioctl, .listen = sctp_inet_listen, .shutdown = inet_shutdown, .setsockopt = sock_common_setsockopt, .getsockopt = sock_common_getsockopt, .sendmsg = inet_sendmsg, .recvmsg = sock_common_recvmsg, .mmap = sock_no_mmap, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_sock_common_setsockopt, .compat_getsockopt = compat_sock_common_getsockopt, #endif }; static struct inet_protosw sctpv6_seqpacket_protosw = { .type = SOCK_SEQPACKET, .protocol = IPPROTO_SCTP, .prot = &sctpv6_prot, .ops = &inet6_seqpacket_ops, .no_check = 0, .flags = SCTP_PROTOSW_FLAG }; static struct inet_protosw sctpv6_stream_protosw = { .type = SOCK_STREAM, .protocol = IPPROTO_SCTP, .prot = &sctpv6_prot, .ops = &inet6_seqpacket_ops, .no_check = 0, .flags = SCTP_PROTOSW_FLAG, }; static int sctp6_rcv(struct sk_buff *skb) { return sctp_rcv(skb) ? -1 : 0; } static const struct inet6_protocol sctpv6_protocol = { .handler = sctp6_rcv, .err_handler = sctp_v6_err, .flags = INET6_PROTO_NOPOLICY | INET6_PROTO_FINAL, }; static struct sctp_af sctp_af_inet6 = { .sa_family = AF_INET6, .sctp_xmit = sctp_v6_xmit, .setsockopt = ipv6_setsockopt, .getsockopt = ipv6_getsockopt, .get_dst = sctp_v6_get_dst, .get_saddr = sctp_v6_get_saddr, .copy_addrlist = sctp_v6_copy_addrlist, .from_skb = sctp_v6_from_skb, .from_sk = sctp_v6_from_sk, .to_sk_saddr = sctp_v6_to_sk_saddr, .to_sk_daddr = sctp_v6_to_sk_daddr, .from_addr_param = sctp_v6_from_addr_param, .to_addr_param = sctp_v6_to_addr_param, .cmp_addr = sctp_v6_cmp_addr, .scope = sctp_v6_scope, .addr_valid = sctp_v6_addr_valid, .inaddr_any = sctp_v6_inaddr_any, .is_any = sctp_v6_is_any, .available = sctp_v6_available, .skb_iif = sctp_v6_skb_iif, .is_ce = sctp_v6_is_ce, .seq_dump_addr = sctp_v6_seq_dump_addr, .ecn_capable = sctp_v6_ecn_capable, .net_header_len = sizeof(struct ipv6hdr), .sockaddr_len = sizeof(struct sockaddr_in6), #ifdef CONFIG_COMPAT .compat_setsockopt = compat_ipv6_setsockopt, .compat_getsockopt = compat_ipv6_getsockopt, #endif }; static struct sctp_pf sctp_pf_inet6 = { .event_msgname = sctp_inet6_event_msgname, .skb_msgname = sctp_inet6_skb_msgname, .af_supported = sctp_inet6_af_supported, .cmp_addr = sctp_inet6_cmp_addr, .bind_verify = sctp_inet6_bind_verify, .send_verify = sctp_inet6_send_verify, .supported_addrs = sctp_inet6_supported_addrs, .create_accept_sk = sctp_v6_create_accept_sk, .addr_v4map = sctp_v6_addr_v4map, .af = &sctp_af_inet6, }; /* Initialize IPv6 support and register with socket layer. */ void sctp_v6_pf_init(void) { /* Register the SCTP specific PF_INET6 functions. */ sctp_register_pf(&sctp_pf_inet6, PF_INET6); /* Register the SCTP specific AF_INET6 functions. */ sctp_register_af(&sctp_af_inet6); } void sctp_v6_pf_exit(void) { list_del(&sctp_af_inet6.list); } /* Initialize IPv6 support and register with socket layer. */ int sctp_v6_protosw_init(void) { int rc; rc = proto_register(&sctpv6_prot, 1); if (rc) return rc; /* Add SCTPv6(UDP and TCP style) to inetsw6 linked list. */ inet6_register_protosw(&sctpv6_seqpacket_protosw); inet6_register_protosw(&sctpv6_stream_protosw); return 0; } void sctp_v6_protosw_exit(void) { inet6_unregister_protosw(&sctpv6_seqpacket_protosw); inet6_unregister_protosw(&sctpv6_stream_protosw); proto_unregister(&sctpv6_prot); } /* Register with inet6 layer. */ int sctp_v6_add_protocol(void) { /* Register notifier for inet6 address additions/deletions. */ register_inet6addr_notifier(&sctp_inet6addr_notifier); if (inet6_add_protocol(&sctpv6_protocol, IPPROTO_SCTP) < 0) return -EAGAIN; return 0; } /* Unregister with inet6 layer. */ void sctp_v6_del_protocol(void) { inet6_del_protocol(&sctpv6_protocol, IPPROTO_SCTP); unregister_inet6addr_notifier(&sctp_inet6addr_notifier); }
./CrossVul/dataset_final_sorted/CWE-310/c/good_5741_0
crossvul-cpp_data_good_5867_0
/* X-Chat * Copyright (C) 1998 Peter Zelezny. * * 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 St, Fifth Floor, Boston, MA 02110-1301, USA * * MS Proxy (ISA server) support is (c) 2006 Pavel Fedin <sonic_amiga@rambler.ru> * based on Dante source code * Copyright (c) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 * Inferno Nettverk A/S, Norway. All rights reserved. */ /*#define DEBUG_MSPROXY*/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <fcntl.h> #define WANTSOCKET #define WANTARPA #include "inet.h" #ifdef WIN32 #include <winbase.h> #include <io.h> #else #include <signal.h> #include <sys/wait.h> #include <unistd.h> #endif #include "hexchat.h" #include "fe.h" #include "cfgfiles.h" #include "network.h" #include "notify.h" #include "hexchatc.h" #include "inbound.h" #include "outbound.h" #include "text.h" #include "util.h" #include "url.h" #include "proto-irc.h" #include "servlist.h" #include "server.h" #ifdef USE_OPENSSL #include <openssl/ssl.h> /* SSL_() */ #include <openssl/err.h> /* ERR_() */ #include "ssl.h" #endif #ifdef USE_MSPROXY #include "msproxy.h" #endif #ifdef WIN32 #include "identd.h" #endif #ifdef USE_LIBPROXY #include <proxy.h> #endif #ifdef USE_OPENSSL /* local variables */ static struct session *g_sess = NULL; #endif static GSList *away_list = NULL; GSList *serv_list = NULL; static void auto_reconnect (server *serv, int send_quit, int err); static void server_disconnect (session * sess, int sendquit, int err); static int server_cleanup (server * serv); static void server_connect (server *serv, char *hostname, int port, int no_login); #ifdef USE_LIBPROXY extern pxProxyFactory *libproxy_factory; #endif /* actually send to the socket. This might do a character translation or send via SSL. server/dcc both use this function. */ int tcp_send_real (void *ssl, int sok, char *encoding, int using_irc, char *buf, int len) { int ret; char *locale; gsize loc_len; if (encoding == NULL) /* system */ { locale = NULL; if (!prefs.utf8_locale) { const gchar *charset; g_get_charset (&charset); locale = g_convert_with_fallback (buf, len, charset, "UTF-8", "?", 0, &loc_len, 0); } } else { if (using_irc) /* using "IRC" encoding (CP1252/UTF-8 hybrid) */ /* if all chars fit inside CP1252, use that. Otherwise this returns NULL and we send UTF-8. */ locale = g_convert (buf, len, "CP1252", "UTF-8", 0, &loc_len, 0); else locale = g_convert_with_fallback (buf, len, encoding, "UTF-8", "?", 0, &loc_len, 0); } if (locale) { len = loc_len; #ifdef USE_OPENSSL if (!ssl) ret = send (sok, locale, len, 0); else ret = _SSL_send (ssl, locale, len); #else ret = send (sok, locale, len, 0); #endif g_free (locale); } else { #ifdef USE_OPENSSL if (!ssl) ret = send (sok, buf, len, 0); else ret = _SSL_send (ssl, buf, len); #else ret = send (sok, buf, len, 0); #endif } return ret; } static int server_send_real (server *serv, char *buf, int len) { fe_add_rawlog (serv, buf, len, TRUE); url_check_line (buf, len); return tcp_send_real (serv->ssl, serv->sok, serv->encoding, serv->using_irc, buf, len); } /* new throttling system, uses the same method as the Undernet ircu2.10 server; under test, a 200-line paste didn't flood off the client */ static int tcp_send_queue (server *serv) { char *buf, *p; int len, i, pri; GSList *list; time_t now = time (0); /* did the server close since the timeout was added? */ if (!is_server (serv)) return 0; /* try priority 2,1,0 */ pri = 2; while (pri >= 0) { list = serv->outbound_queue; while (list) { buf = (char *) list->data; if (buf[0] == pri) { buf++; /* skip the priority byte */ len = strlen (buf); if (serv->next_send < now) serv->next_send = now; if (serv->next_send - now >= 10) { /* check for clock skew */ if (now >= serv->prev_now) return 1; /* don't remove the timeout handler */ /* it is skewed, reset to something sane */ serv->next_send = now; } for (p = buf, i = len; i && *p != ' '; p++, i--); serv->next_send += (2 + i / 120); serv->sendq_len -= len; serv->prev_now = now; fe_set_throttle (serv); server_send_real (serv, buf, len); buf--; serv->outbound_queue = g_slist_remove (serv->outbound_queue, buf); free (buf); list = serv->outbound_queue; } else { list = list->next; } } /* now try pri 0 */ pri--; } return 0; /* remove the timeout handler */ } int tcp_send_len (server *serv, char *buf, int len) { char *dbuf; int noqueue = !serv->outbound_queue; if (!prefs.hex_net_throttle) return server_send_real (serv, buf, len); dbuf = malloc (len + 2); /* first byte is the priority */ dbuf[0] = 2; /* pri 2 for most things */ memcpy (dbuf + 1, buf, len); dbuf[len + 1] = 0; /* privmsg and notice get a lower priority */ if (g_ascii_strncasecmp (dbuf + 1, "PRIVMSG", 7) == 0 || g_ascii_strncasecmp (dbuf + 1, "NOTICE", 6) == 0) { dbuf[0] = 1; } else { /* WHO/MODE get the lowest priority */ if (g_ascii_strncasecmp (dbuf + 1, "WHO ", 4) == 0 || /* but only MODE queries, not changes */ (g_ascii_strncasecmp (dbuf + 1, "MODE", 4) == 0 && strchr (dbuf, '-') == NULL && strchr (dbuf, '+') == NULL)) dbuf[0] = 0; } serv->outbound_queue = g_slist_append (serv->outbound_queue, dbuf); serv->sendq_len += len; /* tcp_send_queue uses strlen */ if (tcp_send_queue (serv) && noqueue) fe_timeout_add (500, tcp_send_queue, serv); return 1; } /*int tcp_send (server *serv, char *buf) { return tcp_send_len (serv, buf, strlen (buf)); }*/ void tcp_sendf (server *serv, const char *fmt, ...) { va_list args; /* keep this buffer in BSS. Converting UTF-8 to ISO-8859-x might make the string shorter, so allow alot more than 512 for now. */ static char send_buf[1540]; /* good code hey (no it's not overflowable) */ int len; va_start (args, fmt); len = vsnprintf (send_buf, sizeof (send_buf) - 1, fmt, args); va_end (args); send_buf[sizeof (send_buf) - 1] = '\0'; if (len < 0 || len > (sizeof (send_buf) - 1)) len = strlen (send_buf); tcp_send_len (serv, send_buf, len); } static int close_socket_cb (gpointer sok) { closesocket (GPOINTER_TO_INT (sok)); return 0; } static void close_socket (int sok) { /* close the socket in 5 seconds so the QUIT message is not lost */ fe_timeout_add (5000, close_socket_cb, GINT_TO_POINTER (sok)); } /* handle 1 line of text received from the server */ static void server_inline (server *serv, char *line, int len) { char *utf_line_allocated = NULL; /* Checks whether we're set to use UTF-8 charset */ if (serv->using_irc || /* 1. using CP1252/UTF-8 Hybrid */ (serv->encoding == NULL && prefs.utf8_locale) || /* OR 2. using system default->UTF-8 */ (serv->encoding != NULL && /* OR 3. explicitly set to UTF-8 */ (g_ascii_strcasecmp (serv->encoding, "UTF8") == 0 || g_ascii_strcasecmp (serv->encoding, "UTF-8") == 0))) { /* The user has the UTF-8 charset set, either via /charset command or from his UTF-8 locale. Thus, we first try the UTF-8 charset, and if we fail to convert, we assume it to be ISO-8859-1 (see text_validate). */ utf_line_allocated = text_validate (&line, &len); } else { /* Since the user has an explicit charset set, either via /charset command or from his non-UTF8 locale, we don't fallback to ISO-8859-1 and instead try to remove errnoeous octets till the string is convertable in the said charset. */ const char *encoding = NULL; if (serv->encoding != NULL) encoding = serv->encoding; else g_get_charset (&encoding); if (encoding != NULL) { char *conv_line; /* holds a copy of the original string */ int conv_len; /* tells g_convert how much of line to convert */ gsize utf_len; gsize read_len; GError *err; gboolean retry; conv_line = g_malloc (len + 1); memcpy (conv_line, line, len); conv_line[len] = 0; conv_len = len; /* if CP1255, convert it with the NUL terminator. Works around SF bug #1122089 */ if (serv->using_cp1255) conv_len++; do { err = NULL; retry = FALSE; utf_line_allocated = g_convert_with_fallback (conv_line, conv_len, "UTF-8", encoding, "?", &read_len, &utf_len, &err); if (err != NULL) { if (err->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE && conv_len > (read_len + 1)) { /* Make our best bet by removing the erroneous char. This will work for casual 8-bit strings with non-standard chars. */ memmove (conv_line + read_len, conv_line + read_len + 1, conv_len - read_len -1); conv_len--; retry = TRUE; } g_error_free (err); } } while (retry); g_free (conv_line); /* If any conversion has occured at all. Conversion might fail due to errors other than invalid sequences, e.g. unknown charset. */ if (utf_line_allocated != NULL) { line = utf_line_allocated; len = utf_len; if (serv->using_cp1255 && len > 0) len--; } else { /* If all fails, treat as UTF-8 with fallback to ISO-8859-1. */ utf_line_allocated = text_validate (&line, &len); } } } fe_add_rawlog (serv, line, len, FALSE); /* let proto-irc.c handle it */ serv->p_inline (serv, line, len); if (utf_line_allocated != NULL) /* only if a special copy was allocated */ g_free (utf_line_allocated); } /* read data from socket */ static gboolean server_read (GIOChannel *source, GIOCondition condition, server *serv) { int sok = serv->sok; int error, i, len; char lbuf[2050]; while (1) { #ifdef USE_OPENSSL if (!serv->ssl) #endif len = recv (sok, lbuf, sizeof (lbuf) - 2, 0); #ifdef USE_OPENSSL else len = _SSL_recv (serv->ssl, lbuf, sizeof (lbuf) - 2); #endif if (len < 1) { error = 0; if (len < 0) { if (would_block ()) return TRUE; error = sock_error (); } if (!serv->end_of_motd) { server_disconnect (serv->server_session, FALSE, error); if (!servlist_cycle (serv)) { if (prefs.hex_net_auto_reconnect) auto_reconnect (serv, FALSE, error); } } else { if (prefs.hex_net_auto_reconnect) auto_reconnect (serv, FALSE, error); else server_disconnect (serv->server_session, FALSE, error); } return TRUE; } i = 0; lbuf[len] = 0; while (i < len) { switch (lbuf[i]) { case '\r': break; case '\n': serv->linebuf[serv->pos] = 0; server_inline (serv, serv->linebuf, serv->pos); serv->pos = 0; break; default: serv->linebuf[serv->pos] = lbuf[i]; if (serv->pos >= (sizeof (serv->linebuf) - 1)) fprintf (stderr, "*** HEXCHAT WARNING: Buffer overflow - shit server!\n"); else serv->pos++; } i++; } } } static void server_connected (server * serv) { prefs.wait_on_exit = TRUE; serv->ping_recv = time (0); serv->lag_sent = 0; serv->connected = TRUE; set_nonblocking (serv->sok); serv->iotag = fe_input_add (serv->sok, FIA_READ|FIA_EX, server_read, serv); if (!serv->no_login) { EMIT_SIGNAL (XP_TE_CONNECTED, serv->server_session, NULL, NULL, NULL, NULL, 0); if (serv->network) { serv->p_login (serv, (!(((ircnet *)serv->network)->flags & FLAG_USE_GLOBAL) && (((ircnet *)serv->network)->user)) ? (((ircnet *)serv->network)->user) : prefs.hex_irc_user_name, (!(((ircnet *)serv->network)->flags & FLAG_USE_GLOBAL) && (((ircnet *)serv->network)->real)) ? (((ircnet *)serv->network)->real) : prefs.hex_irc_real_name); } else { serv->p_login (serv, prefs.hex_irc_user_name, prefs.hex_irc_real_name); } } else { EMIT_SIGNAL (XP_TE_SERVERCONNECTED, serv->server_session, NULL, NULL, NULL, NULL, 0); } server_set_name (serv, serv->servername); fe_server_event (serv, FE_SE_CONNECT, 0); } #ifdef WIN32 static gboolean server_close_pipe (int *pipefd) /* see comments below */ { close (pipefd[0]); /* close WRITE end first to cause an EOF on READ */ close (pipefd[1]); /* in giowin32, and end that thread. */ free (pipefd); return FALSE; } #endif static void server_stopconnecting (server * serv) { if (serv->iotag) { fe_input_remove (serv->iotag); serv->iotag = 0; } if (serv->joindelay_tag) { fe_timeout_remove (serv->joindelay_tag); serv->joindelay_tag = 0; } #ifndef WIN32 /* kill the child process trying to connect */ kill (serv->childpid, SIGKILL); waitpid (serv->childpid, NULL, 0); close (serv->childwrite); close (serv->childread); #else PostThreadMessage (serv->childpid, WM_QUIT, 0, 0); { /* if we close the pipe now, giowin32 will crash. */ int *pipefd = malloc (sizeof (int) * 2); pipefd[0] = serv->childwrite; pipefd[1] = serv->childread; g_idle_add ((GSourceFunc)server_close_pipe, pipefd); } #endif #ifdef USE_OPENSSL if (serv->ssl_do_connect_tag) { fe_timeout_remove (serv->ssl_do_connect_tag); serv->ssl_do_connect_tag = 0; } #endif fe_progressbar_end (serv); serv->connecting = FALSE; fe_server_event (serv, FE_SE_DISCONNECT, 0); } #ifdef USE_OPENSSL #define SSLTMOUT 90 /* seconds */ static void ssl_cb_info (SSL * s, int where, int ret) { /* char buf[128];*/ return; /* FIXME: make debug level adjustable in serverlist or settings */ /* snprintf (buf, sizeof (buf), "%s (%d)", SSL_state_string_long (s), where); if (g_sess) EMIT_SIGNAL (XP_TE_SSLMESSAGE, g_sess, buf, NULL, NULL, NULL, 0); else fprintf (stderr, "%s\n", buf);*/ } static int ssl_cb_verify (int ok, X509_STORE_CTX * ctx) { char subject[256]; char issuer[256]; char buf[512]; X509_NAME_oneline (X509_get_subject_name (ctx->current_cert), subject, sizeof (subject)); X509_NAME_oneline (X509_get_issuer_name (ctx->current_cert), issuer, sizeof (issuer)); snprintf (buf, sizeof (buf), "* Subject: %s", subject); EMIT_SIGNAL (XP_TE_SSLMESSAGE, g_sess, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), "* Issuer: %s", issuer); EMIT_SIGNAL (XP_TE_SSLMESSAGE, g_sess, buf, NULL, NULL, NULL, 0); return (TRUE); /* always ok */ } static int ssl_do_connect (server * serv) { char buf[128]; g_sess = serv->server_session; if (SSL_connect (serv->ssl) <= 0) { char err_buf[128]; int err; g_sess = NULL; if ((err = ERR_get_error ()) > 0) { ERR_error_string (err, err_buf); snprintf (buf, sizeof (buf), "(%d) %s", err, err_buf); EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); if (ERR_GET_REASON (err) == SSL_R_WRONG_VERSION_NUMBER) PrintText (serv->server_session, _("Are you sure this is a SSL capable server and port?\n")); server_cleanup (serv); if (prefs.hex_net_auto_reconnectonfail) auto_reconnect (serv, FALSE, -1); return (0); /* remove it (0) */ } } g_sess = NULL; if (SSL_is_init_finished (serv->ssl)) { struct cert_info cert_info; struct chiper_info *chiper_info; int verify_error; int i; if (!_SSL_get_cert_info (&cert_info, serv->ssl)) { snprintf (buf, sizeof (buf), "* Certification info:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Subject:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); for (i = 0; cert_info.subject_word[i]; i++) { snprintf (buf, sizeof (buf), " %s", cert_info.subject_word[i]); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } snprintf (buf, sizeof (buf), " Issuer:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); for (i = 0; cert_info.issuer_word[i]; i++) { snprintf (buf, sizeof (buf), " %s", cert_info.issuer_word[i]); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } snprintf (buf, sizeof (buf), " Public key algorithm: %s (%d bits)", cert_info.algorithm, cert_info.algorithm_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); /*if (cert_info.rsa_tmp_bits) { snprintf (buf, sizeof (buf), " Public key algorithm uses ephemeral key with %d bits", cert_info.rsa_tmp_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); }*/ snprintf (buf, sizeof (buf), " Sign algorithm %s", cert_info.sign_algorithm/*, cert_info.sign_algorithm_bits*/); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Valid since %s to %s", cert_info.notbefore, cert_info.notafter); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } else { snprintf (buf, sizeof (buf), " * No Certificate"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } chiper_info = _SSL_get_cipher_info (serv->ssl); /* static buffer */ snprintf (buf, sizeof (buf), "* Cipher info:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Version: %s, cipher %s (%u bits)", chiper_info->version, chiper_info->chiper, chiper_info->chiper_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); verify_error = SSL_get_verify_result (serv->ssl); switch (verify_error) { case X509_V_OK: { X509 *cert = SSL_get_peer_certificate (serv->ssl); int hostname_err; if ((hostname_err = _SSL_check_hostname(cert, serv->hostname)) != 0) { snprintf (buf, sizeof (buf), "* Verify E: Failed to validate hostname? (%d)%s", hostname_err, serv->accept_invalid_cert ? " -- Ignored" : ""); if (serv->accept_invalid_cert) EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); else goto conn_fail; } break; } /* snprintf (buf, sizeof (buf), "* Verify OK (?)"); */ /* EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); */ case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: case X509_V_ERR_CERT_HAS_EXPIRED: if (serv->accept_invalid_cert) { snprintf (buf, sizeof (buf), "* Verify E: %s.? (%d) -- Ignored", X509_verify_cert_error_string (verify_error), verify_error); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); break; } default: snprintf (buf, sizeof (buf), "%s.? (%d)", X509_verify_cert_error_string (verify_error), verify_error); conn_fail: EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); server_cleanup (serv); return (0); } server_stopconnecting (serv); /* activate gtk poll */ server_connected (serv); return (0); /* remove it (0) */ } else { if (serv->ssl->session && serv->ssl->session->time + SSLTMOUT < time (NULL)) { snprintf (buf, sizeof (buf), "SSL handshake timed out"); EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); server_cleanup (serv); /* ->connecting = FALSE */ if (prefs.hex_net_auto_reconnectonfail) auto_reconnect (serv, FALSE, -1); return (0); /* remove it (0) */ } return (1); /* call it more (1) */ } } #endif static int timeout_auto_reconnect (server *serv) { if (is_server (serv)) /* make sure it hasnt been closed during the delay */ { serv->recondelay_tag = 0; if (!serv->connected && !serv->connecting && serv->server_session) { server_connect (serv, serv->hostname, serv->port, FALSE); } } return 0; /* returning 0 should remove the timeout handler */ } static void auto_reconnect (server *serv, int send_quit, int err) { session *s; GSList *list; int del; if (serv->server_session == NULL) return; list = sess_list; while (list) /* make sure auto rejoin can work */ { s = list->data; if (s->type == SESS_CHANNEL && s->channel[0]) { strcpy (s->waitchannel, s->channel); strcpy (s->willjoinchannel, s->channel); } list = list->next; } if (serv->connected) server_disconnect (serv->server_session, send_quit, err); del = prefs.hex_net_reconnect_delay * 1000; if (del < 1000) del = 500; /* so it doesn't block the gui */ #ifndef WIN32 if (err == -1 || err == 0 || err == ECONNRESET || err == ETIMEDOUT) #else if (err == -1 || err == 0 || err == WSAECONNRESET || err == WSAETIMEDOUT) #endif serv->reconnect_away = serv->is_away; /* is this server in a reconnect delay? remove it! */ if (serv->recondelay_tag) { fe_timeout_remove (serv->recondelay_tag); serv->recondelay_tag = 0; } serv->recondelay_tag = fe_timeout_add (del, timeout_auto_reconnect, serv); fe_server_event (serv, FE_SE_RECONDELAY, del); } static void server_flush_queue (server *serv) { list_free (&serv->outbound_queue); serv->sendq_len = 0; fe_set_throttle (serv); } /* connect() successed */ static void server_connect_success (server *serv) { #ifdef USE_OPENSSL #define SSLDOCONNTMOUT 300 if (serv->use_ssl) { char *err; /* it'll be a memory leak, if connection isn't terminated by server_cleanup() */ serv->ssl = _SSL_socket (serv->ctx, serv->sok); if ((err = _SSL_set_verify (serv->ctx, ssl_cb_verify, NULL))) { EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, err, NULL, NULL, NULL, 0); server_cleanup (serv); /* ->connecting = FALSE */ return; } /* FIXME: it'll be needed by new servers */ /* send(serv->sok, "STLS\r\n", 6, 0); sleep(1); */ set_nonblocking (serv->sok); serv->ssl_do_connect_tag = fe_timeout_add (SSLDOCONNTMOUT, ssl_do_connect, serv); return; } serv->ssl = NULL; #endif server_stopconnecting (serv); /* ->connecting = FALSE */ /* activate glib poll */ server_connected (serv); } /* receive info from the child-process about connection progress */ static gboolean server_read_child (GIOChannel *source, GIOCondition condition, server *serv) { session *sess = serv->server_session; char tbuf[128]; char outbuf[512]; char host[100]; char ip[100]; #ifdef USE_MSPROXY char *p; #endif waitline2 (source, tbuf, sizeof tbuf); switch (tbuf[0]) { case '0': /* print some text */ waitline2 (source, tbuf, sizeof tbuf); PrintText (serv->server_session, tbuf); break; case '1': /* unknown host */ server_stopconnecting (serv); closesocket (serv->sok4); if (serv->proxy_sok4 != -1) closesocket (serv->proxy_sok4); #ifdef USE_IPV6 if (serv->sok6 != -1) closesocket (serv->sok6); if (serv->proxy_sok6 != -1) closesocket (serv->proxy_sok6); #endif EMIT_SIGNAL (XP_TE_UKNHOST, sess, NULL, NULL, NULL, NULL, 0); if (!servlist_cycle (serv)) if (prefs.hex_net_auto_reconnectonfail) auto_reconnect (serv, FALSE, -1); break; case '2': /* connection failed */ waitline2 (source, tbuf, sizeof tbuf); server_stopconnecting (serv); closesocket (serv->sok4); if (serv->proxy_sok4 != -1) closesocket (serv->proxy_sok4); #ifdef USE_IPV6 if (serv->sok6 != -1) closesocket (serv->sok6); if (serv->proxy_sok6 != -1) closesocket (serv->proxy_sok6); #endif EMIT_SIGNAL (XP_TE_CONNFAIL, sess, errorstring (atoi (tbuf)), NULL, NULL, NULL, 0); if (!servlist_cycle (serv)) if (prefs.hex_net_auto_reconnectonfail) auto_reconnect (serv, FALSE, -1); break; case '3': /* gethostbyname finished */ waitline2 (source, host, sizeof host); waitline2 (source, ip, sizeof ip); waitline2 (source, outbuf, sizeof outbuf); EMIT_SIGNAL (XP_TE_CONNECT, sess, host, ip, outbuf, NULL, 0); #ifdef WIN32 if (prefs.hex_identd) { if (serv->network && ((ircnet *)serv->network)->user) { identd_start (((ircnet *)serv->network)->user); } else { identd_start (prefs.hex_irc_user_name); } } #else snprintf (outbuf, sizeof (outbuf), "%s/auth/xchat_auth", g_get_home_dir ()); if (access (outbuf, X_OK) == 0) { snprintf (outbuf, sizeof (outbuf), "exec -d %s/auth/xchat_auth %s", g_get_home_dir (), prefs.hex_irc_user_name); handle_command (serv->server_session, outbuf, FALSE); } #endif break; case '4': /* success */ waitline2 (source, tbuf, sizeof (tbuf)); #ifdef USE_MSPROXY serv->sok = strtol (tbuf, &p, 10); if (*p++ == ' ') { serv->proxy_sok = strtol (p, &p, 10); serv->msp_state.clientid = strtol (++p, &p, 10); serv->msp_state.serverid = strtol (++p, &p, 10); serv->msp_state.seq_sent = atoi (++p); } else serv->proxy_sok = -1; #ifdef DEBUG_MSPROXY printf ("Parent got main socket: %d, proxy socket: %d\n", serv->sok, serv->proxy_sok); printf ("Client ID 0x%08x server ID 0x%08x seq_sent %d\n", serv->msp_state.clientid, serv->msp_state.serverid, serv->msp_state.seq_sent); #endif #else serv->sok = atoi (tbuf); #endif #ifdef USE_IPV6 /* close the one we didn't end up using */ if (serv->sok == serv->sok4) closesocket (serv->sok6); else closesocket (serv->sok4); if (serv->proxy_sok != -1) { if (serv->proxy_sok == serv->proxy_sok4) closesocket (serv->proxy_sok6); else closesocket (serv->proxy_sok4); } #endif server_connect_success (serv); break; case '5': /* prefs ip discovered */ waitline2 (source, tbuf, sizeof tbuf); prefs.local_ip = inet_addr (tbuf); break; case '7': /* gethostbyname (prefs.hex_net_bind_host) failed */ sprintf (outbuf, _("Cannot resolve hostname %s\nCheck your IP Settings!\n"), prefs.hex_net_bind_host); PrintText (sess, outbuf); break; case '8': PrintText (sess, _("Proxy traversal failed.\n")); server_disconnect (sess, FALSE, -1); break; case '9': waitline2 (source, tbuf, sizeof tbuf); EMIT_SIGNAL (XP_TE_SERVERLOOKUP, sess, tbuf, NULL, NULL, NULL, 0); break; } return TRUE; } /* kill all sockets & iotags of a server. Stop a connection attempt, or disconnect if already connected. */ static int server_cleanup (server * serv) { fe_set_lag (serv, 0); if (serv->iotag) { fe_input_remove (serv->iotag); serv->iotag = 0; } if (serv->joindelay_tag) { fe_timeout_remove (serv->joindelay_tag); serv->joindelay_tag = 0; } #ifdef USE_OPENSSL if (serv->ssl) { SSL_shutdown (serv->ssl); SSL_free (serv->ssl); serv->ssl = NULL; } #endif if (serv->connecting) { server_stopconnecting (serv); closesocket (serv->sok4); if (serv->proxy_sok4 != -1) closesocket (serv->proxy_sok4); if (serv->sok6 != -1) closesocket (serv->sok6); if (serv->proxy_sok6 != -1) closesocket (serv->proxy_sok6); return 1; } if (serv->connected) { close_socket (serv->sok); if (serv->proxy_sok) close_socket (serv->proxy_sok); serv->connected = FALSE; serv->end_of_motd = FALSE; return 2; } /* is this server in a reconnect delay? remove it! */ if (serv->recondelay_tag) { fe_timeout_remove (serv->recondelay_tag); serv->recondelay_tag = 0; return 3; } return 0; } static void server_disconnect (session * sess, int sendquit, int err) { server *serv = sess->server; GSList *list; char tbuf[64]; gboolean shutup = FALSE; /* send our QUIT reason */ if (sendquit && serv->connected) { server_sendquit (sess); } fe_server_event (serv, FE_SE_DISCONNECT, 0); /* close all sockets & io tags */ switch (server_cleanup (serv)) { case 0: /* it wasn't even connected! */ notc_msg (sess); return; case 1: /* it was in the process of connecting */ sprintf (tbuf, "%d", sess->server->childpid); EMIT_SIGNAL (XP_TE_STOPCONNECT, sess, tbuf, NULL, NULL, NULL, 0); return; case 3: shutup = TRUE; /* won't print "disconnected" in channels */ } server_flush_queue (serv); list = sess_list; while (list) { sess = (struct session *) list->data; if (sess->server == serv) { if (!shutup || sess->type == SESS_SERVER) /* print "Disconnected" to each window using this server */ EMIT_SIGNAL (XP_TE_DISCON, sess, errorstring (err), NULL, NULL, NULL, 0); if (!sess->channel[0] || sess->type == SESS_CHANNEL) clear_channel (sess); } list = list->next; } serv->pos = 0; serv->motd_skipped = FALSE; serv->no_login = FALSE; serv->servername[0] = 0; serv->lag_sent = 0; notify_cleanup (); } /* send a "print text" command to the parent process - MUST END IN \n! */ static void proxy_error (int fd, char *msg) { write (fd, "0\n", 2); write (fd, msg, strlen (msg)); } struct sock_connect { char version; char type; guint16 port; guint32 address; char username[10]; }; /* traverse_socks() returns: * 0 success * * 1 socks traversal failed */ static int traverse_socks (int print_fd, int sok, char *serverAddr, int port) { struct sock_connect sc; unsigned char buf[256]; sc.version = 4; sc.type = 1; sc.port = htons (port); sc.address = inet_addr (serverAddr); strncpy (sc.username, prefs.hex_irc_user_name, 9); send (sok, (char *) &sc, 8 + strlen (sc.username) + 1, 0); buf[1] = 0; recv (sok, buf, 10, 0); if (buf[1] == 90) return 0; snprintf (buf, sizeof (buf), "SOCKS\tServer reported error %d,%d.\n", buf[0], buf[1]); proxy_error (print_fd, buf); return 1; } struct sock5_connect1 { char version; char nmethods; char method; }; static int traverse_socks5 (int print_fd, int sok, char *serverAddr, int port) { struct sock5_connect1 sc1; unsigned char *sc2; unsigned int packetlen, addrlen; unsigned char buf[260]; int auth = prefs.hex_net_proxy_auth && prefs.hex_net_proxy_user[0] && prefs.hex_net_proxy_pass[0]; sc1.version = 5; sc1.nmethods = 1; if (auth) sc1.method = 2; /* Username/Password Authentication (UPA) */ else sc1.method = 0; /* NO Authentication */ send (sok, (char *) &sc1, 3, 0); if (recv (sok, buf, 2, 0) != 2) goto read_error; if (buf[0] != 5) { proxy_error (print_fd, "SOCKS\tServer is not socks version 5.\n"); return 1; } /* did the server say no auth required? */ if (buf[1] == 0) auth = 0; if (auth) { int len_u=0, len_p=0; /* authentication sub-negotiation (RFC1929) */ if (buf[1] != 2) /* UPA not supported by server */ { proxy_error (print_fd, "SOCKS\tServer doesn't support UPA authentication.\n"); return 1; } memset (buf, 0, sizeof(buf)); /* form the UPA request */ len_u = strlen (prefs.hex_net_proxy_user); len_p = strlen (prefs.hex_net_proxy_pass); buf[0] = 1; buf[1] = len_u; memcpy (buf + 2, prefs.hex_net_proxy_user, len_u); buf[2 + len_u] = len_p; memcpy (buf + 3 + len_u, prefs.hex_net_proxy_pass, len_p); send (sok, buf, 3 + len_u + len_p, 0); if ( recv (sok, buf, 2, 0) != 2 ) goto read_error; if ( buf[1] != 0 ) { proxy_error (print_fd, "SOCKS\tAuthentication failed. " "Is username and password correct?\n"); return 1; /* UPA failed! */ } } else { if (buf[1] != 0) { proxy_error (print_fd, "SOCKS\tAuthentication required but disabled in settings.\n"); return 1; } } addrlen = strlen (serverAddr); packetlen = 4 + 1 + addrlen + 2; sc2 = malloc (packetlen); sc2[0] = 5; /* version */ sc2[1] = 1; /* command */ sc2[2] = 0; /* reserved */ sc2[3] = 3; /* address type */ sc2[4] = (unsigned char) addrlen; /* hostname length */ memcpy (sc2 + 5, serverAddr, addrlen); *((unsigned short *) (sc2 + 5 + addrlen)) = htons (port); send (sok, sc2, packetlen, 0); free (sc2); /* consume all of the reply */ if (recv (sok, buf, 4, 0) != 4) goto read_error; if (buf[0] != 5 || buf[1] != 0) { if (buf[1] == 2) snprintf (buf, sizeof (buf), "SOCKS\tProxy refused to connect to host (not allowed).\n"); else snprintf (buf, sizeof (buf), "SOCKS\tProxy failed to connect to host (error %d).\n", buf[1]); proxy_error (print_fd, buf); return 1; } if (buf[3] == 1) /* IPV4 32bit address */ { if (recv (sok, buf, 6, 0) != 6) goto read_error; } else if (buf[3] == 4) /* IPV6 128bit address */ { if (recv (sok, buf, 18, 0) != 18) goto read_error; } else if (buf[3] == 3) /* string, 1st byte is size */ { if (recv (sok, buf, 1, 0) != 1) /* read the string size */ goto read_error; packetlen = buf[0] + 2; /* can't exceed 260 */ if (recv (sok, buf, packetlen, 0) != packetlen) goto read_error; } return 0; /* success */ read_error: proxy_error (print_fd, "SOCKS\tRead error from server.\n"); return 1; } static int traverse_wingate (int print_fd, int sok, char *serverAddr, int port) { char buf[128]; snprintf (buf, sizeof (buf), "%s %d\r\n", serverAddr, port); send (sok, buf, strlen (buf), 0); return 0; } /* stuff for HTTP auth is here */ static void three_to_four (char *from, char *to) { static const char tab64[64]= { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P', 'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f', 'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v', 'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/' }; to[0] = tab64 [ (from[0] >> 2) & 63 ]; to[1] = tab64 [ ((from[0] << 4) | (from[1] >> 4)) & 63 ]; to[2] = tab64 [ ((from[1] << 2) | (from[2] >> 6)) & 63 ]; to[3] = tab64 [ from[2] & 63 ]; }; void base64_encode (char *to, char *from, unsigned int len) { while (len >= 3) { three_to_four (from, to); len -= 3; from += 3; to += 4; } if (len) { char three[3] = {0,0,0}; unsigned int i; for (i = 0; i < len; i++) { three[i] = *from++; } three_to_four (three, to); if (len == 1) { to[2] = to[3] = '='; } else if (len == 2) { to[3] = '='; } to += 4; }; to[0] = 0; } static int http_read_line (int print_fd, int sok, char *buf, int len) { len = waitline (sok, buf, len, TRUE); if (len >= 1) { /* print the message out (send it to the parent process) */ write (print_fd, "0\n", 2); if (buf[len-1] == '\r') { buf[len-1] = '\n'; write (print_fd, buf, len); } else { write (print_fd, buf, len); write (print_fd, "\n", 1); } } return len; } static int traverse_http (int print_fd, int sok, char *serverAddr, int port) { char buf[512]; char auth_data[256]; char auth_data2[252]; int n, n2; n = snprintf (buf, sizeof (buf), "CONNECT %s:%d HTTP/1.0\r\n", serverAddr, port); if (prefs.hex_net_proxy_auth) { n2 = snprintf (auth_data2, sizeof (auth_data2), "%s:%s", prefs.hex_net_proxy_user, prefs.hex_net_proxy_pass); base64_encode (auth_data, auth_data2, n2); n += snprintf (buf+n, sizeof (buf)-n, "Proxy-Authorization: Basic %s\r\n", auth_data); } n += snprintf (buf+n, sizeof (buf)-n, "\r\n"); send (sok, buf, n, 0); n = http_read_line (print_fd, sok, buf, sizeof (buf)); /* "HTTP/1.0 200 OK" */ if (n < 12) return 1; if (memcmp (buf, "HTTP/", 5) || memcmp (buf + 9, "200", 3)) return 1; while (1) { /* read until blank line */ n = http_read_line (print_fd, sok, buf, sizeof (buf)); if (n < 1 || (n == 1 && buf[0] == '\n')) break; } return 0; } static int traverse_proxy (int proxy_type, int print_fd, int sok, char *ip, int port, struct msproxy_state_t *state, netstore *ns_proxy, int csok4, int csok6, int *csok, char bound) { switch (proxy_type) { case 1: return traverse_wingate (print_fd, sok, ip, port); case 2: return traverse_socks (print_fd, sok, ip, port); case 3: return traverse_socks5 (print_fd, sok, ip, port); case 4: return traverse_http (print_fd, sok, ip, port); #ifdef USE_MSPROXY case 5: return traverse_msproxy (sok, ip, port, state, ns_proxy, csok4, csok6, csok, bound); #endif } return 1; } /* this is the child process making the connection attempt */ static int server_child (server * serv) { netstore *ns_server; netstore *ns_proxy = NULL; netstore *ns_local; int port = serv->port; int error; int sok, psok; char *hostname = serv->hostname; char *real_hostname = NULL; char *ip; char *proxy_ip = NULL; char *local_ip; int connect_port; char buf[512]; char bound = 0; int proxy_type = 0; char *proxy_host = NULL; int proxy_port; ns_server = net_store_new (); /* is a hostname set? - bind to it */ if (prefs.hex_net_bind_host[0]) { ns_local = net_store_new (); local_ip = net_resolve (ns_local, prefs.hex_net_bind_host, 0, &real_hostname); if (local_ip != NULL) { snprintf (buf, sizeof (buf), "5\n%s\n", local_ip); write (serv->childwrite, buf, strlen (buf)); net_bind (ns_local, serv->sok4, serv->sok6); bound = 1; } else { write (serv->childwrite, "7\n", 2); } net_store_destroy (ns_local); } if (!serv->dont_use_proxy) /* blocked in serverlist? */ { if (FALSE) ; #ifdef USE_LIBPROXY else if (prefs.hex_net_proxy_type == 5) { char **proxy_list; char *url, *proxy; url = g_strdup_printf ("irc://%s:%d", hostname, port); proxy_list = px_proxy_factory_get_proxies (libproxy_factory, url); if (proxy_list) { /* can use only one */ proxy = proxy_list[0]; if (!strncmp (proxy, "direct", 6)) proxy_type = 0; else if (!strncmp (proxy, "http", 4)) proxy_type = 4; else if (!strncmp (proxy, "socks5", 6)) proxy_type = 3; else if (!strncmp (proxy, "socks", 5)) proxy_type = 2; } if (proxy_type) { char *c; c = strchr (proxy, ':') + 3; proxy_host = strdup (c); c = strchr (proxy_host, ':'); *c = '\0'; proxy_port = atoi (c + 1); } g_strfreev (proxy_list); g_free (url); } #endif else if (prefs.hex_net_proxy_host[0] && prefs.hex_net_proxy_type > 0 && prefs.hex_net_proxy_use != 2) /* proxy is NOT dcc-only */ { proxy_type = prefs.hex_net_proxy_type; proxy_host = strdup (prefs.hex_net_proxy_host); proxy_port = prefs.hex_net_proxy_port; } } serv->proxy_type = proxy_type; /* first resolve where we want to connect to */ if (proxy_type > 0) { snprintf (buf, sizeof (buf), "9\n%s\n", proxy_host); write (serv->childwrite, buf, strlen (buf)); ip = net_resolve (ns_server, proxy_host, proxy_port, &real_hostname); free (proxy_host); if (!ip) { write (serv->childwrite, "1\n", 2); goto xit; } connect_port = proxy_port; /* if using socks4 or MS Proxy, attempt to resolve ip for irc server */ if ((proxy_type == 2) || (proxy_type == 5)) { ns_proxy = net_store_new (); proxy_ip = net_resolve (ns_proxy, hostname, port, &real_hostname); if (!proxy_ip) { write (serv->childwrite, "1\n", 2); goto xit; } } else /* otherwise we can just use the hostname */ proxy_ip = strdup (hostname); } else { ip = net_resolve (ns_server, hostname, port, &real_hostname); if (!ip) { write (serv->childwrite, "1\n", 2); goto xit; } connect_port = port; } snprintf (buf, sizeof (buf), "3\n%s\n%s\n%d\n", real_hostname, ip, connect_port); write (serv->childwrite, buf, strlen (buf)); if (!serv->dont_use_proxy && (proxy_type == 5)) error = net_connect (ns_server, serv->proxy_sok4, serv->proxy_sok6, &psok); else { error = net_connect (ns_server, serv->sok4, serv->sok6, &sok); psok = sok; } if (error != 0) { snprintf (buf, sizeof (buf), "2\n%d\n", sock_error ()); write (serv->childwrite, buf, strlen (buf)); } else { /* connect succeeded */ if (proxy_ip) { switch (traverse_proxy (proxy_type, serv->childwrite, psok, proxy_ip, port, &serv->msp_state, ns_proxy, serv->sok4, serv->sok6, &sok, bound)) { case 0: /* success */ #ifdef USE_MSPROXY if (!serv->dont_use_proxy && (proxy_type == 5)) snprintf (buf, sizeof (buf), "4\n%d %d %d %d %d\n", sok, psok, serv->msp_state.clientid, serv->msp_state.serverid, serv->msp_state.seq_sent); else #endif snprintf (buf, sizeof (buf), "4\n%d\n", sok); /* success */ write (serv->childwrite, buf, strlen (buf)); break; case 1: /* socks traversal failed */ write (serv->childwrite, "8\n", 2); break; } } else { snprintf (buf, sizeof (buf), "4\n%d\n", sok); /* success */ write (serv->childwrite, buf, strlen (buf)); } } xit: #if defined (USE_IPV6) || defined (WIN32) /* this is probably not needed */ net_store_destroy (ns_server); if (ns_proxy) net_store_destroy (ns_proxy); #endif /* no need to free ip/real_hostname, this process is exiting */ #ifdef WIN32 /* under win32 we use a thread -> shared memory, must free! */ if (proxy_ip) free (proxy_ip); if (ip) free (ip); if (real_hostname) free (real_hostname); #endif return 0; /* cppcheck-suppress memleak */ } static void server_connect (server *serv, char *hostname, int port, int no_login) { int pid, read_des[2]; session *sess = serv->server_session; #ifdef USE_OPENSSL if (!serv->ctx && serv->use_ssl) { if (!(serv->ctx = _SSL_context_init (ssl_cb_info, FALSE))) { fprintf (stderr, "_SSL_context_init failed\n"); exit (1); } } #endif if (!hostname[0]) return; if (port < 0) { /* use default port for this server type */ port = 6667; #ifdef USE_OPENSSL if (serv->use_ssl) port = 6697; #endif } port &= 0xffff; /* wrap around */ if (serv->connected || serv->connecting || serv->recondelay_tag) server_disconnect (sess, TRUE, -1); fe_progressbar_start (sess); EMIT_SIGNAL (XP_TE_SERVERLOOKUP, sess, hostname, NULL, NULL, NULL, 0); safe_strcpy (serv->servername, hostname, sizeof (serv->servername)); /* overlap illegal in strncpy */ if (hostname != serv->hostname) safe_strcpy (serv->hostname, hostname, sizeof (serv->hostname)); #ifdef USE_OPENSSL if (serv->use_ssl) { char *cert_file; serv->have_cert = FALSE; /* first try network specific cert/key */ cert_file = g_strdup_printf ("%s" G_DIR_SEPARATOR_S "certs" G_DIR_SEPARATOR_S "%s.pem", get_xdir (), server_get_network (serv, TRUE)); if (SSL_CTX_use_certificate_file (serv->ctx, cert_file, SSL_FILETYPE_PEM) == 1) { if (SSL_CTX_use_PrivateKey_file (serv->ctx, cert_file, SSL_FILETYPE_PEM) == 1) serv->have_cert = TRUE; } else { /* if that doesn't exist, try <config>/certs/client.pem */ cert_file = g_build_filename (get_xdir (), "certs", "client.pem", NULL); if (SSL_CTX_use_certificate_file (serv->ctx, cert_file, SSL_FILETYPE_PEM) == 1) { if (SSL_CTX_use_PrivateKey_file (serv->ctx, cert_file, SSL_FILETYPE_PEM) == 1) serv->have_cert = TRUE; } } g_free (cert_file); } #endif server_set_defaults (serv); serv->connecting = TRUE; serv->port = port; serv->no_login = no_login; fe_server_event (serv, FE_SE_CONNECTING, 0); fe_set_away (serv); server_flush_queue (serv); #ifdef WIN32 if (_pipe (read_des, 4096, _O_BINARY) < 0) #else if (pipe (read_des) < 0) #endif return; #ifdef __EMX__ /* os/2 */ setmode (read_des[0], O_BINARY); setmode (read_des[1], O_BINARY); #endif serv->childread = read_des[0]; serv->childwrite = read_des[1]; /* create both sockets now, drop one later */ net_sockets (&serv->sok4, &serv->sok6); #ifdef USE_MSPROXY /* In case of MS Proxy we have a separate UDP control connection */ if (!serv->dont_use_proxy && (serv->proxy_type == 5)) udp_sockets (&serv->proxy_sok4, &serv->proxy_sok6); else #endif { serv->proxy_sok4 = -1; serv->proxy_sok6 = -1; } #ifdef WIN32 CloseHandle (CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)server_child, serv, 0, (DWORD *)&pid)); #else #ifdef LOOKUPD /* CL: net_resolve calls rand() when LOOKUPD is set, so prepare a different * seed for each child. This method gives a bigger variation in seed values * than calling srand(time(0)) in the child itself. */ rand(); #endif switch (pid = fork ()) { case -1: return; case 0: /* this is the child */ setuid (getuid ()); server_child (serv); _exit (0); } #endif serv->childpid = pid; #ifdef WIN32 serv->iotag = fe_input_add (serv->childread, FIA_READ|FIA_FD, server_read_child, #else serv->iotag = fe_input_add (serv->childread, FIA_READ, server_read_child, #endif serv); } void server_fill_her_up (server *serv) { serv->connect = server_connect; serv->disconnect = server_disconnect; serv->cleanup = server_cleanup; serv->flush_queue = server_flush_queue; serv->auto_reconnect = auto_reconnect; proto_fill_her_up (serv); } void server_set_encoding (server *serv, char *new_encoding) { char *space; if (serv->encoding) { free (serv->encoding); /* can be left as NULL to indicate system encoding */ serv->encoding = NULL; serv->using_cp1255 = FALSE; serv->using_irc = FALSE; } if (new_encoding) { serv->encoding = strdup (new_encoding); /* the serverlist GUI might have added a space and short description - remove it. */ space = strchr (serv->encoding, ' '); if (space) space[0] = 0; /* server_inline() uses these flags */ if (!g_ascii_strcasecmp (serv->encoding, "CP1255") || !g_ascii_strcasecmp (serv->encoding, "WINDOWS-1255")) serv->using_cp1255 = TRUE; else if (!g_ascii_strcasecmp (serv->encoding, "IRC")) serv->using_irc = TRUE; } } server * server_new (void) { static int id = 0; server *serv; serv = malloc (sizeof (struct server)); memset (serv, 0, sizeof (struct server)); /* use server.c and proto-irc.c functions */ server_fill_her_up (serv); serv->id = id++; serv->sok = -1; strcpy (serv->nick, prefs.hex_irc_nick1); server_set_defaults (serv); serv_list = g_slist_prepend (serv_list, serv); fe_new_server (serv); return serv; } int is_server (server *serv) { return g_slist_find (serv_list, serv) ? 1 : 0; } void server_set_defaults (server *serv) { if (serv->chantypes) free (serv->chantypes); if (serv->chanmodes) free (serv->chanmodes); if (serv->nick_prefixes) free (serv->nick_prefixes); if (serv->nick_modes) free (serv->nick_modes); serv->chantypes = strdup ("#&!+"); serv->chanmodes = strdup ("beI,k,l"); serv->nick_prefixes = strdup ("@%+"); serv->nick_modes = strdup ("ohv"); serv->nickcount = 1; serv->end_of_motd = FALSE; serv->is_away = FALSE; serv->supports_watch = FALSE; serv->supports_monitor = FALSE; serv->bad_prefix = FALSE; serv->use_who = TRUE; serv->have_namesx = FALSE; serv->have_awaynotify = FALSE; serv->have_uhnames = FALSE; serv->have_whox = FALSE; serv->have_idmsg = FALSE; serv->have_accnotify = FALSE; serv->have_extjoin = FALSE; serv->have_server_time = FALSE; serv->have_sasl = FALSE; serv->have_except = FALSE; serv->have_invite = FALSE; } char * server_get_network (server *serv, gboolean fallback) { /* check the network list */ if (serv->network) return ((ircnet *)serv->network)->name; /* check the network name given in 005 NETWORK=... */ if (serv->server_session && *serv->server_session->channel) return serv->server_session->channel; if (fallback) return serv->servername; return NULL; } void server_set_name (server *serv, char *name) { GSList *list = sess_list; session *sess; if (name[0] == 0) name = serv->hostname; /* strncpy parameters must NOT overlap */ if (name != serv->servername) { safe_strcpy (serv->servername, name, sizeof (serv->servername)); } while (list) { sess = (session *) list->data; if (sess->server == serv) fe_set_title (sess); list = list->next; } if (serv->server_session->type == SESS_SERVER) { if (serv->network) { safe_strcpy (serv->server_session->channel, ((ircnet *)serv->network)->name, CHANLEN); } else { safe_strcpy (serv->server_session->channel, name, CHANLEN); } fe_set_channel (serv->server_session); } } struct away_msg * server_away_find_message (server *serv, char *nick) { struct away_msg *away; GSList *list = away_list; while (list) { away = (struct away_msg *) list->data; if (away->server == serv && !serv->p_cmp (nick, away->nick)) return away; list = list->next; } return NULL; } static void server_away_free_messages (server *serv) { GSList *list, *next; struct away_msg *away; list = away_list; while (list) { away = list->data; next = list->next; if (away->server == serv) { away_list = g_slist_remove (away_list, away); if (away->message) free (away->message); free (away); next = away_list; } list = next; } } void server_away_save_message (server *serv, char *nick, char *msg) { struct away_msg *away = server_away_find_message (serv, nick); if (away) /* Change message for known user */ { if (away->message) free (away->message); away->message = strdup (msg); } else /* Create brand new entry */ { away = malloc (sizeof (struct away_msg)); if (away) { away->server = serv; safe_strcpy (away->nick, nick, sizeof (away->nick)); away->message = strdup (msg); away_list = g_slist_prepend (away_list, away); } } } void server_free (server *serv) { serv->cleanup (serv); serv_list = g_slist_remove (serv_list, serv); dcc_notify_kill (serv); serv->flush_queue (serv); server_away_free_messages (serv); free (serv->nick_modes); free (serv->nick_prefixes); free (serv->chanmodes); free (serv->chantypes); if (serv->bad_nick_prefixes) free (serv->bad_nick_prefixes); if (serv->last_away_reason) free (serv->last_away_reason); if (serv->encoding) free (serv->encoding); if (serv->favlist) g_slist_free_full (serv->favlist, (GDestroyNotify) servlist_favchan_free); #ifdef USE_OPENSSL if (serv->ctx) _SSL_context_free (serv->ctx); #endif fe_server_callback (serv); free (serv); notify_cleanup (); }
./CrossVul/dataset_final_sorted/CWE-310/c/good_5867_0
crossvul-cpp_data_bad_5666_4
/* * Crypto user configuration API. * * Copyright (C) 2011 secunet Security Networks AG * Copyright (C) 2011 Steffen Klassert <steffen.klassert@secunet.com> * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. */ #include <linux/module.h> #include <linux/crypto.h> #include <linux/cryptouser.h> #include <linux/sched.h> #include <net/netlink.h> #include <linux/security.h> #include <net/net_namespace.h> #include <crypto/internal/aead.h> #include <crypto/internal/skcipher.h> #include "internal.h" static DEFINE_MUTEX(crypto_cfg_mutex); /* The crypto netlink socket */ static struct sock *crypto_nlsk; struct crypto_dump_info { struct sk_buff *in_skb; struct sk_buff *out_skb; u32 nlmsg_seq; u16 nlmsg_flags; }; static struct crypto_alg *crypto_alg_match(struct crypto_user_alg *p, int exact) { struct crypto_alg *q, *alg = NULL; down_read(&crypto_alg_sem); list_for_each_entry(q, &crypto_alg_list, cra_list) { int match = 0; if ((q->cra_flags ^ p->cru_type) & p->cru_mask) continue; if (strlen(p->cru_driver_name)) match = !strcmp(q->cra_driver_name, p->cru_driver_name); else if (!exact) match = !strcmp(q->cra_name, p->cru_name); if (match) { alg = q; break; } } up_read(&crypto_alg_sem); return alg; } static int crypto_report_cipher(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_cipher rcipher; snprintf(rcipher.type, CRYPTO_MAX_ALG_NAME, "%s", "cipher"); rcipher.blocksize = alg->cra_blocksize; rcipher.min_keysize = alg->cra_cipher.cia_min_keysize; rcipher.max_keysize = alg->cra_cipher.cia_max_keysize; if (nla_put(skb, CRYPTOCFGA_REPORT_CIPHER, sizeof(struct crypto_report_cipher), &rcipher)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } static int crypto_report_comp(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_comp rcomp; snprintf(rcomp.type, CRYPTO_MAX_ALG_NAME, "%s", "compression"); if (nla_put(skb, CRYPTOCFGA_REPORT_COMPRESS, sizeof(struct crypto_report_comp), &rcomp)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } static int crypto_report_one(struct crypto_alg *alg, struct crypto_user_alg *ualg, struct sk_buff *skb) { memcpy(&ualg->cru_name, &alg->cra_name, sizeof(ualg->cru_name)); memcpy(&ualg->cru_driver_name, &alg->cra_driver_name, sizeof(ualg->cru_driver_name)); memcpy(&ualg->cru_module_name, module_name(alg->cra_module), CRYPTO_MAX_ALG_NAME); ualg->cru_flags = alg->cra_flags; ualg->cru_refcnt = atomic_read(&alg->cra_refcnt); if (nla_put_u32(skb, CRYPTOCFGA_PRIORITY_VAL, alg->cra_priority)) goto nla_put_failure; if (alg->cra_flags & CRYPTO_ALG_LARVAL) { struct crypto_report_larval rl; snprintf(rl.type, CRYPTO_MAX_ALG_NAME, "%s", "larval"); if (nla_put(skb, CRYPTOCFGA_REPORT_LARVAL, sizeof(struct crypto_report_larval), &rl)) goto nla_put_failure; goto out; } if (alg->cra_type && alg->cra_type->report) { if (alg->cra_type->report(skb, alg)) goto nla_put_failure; goto out; } switch (alg->cra_flags & (CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_LARVAL)) { case CRYPTO_ALG_TYPE_CIPHER: if (crypto_report_cipher(skb, alg)) goto nla_put_failure; break; case CRYPTO_ALG_TYPE_COMPRESS: if (crypto_report_comp(skb, alg)) goto nla_put_failure; break; } out: return 0; nla_put_failure: return -EMSGSIZE; } static int crypto_report_alg(struct crypto_alg *alg, struct crypto_dump_info *info) { struct sk_buff *in_skb = info->in_skb; struct sk_buff *skb = info->out_skb; struct nlmsghdr *nlh; struct crypto_user_alg *ualg; int err = 0; nlh = nlmsg_put(skb, NETLINK_CB(in_skb).portid, info->nlmsg_seq, CRYPTO_MSG_GETALG, sizeof(*ualg), info->nlmsg_flags); if (!nlh) { err = -EMSGSIZE; goto out; } ualg = nlmsg_data(nlh); err = crypto_report_one(alg, ualg, skb); if (err) { nlmsg_cancel(skb, nlh); goto out; } nlmsg_end(skb, nlh); out: return err; } static int crypto_report(struct sk_buff *in_skb, struct nlmsghdr *in_nlh, struct nlattr **attrs) { struct crypto_user_alg *p = nlmsg_data(in_nlh); struct crypto_alg *alg; struct sk_buff *skb; struct crypto_dump_info info; int err; if (!p->cru_driver_name) return -EINVAL; alg = crypto_alg_match(p, 1); if (!alg) return -ENOENT; skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC); if (!skb) return -ENOMEM; info.in_skb = in_skb; info.out_skb = skb; info.nlmsg_seq = in_nlh->nlmsg_seq; info.nlmsg_flags = 0; err = crypto_report_alg(alg, &info); if (err) return err; return nlmsg_unicast(crypto_nlsk, skb, NETLINK_CB(in_skb).portid); } static int crypto_dump_report(struct sk_buff *skb, struct netlink_callback *cb) { struct crypto_alg *alg; struct crypto_dump_info info; int err; if (cb->args[0]) goto out; cb->args[0] = 1; info.in_skb = cb->skb; info.out_skb = skb; info.nlmsg_seq = cb->nlh->nlmsg_seq; info.nlmsg_flags = NLM_F_MULTI; list_for_each_entry(alg, &crypto_alg_list, cra_list) { err = crypto_report_alg(alg, &info); if (err) goto out_err; } out: return skb->len; out_err: return err; } static int crypto_dump_report_done(struct netlink_callback *cb) { return 0; } static int crypto_update_alg(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct crypto_alg *alg; struct crypto_user_alg *p = nlmsg_data(nlh); struct nlattr *priority = attrs[CRYPTOCFGA_PRIORITY_VAL]; LIST_HEAD(list); if (priority && !strlen(p->cru_driver_name)) return -EINVAL; alg = crypto_alg_match(p, 1); if (!alg) return -ENOENT; down_write(&crypto_alg_sem); crypto_remove_spawns(alg, &list, NULL); if (priority) alg->cra_priority = nla_get_u32(priority); up_write(&crypto_alg_sem); crypto_remove_final(&list); return 0; } static int crypto_del_alg(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct crypto_alg *alg; struct crypto_user_alg *p = nlmsg_data(nlh); alg = crypto_alg_match(p, 1); if (!alg) return -ENOENT; /* We can not unregister core algorithms such as aes-generic. * We would loose the reference in the crypto_alg_list to this algorithm * if we try to unregister. Unregistering such an algorithm without * removing the module is not possible, so we restrict to crypto * instances that are build from templates. */ if (!(alg->cra_flags & CRYPTO_ALG_INSTANCE)) return -EINVAL; if (atomic_read(&alg->cra_refcnt) != 1) return -EBUSY; return crypto_unregister_instance(alg); } static struct crypto_alg *crypto_user_skcipher_alg(const char *name, u32 type, u32 mask) { int err; struct crypto_alg *alg; type = crypto_skcipher_type(type); mask = crypto_skcipher_mask(mask); for (;;) { alg = crypto_lookup_skcipher(name, type, mask); if (!IS_ERR(alg)) return alg; err = PTR_ERR(alg); if (err != -EAGAIN) break; if (signal_pending(current)) { err = -EINTR; break; } } return ERR_PTR(err); } static struct crypto_alg *crypto_user_aead_alg(const char *name, u32 type, u32 mask) { int err; struct crypto_alg *alg; type &= ~(CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV); type |= CRYPTO_ALG_TYPE_AEAD; mask &= ~(CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV); mask |= CRYPTO_ALG_TYPE_MASK; for (;;) { alg = crypto_lookup_aead(name, type, mask); if (!IS_ERR(alg)) return alg; err = PTR_ERR(alg); if (err != -EAGAIN) break; if (signal_pending(current)) { err = -EINTR; break; } } return ERR_PTR(err); } static int crypto_add_alg(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { int exact = 0; const char *name; struct crypto_alg *alg; struct crypto_user_alg *p = nlmsg_data(nlh); struct nlattr *priority = attrs[CRYPTOCFGA_PRIORITY_VAL]; if (strlen(p->cru_driver_name)) exact = 1; if (priority && !exact) return -EINVAL; alg = crypto_alg_match(p, exact); if (alg) return -EEXIST; if (strlen(p->cru_driver_name)) name = p->cru_driver_name; else name = p->cru_name; switch (p->cru_type & p->cru_mask & CRYPTO_ALG_TYPE_MASK) { case CRYPTO_ALG_TYPE_AEAD: alg = crypto_user_aead_alg(name, p->cru_type, p->cru_mask); break; case CRYPTO_ALG_TYPE_GIVCIPHER: case CRYPTO_ALG_TYPE_BLKCIPHER: case CRYPTO_ALG_TYPE_ABLKCIPHER: alg = crypto_user_skcipher_alg(name, p->cru_type, p->cru_mask); break; default: alg = crypto_alg_mod_lookup(name, p->cru_type, p->cru_mask); } if (IS_ERR(alg)) return PTR_ERR(alg); down_write(&crypto_alg_sem); if (priority) alg->cra_priority = nla_get_u32(priority); up_write(&crypto_alg_sem); crypto_mod_put(alg); return 0; } #define MSGSIZE(type) sizeof(struct type) static const int crypto_msg_min[CRYPTO_NR_MSGTYPES] = { [CRYPTO_MSG_NEWALG - CRYPTO_MSG_BASE] = MSGSIZE(crypto_user_alg), [CRYPTO_MSG_DELALG - CRYPTO_MSG_BASE] = MSGSIZE(crypto_user_alg), [CRYPTO_MSG_UPDATEALG - CRYPTO_MSG_BASE] = MSGSIZE(crypto_user_alg), [CRYPTO_MSG_GETALG - CRYPTO_MSG_BASE] = MSGSIZE(crypto_user_alg), }; static const struct nla_policy crypto_policy[CRYPTOCFGA_MAX+1] = { [CRYPTOCFGA_PRIORITY_VAL] = { .type = NLA_U32}, }; #undef MSGSIZE static struct crypto_link { int (*doit)(struct sk_buff *, struct nlmsghdr *, struct nlattr **); int (*dump)(struct sk_buff *, struct netlink_callback *); int (*done)(struct netlink_callback *); } crypto_dispatch[CRYPTO_NR_MSGTYPES] = { [CRYPTO_MSG_NEWALG - CRYPTO_MSG_BASE] = { .doit = crypto_add_alg}, [CRYPTO_MSG_DELALG - CRYPTO_MSG_BASE] = { .doit = crypto_del_alg}, [CRYPTO_MSG_UPDATEALG - CRYPTO_MSG_BASE] = { .doit = crypto_update_alg}, [CRYPTO_MSG_GETALG - CRYPTO_MSG_BASE] = { .doit = crypto_report, .dump = crypto_dump_report, .done = crypto_dump_report_done}, }; static int crypto_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh) { struct nlattr *attrs[CRYPTOCFGA_MAX+1]; struct crypto_link *link; int type, err; type = nlh->nlmsg_type; if (type > CRYPTO_MSG_MAX) return -EINVAL; type -= CRYPTO_MSG_BASE; link = &crypto_dispatch[type]; if (!capable(CAP_NET_ADMIN)) return -EPERM; if ((type == (CRYPTO_MSG_GETALG - CRYPTO_MSG_BASE) && (nlh->nlmsg_flags & NLM_F_DUMP))) { struct crypto_alg *alg; u16 dump_alloc = 0; if (link->dump == NULL) return -EINVAL; list_for_each_entry(alg, &crypto_alg_list, cra_list) dump_alloc += CRYPTO_REPORT_MAXSIZE; { struct netlink_dump_control c = { .dump = link->dump, .done = link->done, .min_dump_alloc = dump_alloc, }; return netlink_dump_start(crypto_nlsk, skb, nlh, &c); } } err = nlmsg_parse(nlh, crypto_msg_min[type], attrs, CRYPTOCFGA_MAX, crypto_policy); if (err < 0) return err; if (link->doit == NULL) return -EINVAL; return link->doit(skb, nlh, attrs); } static void crypto_netlink_rcv(struct sk_buff *skb) { mutex_lock(&crypto_cfg_mutex); netlink_rcv_skb(skb, &crypto_user_rcv_msg); mutex_unlock(&crypto_cfg_mutex); } static int __init crypto_user_init(void) { struct netlink_kernel_cfg cfg = { .input = crypto_netlink_rcv, }; crypto_nlsk = netlink_kernel_create(&init_net, NETLINK_CRYPTO, &cfg); if (!crypto_nlsk) return -ENOMEM; return 0; } static void __exit crypto_user_exit(void) { netlink_kernel_release(crypto_nlsk); } module_init(crypto_user_init); module_exit(crypto_user_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Steffen Klassert <steffen.klassert@secunet.com>"); MODULE_DESCRIPTION("Crypto userspace configuration API");
./CrossVul/dataset_final_sorted/CWE-310/c/bad_5666_4
crossvul-cpp_data_bad_1446_0
/* ssl/s3_srvr.c -*- mode:C; c-file-style: "eay" -*- */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ /* ==================================================================== * Copyright (c) 1998-2007 The OpenSSL 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: * * 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. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* ==================================================================== * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * * Portions of the attached software ("Contribution") are developed by * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project. * * The Contribution is licensed pursuant to the OpenSSL open source * license provided above. * * ECC cipher suite support in OpenSSL originally written by * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories. * */ /* ==================================================================== * Copyright 2005 Nokia. All rights reserved. * * The portions of the attached software ("Contribution") is developed by * Nokia Corporation and is licensed pursuant to the OpenSSL open source * license. * * The Contribution, originally written by Mika Kousa and Pasi Eronen of * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites * support (see RFC 4279) to OpenSSL. * * No patent licenses or other rights except those expressly stated in * the OpenSSL open source license shall be deemed granted or received * expressly, by implication, estoppel, or otherwise. * * No assurances are provided by Nokia that the Contribution does not * infringe the patent or other intellectual property rights of any third * party or that the license provides you with all the necessary rights * to make use of the Contribution. * * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR * OTHERWISE. */ #define REUSE_CIPHER_BUG #define NETSCAPE_HANG_BUG #include <stdio.h> #include "ssl_locl.h" #include "kssl_lcl.h" #include "../crypto/constant_time_locl.h" #include <openssl/buffer.h> #include <openssl/rand.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/hmac.h> #include <openssl/x509.h> #ifndef OPENSSL_NO_DH #include <openssl/dh.h> #endif #include <openssl/bn.h> #ifndef OPENSSL_NO_KRB5 #include <openssl/krb5_asn.h> #endif #include <openssl/md5.h> #ifndef OPENSSL_NO_SSL3_METHOD static const SSL_METHOD *ssl3_get_server_method(int ver); static const SSL_METHOD *ssl3_get_server_method(int ver) { if (ver == SSL3_VERSION) return(SSLv3_server_method()); else return(NULL); } IMPLEMENT_ssl3_meth_func(SSLv3_server_method, ssl3_accept, ssl_undefined_function, ssl3_get_server_method) #endif #ifndef OPENSSL_NO_SRP static int ssl_check_srp_ext_ClientHello(SSL *s, int *al) { int ret = SSL_ERROR_NONE; *al = SSL_AD_UNRECOGNIZED_NAME; if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) && (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) { if(s->srp_ctx.login == NULL) { /* RFC 5054 says SHOULD reject, we do so if There is no srp login name */ ret = SSL3_AL_FATAL; *al = SSL_AD_UNKNOWN_PSK_IDENTITY; } else { ret = SSL_srp_server_param_with_username(s,al); } } return ret; } #endif int ssl3_accept(SSL *s) { BUF_MEM *buf; unsigned long alg_k,Time=(unsigned long)time(NULL); void (*cb)(const SSL *ssl,int type,int val)=NULL; int ret= -1; int new_state,state,skip=0; RAND_add(&Time,sizeof(Time),0); ERR_clear_error(); clear_sys_error(); if (s->info_callback != NULL) cb=s->info_callback; else if (s->ctx->info_callback != NULL) cb=s->ctx->info_callback; /* init things to blank */ s->in_handshake++; if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); if (s->cert == NULL) { SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET); return(-1); } #ifndef OPENSSL_NO_HEARTBEATS /* If we're awaiting a HeartbeatResponse, pretend we * already got and don't await it anymore, because * Heartbeats don't make sense during handshakes anyway. */ if (s->tlsext_hb_pending) { s->tlsext_hb_pending = 0; s->tlsext_hb_seq++; } #endif for (;;) { state=s->state; switch (s->state) { case SSL_ST_RENEGOTIATE: s->renegotiate=1; /* s->state=SSL_ST_ACCEPT; */ case SSL_ST_BEFORE: case SSL_ST_ACCEPT: case SSL_ST_BEFORE|SSL_ST_ACCEPT: case SSL_ST_OK|SSL_ST_ACCEPT: s->server=1; if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1); if ((s->version>>8) != 3) { SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR); return -1; } if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) { SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_VERSION_TOO_LOW); return -1; } s->type=SSL_ST_ACCEPT; if (s->init_buf == NULL) { if ((buf=BUF_MEM_new()) == NULL) { ret= -1; goto end; } if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH)) { BUF_MEM_free(buf); ret= -1; goto end; } s->init_buf=buf; } if (!ssl3_setup_buffers(s)) { ret= -1; goto end; } s->init_num=0; s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY; s->s3->flags &= ~SSL3_FLAGS_CCS_OK; /* Should have been reset by ssl3_get_finished, too. */ s->s3->change_cipher_spec = 0; if (s->state != SSL_ST_RENEGOTIATE) { /* Ok, we now need to push on a buffering BIO so that * the output is sent in a way that TCP likes :-) */ if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; } ssl3_init_finished_mac(s); s->state=SSL3_ST_SR_CLNT_HELLO_A; s->ctx->stats.sess_accept++; } else if (!s->s3->send_connection_binding && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { /* Server attempting to renegotiate with * client that doesn't support secure * renegotiation. */ SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); ret = -1; goto end; } else { /* s->state == SSL_ST_RENEGOTIATE, * we will just send a HelloRequest */ s->ctx->stats.sess_accept_renegotiate++; s->state=SSL3_ST_SW_HELLO_REQ_A; } break; case SSL3_ST_SW_HELLO_REQ_A: case SSL3_ST_SW_HELLO_REQ_B: s->shutdown=0; ret=ssl3_send_hello_request(s); if (ret <= 0) goto end; s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C; s->state=SSL3_ST_SW_FLUSH; s->init_num=0; ssl3_init_finished_mac(s); break; case SSL3_ST_SW_HELLO_REQ_C: s->state=SSL_ST_OK; break; case SSL3_ST_SR_CLNT_HELLO_A: case SSL3_ST_SR_CLNT_HELLO_B: case SSL3_ST_SR_CLNT_HELLO_C: ret=ssl3_get_client_hello(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_SRP s->state = SSL3_ST_SR_CLNT_HELLO_D; case SSL3_ST_SR_CLNT_HELLO_D: { int al; if ((ret = ssl_check_srp_ext_ClientHello(s,&al)) < 0) { /* callback indicates firther work to be done */ s->rwstate=SSL_X509_LOOKUP; goto end; } if (ret != SSL_ERROR_NONE) { ssl3_send_alert(s,SSL3_AL_FATAL,al); /* This is not really an error but the only means to for a client to detect whether srp is supported. */ if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY) SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLSEXT); ret = SSL_TLSEXT_ERR_ALERT_FATAL; ret= -1; goto end; } } #endif s->renegotiate = 2; s->state=SSL3_ST_SW_SRVR_HELLO_A; s->init_num=0; break; case SSL3_ST_SW_SRVR_HELLO_A: case SSL3_ST_SW_SRVR_HELLO_B: ret=ssl3_send_server_hello(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_TLSEXT if (s->hit) { if (s->tlsext_ticket_expected) s->state=SSL3_ST_SW_SESSION_TICKET_A; else s->state=SSL3_ST_SW_CHANGE_A; } #else if (s->hit) s->state=SSL3_ST_SW_CHANGE_A; #endif else s->state = SSL3_ST_SW_CERT_A; s->init_num = 0; break; case SSL3_ST_SW_CERT_A: case SSL3_ST_SW_CERT_B: /* Check if it is anon DH or anon ECDH, */ /* normal PSK or KRB5 or SRP */ if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aKRB5|SSL_aSRP)) && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { ret=ssl3_send_server_certificate(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_TLSEXT if (s->tlsext_status_expected) s->state=SSL3_ST_SW_CERT_STATUS_A; else s->state=SSL3_ST_SW_KEY_EXCH_A; } else { skip = 1; s->state=SSL3_ST_SW_KEY_EXCH_A; } #else } else skip=1; s->state=SSL3_ST_SW_KEY_EXCH_A; #endif s->init_num=0; break; case SSL3_ST_SW_KEY_EXCH_A: case SSL3_ST_SW_KEY_EXCH_B: alg_k = s->s3->tmp.new_cipher->algorithm_mkey; /* * clear this, it may get reset by * send_server_key_exchange */ s->s3->tmp.use_rsa_tmp=0; /* only send if a DH key exchange, fortezza or * RSA but we have a sign only certificate * * PSK: may send PSK identity hints * * For ECC ciphersuites, we send a serverKeyExchange * message only if the cipher suite is either * ECDH-anon or ECDHE. In other cases, the * server certificate contains the server's * public key for key exchange. */ if (0 /* PSK: send ServerKeyExchange if PSK identity * hint if provided */ #ifndef OPENSSL_NO_PSK || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint) #endif #ifndef OPENSSL_NO_SRP /* SRP: send ServerKeyExchange */ || (alg_k & SSL_kSRP) #endif || (alg_k & SSL_kDHE) || (alg_k & SSL_kECDHE) || ((alg_k & SSL_kRSA) && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher) ) ) ) ) { ret=ssl3_send_server_key_exchange(s); if (ret <= 0) goto end; } else skip=1; s->state=SSL3_ST_SW_CERT_REQ_A; s->init_num=0; break; case SSL3_ST_SW_CERT_REQ_A: case SSL3_ST_SW_CERT_REQ_B: if (/* don't request cert unless asked for it: */ !(s->verify_mode & SSL_VERIFY_PEER) || /* if SSL_VERIFY_CLIENT_ONCE is set, * don't request cert during re-negotiation: */ ((s->session->peer != NULL) && (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) || /* never request cert in anonymous ciphersuites * (see section "Certificate request" in SSL 3 drafts * and in RFC 2246): */ ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) && /* ... except when the application insists on verification * (against the specs, but s3_clnt.c accepts this for SSL 3) */ !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) || /* never request cert in Kerberos ciphersuites */ (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) || /* don't request certificate for SRP auth */ (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP) /* With normal PSK Certificates and * Certificate Requests are omitted */ || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { /* no cert request */ skip=1; s->s3->tmp.cert_request=0; s->state=SSL3_ST_SW_SRVR_DONE_A; if (s->s3->handshake_buffer) if (!ssl3_digest_cached_records(s)) return -1; } else { s->s3->tmp.cert_request=1; ret=ssl3_send_certificate_request(s); if (ret <= 0) goto end; #ifndef NETSCAPE_HANG_BUG s->state=SSL3_ST_SW_SRVR_DONE_A; #else s->state=SSL3_ST_SW_FLUSH; s->s3->tmp.next_state=SSL3_ST_SR_CERT_A; #endif s->init_num=0; } break; case SSL3_ST_SW_SRVR_DONE_A: case SSL3_ST_SW_SRVR_DONE_B: ret=ssl3_send_server_done(s); if (ret <= 0) goto end; s->s3->tmp.next_state=SSL3_ST_SR_CERT_A; s->state=SSL3_ST_SW_FLUSH; s->init_num=0; break; case SSL3_ST_SW_FLUSH: /* This code originally checked to see if * any data was pending using BIO_CTRL_INFO * and then flushed. This caused problems * as documented in PR#1939. The proposed * fix doesn't completely resolve this issue * as buggy implementations of BIO_CTRL_PENDING * still exist. So instead we just flush * unconditionally. */ s->rwstate=SSL_WRITING; if (BIO_flush(s->wbio) <= 0) { ret= -1; goto end; } s->rwstate=SSL_NOTHING; s->state=s->s3->tmp.next_state; break; case SSL3_ST_SR_CERT_A: case SSL3_ST_SR_CERT_B: if (s->s3->tmp.cert_request) { ret=ssl3_get_client_certificate(s); if (ret <= 0) goto end; } s->init_num=0; s->state=SSL3_ST_SR_KEY_EXCH_A; break; case SSL3_ST_SR_KEY_EXCH_A: case SSL3_ST_SR_KEY_EXCH_B: ret=ssl3_get_client_key_exchange(s); if (ret <= 0) goto end; if (ret == 2) { /* For the ECDH ciphersuites when * the client sends its ECDH pub key in * a certificate, the CertificateVerify * message is not sent. * Also for GOST ciphersuites when * the client uses its key from the certificate * for key exchange. */ #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) s->state=SSL3_ST_SR_FINISHED_A; #else if (s->s3->next_proto_neg_seen) s->state=SSL3_ST_SR_NEXT_PROTO_A; else s->state=SSL3_ST_SR_FINISHED_A; #endif s->init_num = 0; } else if (SSL_USE_SIGALGS(s)) { s->state=SSL3_ST_SR_CERT_VRFY_A; s->init_num=0; if (!s->session->peer) break; /* For sigalgs freeze the handshake buffer * at this point and digest cached records. */ if (!s->s3->handshake_buffer) { SSLerr(SSL_F_SSL3_ACCEPT,ERR_R_INTERNAL_ERROR); return -1; } s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE; if (!ssl3_digest_cached_records(s)) return -1; } else { int offset=0; int dgst_num; s->state=SSL3_ST_SR_CERT_VRFY_A; s->init_num=0; /* We need to get hashes here so if there is * a client cert, it can be verified * FIXME - digest processing for CertificateVerify * should be generalized. But it is next step */ if (s->s3->handshake_buffer) if (!ssl3_digest_cached_records(s)) return -1; for (dgst_num=0; dgst_num<SSL_MAX_DIGEST;dgst_num++) if (s->s3->handshake_dgst[dgst_num]) { int dgst_size; s->method->ssl3_enc->cert_verify_mac(s,EVP_MD_CTX_type(s->s3->handshake_dgst[dgst_num]),&(s->s3->tmp.cert_verify_md[offset])); dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]); if (dgst_size < 0) { ret = -1; goto end; } offset+=dgst_size; } } break; case SSL3_ST_SR_CERT_VRFY_A: case SSL3_ST_SR_CERT_VRFY_B: /* * This *should* be the first time we enable CCS, but be * extra careful about surrounding code changes. We need * to set this here because we don't know if we're * expecting a CertificateVerify or not. */ if (!s->s3->change_cipher_spec) s->s3->flags |= SSL3_FLAGS_CCS_OK; /* we should decide if we expected this one */ ret=ssl3_get_cert_verify(s); if (ret <= 0) goto end; #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) s->state=SSL3_ST_SR_FINISHED_A; #else if (s->s3->next_proto_neg_seen) s->state=SSL3_ST_SR_NEXT_PROTO_A; else s->state=SSL3_ST_SR_FINISHED_A; #endif s->init_num=0; break; #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) case SSL3_ST_SR_NEXT_PROTO_A: case SSL3_ST_SR_NEXT_PROTO_B: /* * Enable CCS for resumed handshakes with NPN. * In a full handshake with NPN, we end up here through * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was * already set. Receiving a CCS clears the flag, so make * sure not to re-enable it to ban duplicates. * s->s3->change_cipher_spec is set when a CCS is * processed in s3_pkt.c, and remains set until * the client's Finished message is read. */ if (!s->s3->change_cipher_spec) s->s3->flags |= SSL3_FLAGS_CCS_OK; ret=ssl3_get_next_proto(s); if (ret <= 0) goto end; s->init_num = 0; s->state=SSL3_ST_SR_FINISHED_A; break; #endif case SSL3_ST_SR_FINISHED_A: case SSL3_ST_SR_FINISHED_B: /* * Enable CCS for resumed handshakes without NPN. * In a full handshake, we end up here through * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was * already set. Receiving a CCS clears the flag, so make * sure not to re-enable it to ban duplicates. * s->s3->change_cipher_spec is set when a CCS is * processed in s3_pkt.c, and remains set until * the client's Finished message is read. */ if (!s->s3->change_cipher_spec) s->s3->flags |= SSL3_FLAGS_CCS_OK; ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A, SSL3_ST_SR_FINISHED_B); if (ret <= 0) goto end; if (s->hit) s->state=SSL_ST_OK; #ifndef OPENSSL_NO_TLSEXT else if (s->tlsext_ticket_expected) s->state=SSL3_ST_SW_SESSION_TICKET_A; #endif else s->state=SSL3_ST_SW_CHANGE_A; s->init_num=0; break; #ifndef OPENSSL_NO_TLSEXT case SSL3_ST_SW_SESSION_TICKET_A: case SSL3_ST_SW_SESSION_TICKET_B: ret=ssl3_send_newsession_ticket(s); if (ret <= 0) goto end; s->state=SSL3_ST_SW_CHANGE_A; s->init_num=0; break; case SSL3_ST_SW_CERT_STATUS_A: case SSL3_ST_SW_CERT_STATUS_B: ret=ssl3_send_cert_status(s); if (ret <= 0) goto end; s->state=SSL3_ST_SW_KEY_EXCH_A; s->init_num=0; break; #endif case SSL3_ST_SW_CHANGE_A: case SSL3_ST_SW_CHANGE_B: s->session->cipher=s->s3->tmp.new_cipher; if (!s->method->ssl3_enc->setup_key_block(s)) { ret= -1; goto end; } ret=ssl3_send_change_cipher_spec(s, SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B); if (ret <= 0) goto end; s->state=SSL3_ST_SW_FINISHED_A; s->init_num=0; if (!s->method->ssl3_enc->change_cipher_state(s, SSL3_CHANGE_CIPHER_SERVER_WRITE)) { ret= -1; goto end; } break; case SSL3_ST_SW_FINISHED_A: case SSL3_ST_SW_FINISHED_B: ret=ssl3_send_finished(s, SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B, s->method->ssl3_enc->server_finished_label, s->method->ssl3_enc->server_finished_label_len); if (ret <= 0) goto end; s->state=SSL3_ST_SW_FLUSH; if (s->hit) { #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A; #else if (s->s3->next_proto_neg_seen) { s->s3->tmp.next_state=SSL3_ST_SR_NEXT_PROTO_A; } else s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A; #endif } else s->s3->tmp.next_state=SSL_ST_OK; s->init_num=0; break; case SSL_ST_OK: /* clean a few things up */ ssl3_cleanup_key_block(s); BUF_MEM_free(s->init_buf); s->init_buf=NULL; /* remove buffering on output */ ssl_free_wbio_buffer(s); s->init_num=0; if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */ { s->renegotiate=0; s->new_session=0; ssl_update_cache(s,SSL_SESS_CACHE_SERVER); s->ctx->stats.sess_accept_good++; /* s->server=1; */ s->handshake_func=ssl3_accept; if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1); } ret = 1; goto end; /* break; */ default: SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE); ret= -1; goto end; /* break; */ } if (!s->s3->tmp.reuse_message && !skip) { if (s->debug) { if ((ret=BIO_flush(s->wbio)) <= 0) goto end; } if ((cb != NULL) && (s->state != state)) { new_state=s->state; s->state=state; cb(s,SSL_CB_ACCEPT_LOOP,1); s->state=new_state; } } skip=0; } end: /* BIO_flush(s->wbio); */ s->in_handshake--; if (cb != NULL) cb(s,SSL_CB_ACCEPT_EXIT,ret); return(ret); } int ssl3_send_hello_request(SSL *s) { if (s->state == SSL3_ST_SW_HELLO_REQ_A) { ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0); s->state=SSL3_ST_SW_HELLO_REQ_B; } /* SSL3_ST_SW_HELLO_REQ_B */ return ssl_do_write(s); } int ssl3_get_client_hello(SSL *s) { int i,j,ok,al=SSL_AD_INTERNAL_ERROR,ret= -1; unsigned int cookie_len; long n; unsigned long id; unsigned char *p,*d; SSL_CIPHER *c; #ifndef OPENSSL_NO_COMP unsigned char *q; SSL_COMP *comp=NULL; #endif STACK_OF(SSL_CIPHER) *ciphers=NULL; if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet) goto retry_cert; /* We do this so that we will respond with our native type. * If we are TLSv1 and we get SSLv3, we will respond with TLSv1, * This down switching should be handled by a different method. * If we are SSLv3, we will respond with SSLv3, even if prompted with * TLSv1. */ if (s->state == SSL3_ST_SR_CLNT_HELLO_A ) { s->state=SSL3_ST_SR_CLNT_HELLO_B; } s->first_packet=1; n=s->method->ssl_get_message(s, SSL3_ST_SR_CLNT_HELLO_B, SSL3_ST_SR_CLNT_HELLO_C, SSL3_MT_CLIENT_HELLO, SSL3_RT_MAX_PLAIN_LENGTH, &ok); if (!ok) return((int)n); s->first_packet=0; d=p=(unsigned char *)s->init_msg; /* use version from inside client hello, not from record header * (may differ: see RFC 2246, Appendix E, second paragraph) */ s->client_version=(((int)p[0])<<8)|(int)p[1]; p+=2; if (SSL_IS_DTLS(s) ? (s->client_version > s->version && s->method->version != DTLS_ANY_VERSION) : (s->client_version < s->version)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER); if ((s->client_version>>8) == SSL3_VERSION_MAJOR && !s->enc_write_ctx && !s->write_hash) { /* similar to ssl3_get_record, send alert using remote version number */ s->version = s->client_version; } al = SSL_AD_PROTOCOL_VERSION; goto f_err; } /* If we require cookies and this ClientHello doesn't * contain one, just return since we do not want to * allocate any memory yet. So check cookie length... */ if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) { unsigned int session_length, cookie_length; session_length = *(p + SSL3_RANDOM_SIZE); cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1); if (cookie_length == 0) return 1; } /* load the client random */ memcpy(s->s3->client_random,p,SSL3_RANDOM_SIZE); p+=SSL3_RANDOM_SIZE; /* get the session-id */ j= *(p++); s->hit=0; /* Versions before 0.9.7 always allow clients to resume sessions in renegotiation. * 0.9.7 and later allow this by default, but optionally ignore resumption requests * with flag SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather * than a change to default behavior so that applications relying on this for security * won't even compile against older library versions). * * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to request * renegotiation but not a new session (s->new_session remains unset): for servers, * this essentially just means that the SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION * setting will be ignored. */ if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) { if (!ssl_get_new_session(s,1)) goto err; } else { i=ssl_get_prev_session(s, p, j, d + n); /* * Only resume if the session's version matches the negotiated * version. * RFC 5246 does not provide much useful advice on resumption * with a different protocol version. It doesn't forbid it but * the sanity of such behaviour would be questionable. * In practice, clients do not accept a version mismatch and * will abort the handshake with an error. */ if (i == 1 && s->version == s->session->ssl_version) { /* previous session */ s->hit=1; } else if (i == -1) goto err; else /* i == 0 */ { if (!ssl_get_new_session(s,1)) goto err; } } p+=j; if (SSL_IS_DTLS(s)) { /* cookie stuff */ cookie_len = *(p++); /* * The ClientHello may contain a cookie even if the * HelloVerify message has not been sent--make sure that it * does not cause an overflow. */ if ( cookie_len > sizeof(s->d1->rcvd_cookie)) { /* too much data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } /* verify the cookie if appropriate option is set. */ if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) && cookie_len > 0) { memcpy(s->d1->rcvd_cookie, p, cookie_len); if ( s->ctx->app_verify_cookie_cb != NULL) { if ( s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie, cookie_len) == 0) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } /* else cookie verification succeeded */ } else if ( memcmp(s->d1->rcvd_cookie, s->d1->cookie, s->d1->cookie_len) != 0) /* default verification */ { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } /* Set to -2 so if successful we return 2 */ ret = -2; } p += cookie_len; if (s->method->version == DTLS_ANY_VERSION) { /* Select version to use */ if (s->client_version <= DTLS1_2_VERSION && !(s->options & SSL_OP_NO_DTLSv1_2)) { s->version = DTLS1_2_VERSION; s->method = DTLSv1_2_server_method(); } else if (tls1_suiteb(s)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE); s->version = s->client_version; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } else if (s->client_version <= DTLS1_VERSION && !(s->options & SSL_OP_NO_DTLSv1)) { s->version = DTLS1_VERSION; s->method = DTLSv1_server_method(); } else { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER); s->version = s->client_version; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } s->session->ssl_version = s->version; } } n2s(p,i); if ((i == 0) && (j != 0)) { /* we need a cipher if we are not resuming a session */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_SPECIFIED); goto f_err; } if ((p+i) >= (d+n)) { /* not enough data */ al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH); goto f_err; } if ((i > 0) && (ssl_bytes_to_cipher_list(s,p,i,&(ciphers)) == NULL)) { goto err; } p+=i; /* If it is a hit, check that the cipher is in the list */ if ((s->hit) && (i > 0)) { j=0; id=s->session->cipher->id; #ifdef CIPHER_DEBUG fprintf(stderr,"client sent %d ciphers\n",sk_SSL_CIPHER_num(ciphers)); #endif for (i=0; i<sk_SSL_CIPHER_num(ciphers); i++) { c=sk_SSL_CIPHER_value(ciphers,i); #ifdef CIPHER_DEBUG fprintf(stderr,"client [%2d of %2d]:%s\n", i,sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c)); #endif if (c->id == id) { j=1; break; } } /* Disabled because it can be used in a ciphersuite downgrade * attack: CVE-2010-4180. */ #if 0 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1)) { /* Special case as client bug workaround: the previously used cipher may * not be in the current list, the client instead might be trying to * continue using a cipher that before wasn't chosen due to server * preferences. We'll have to reject the connection if the cipher is not * enabled, though. */ c = sk_SSL_CIPHER_value(ciphers, 0); if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) { s->session->cipher = c; j = 1; } } #endif if (j == 0) { /* we need to have the cipher in the cipher * list if we are asked to reuse it */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_CIPHER_MISSING); goto f_err; } } /* compression */ i= *(p++); if ((p+i) > (d+n)) { /* not enough data */ al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH); goto f_err; } #ifndef OPENSSL_NO_COMP q=p; #endif for (j=0; j<i; j++) { if (p[j] == 0) break; } p+=i; if (j >= i) { /* no compress */ al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_COMPRESSION_SPECIFIED); goto f_err; } #ifndef OPENSSL_NO_TLSEXT /* TLS extensions*/ if (s->version >= SSL3_VERSION) { if (!ssl_parse_clienthello_tlsext(s,&p,d,n)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_PARSE_TLSEXT); goto err; } } /* Check if we want to use external pre-shared secret for this * handshake for not reused session only. We need to generate * server_random before calling tls_session_secret_cb in order to allow * SessionTicket processing to use it in key derivation. */ { unsigned char *pos; pos=s->s3->server_random; if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) { goto f_err; } } if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) { SSL_CIPHER *pref_cipher=NULL; s->session->master_key_length=sizeof(s->session->master_key); if(s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length, ciphers, &pref_cipher, s->tls_session_secret_cb_arg)) { s->hit=1; s->session->ciphers=ciphers; s->session->verify_result=X509_V_OK; ciphers=NULL; /* check if some cipher was preferred by call back */ pref_cipher=pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s)); if (pref_cipher == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER); goto f_err; } s->session->cipher=pref_cipher; if (s->cipher_list) sk_SSL_CIPHER_free(s->cipher_list); if (s->cipher_list_by_id) sk_SSL_CIPHER_free(s->cipher_list_by_id); s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers); s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers); } } #endif /* Worst case, we will use the NULL compression, but if we have other * options, we will now look for them. We have i-1 compression * algorithms from the client, starting at q. */ s->s3->tmp.new_compression=NULL; #ifndef OPENSSL_NO_COMP /* This only happens if we have a cache hit */ if (s->session->compress_meth != 0) { int m, comp_id = s->session->compress_meth; /* Perform sanity checks on resumed compression algorithm */ /* Can't disable compression */ if (!ssl_allow_compression(s)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } /* Look for resumed compression method */ for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) { comp=sk_SSL_COMP_value(s->ctx->comp_methods,m); if (comp_id == comp->id) { s->s3->tmp.new_compression=comp; break; } } if (s->s3->tmp.new_compression == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INVALID_COMPRESSION_ALGORITHM); goto f_err; } /* Look for resumed method in compression list */ for (m = 0; m < i; m++) { if (q[m] == comp_id) break; } if (m >= i) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING); goto f_err; } } else if (s->hit) comp = NULL; else if (ssl_allow_compression(s) && s->ctx->comp_methods) { /* See if we have a match */ int m,nn,o,v,done=0; nn=sk_SSL_COMP_num(s->ctx->comp_methods); for (m=0; m<nn; m++) { comp=sk_SSL_COMP_value(s->ctx->comp_methods,m); v=comp->id; for (o=0; o<i; o++) { if (v == q[o]) { done=1; break; } } if (done) break; } if (done) s->s3->tmp.new_compression=comp; else comp=NULL; } #else /* If compression is disabled we'd better not try to resume a session * using compression. */ if (s->session->compress_meth != 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } #endif /* Given s->session->ciphers and SSL_get_ciphers, we must * pick a cipher */ if (!s->hit) { #ifdef OPENSSL_NO_COMP s->session->compress_meth=0; #else s->session->compress_meth=(comp == NULL)?0:comp->id; #endif if (s->session->ciphers != NULL) sk_SSL_CIPHER_free(s->session->ciphers); s->session->ciphers=ciphers; if (ciphers == NULL) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_PASSED); goto f_err; } ciphers=NULL; if (!tls1_set_server_sigalgs(s)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); goto err; } /* Let cert callback update server certificates if required */ retry_cert: if (s->cert->cert_cb) { int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg); if (rv == 0) { al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_CERT_CB_ERROR); goto f_err; } if (rv < 0) { s->rwstate=SSL_X509_LOOKUP; return -1; } s->rwstate = SSL_NOTHING; } c=ssl3_choose_cipher(s,s->session->ciphers, SSL_get_ciphers(s)); if (c == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER); goto f_err; } s->s3->tmp.new_cipher=c; /* check whether we should disable session resumption */ if (s->not_resumable_session_cb != NULL) s->session->not_resumable=s->not_resumable_session_cb(s, ((c->algorithm_mkey & (SSL_kDHE | SSL_kECDHE)) != 0)); if (s->session->not_resumable) /* do not send a session ticket */ s->tlsext_ticket_expected = 0; } else { /* Session-id reuse */ #ifdef REUSE_CIPHER_BUG STACK_OF(SSL_CIPHER) *sk; SSL_CIPHER *nc=NULL; SSL_CIPHER *ec=NULL; if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG) { sk=s->session->ciphers; for (i=0; i<sk_SSL_CIPHER_num(sk); i++) { c=sk_SSL_CIPHER_value(sk,i); if (c->algorithm_enc & SSL_eNULL) nc=c; if (SSL_C_IS_EXPORT(c)) ec=c; } if (nc != NULL) s->s3->tmp.new_cipher=nc; else if (ec != NULL) s->s3->tmp.new_cipher=ec; else s->s3->tmp.new_cipher=s->session->cipher; } else #endif s->s3->tmp.new_cipher=s->session->cipher; } if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) { if (!ssl3_digest_cached_records(s)) goto f_err; } /*- * we now have the following setup. * client_random * cipher_list - our prefered list of ciphers * ciphers - the clients prefered list of ciphers * compression - basically ignored right now * ssl version is set - sslv3 * s->session - The ssl session has been setup. * s->hit - session reuse flag * s->s3->tmp.new_cipher- the new cipher to use. */ /* Handles TLS extensions that we couldn't check earlier */ if (s->version >= SSL3_VERSION) { if (ssl_check_clienthello_tlsext_late(s) <= 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); goto err; } } if (ret < 0) ret=-ret; if (0) { f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); } err: if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers); return ret < 0 ? -1 : ret; } int ssl3_send_server_hello(SSL *s) { unsigned char *buf; unsigned char *p,*d; int i,sl; int al = 0; unsigned long l; if (s->state == SSL3_ST_SW_SRVR_HELLO_A) { buf=(unsigned char *)s->init_buf->data; #ifdef OPENSSL_NO_TLSEXT p=s->s3->server_random; if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0) return -1; #endif /* Do the message type and length last */ d=p= ssl_handshake_start(s); *(p++)=s->version>>8; *(p++)=s->version&0xff; /* Random stuff */ memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE); p+=SSL3_RANDOM_SIZE; /*- * There are several cases for the session ID to send * back in the server hello: * - For session reuse from the session cache, * we send back the old session ID. * - If stateless session reuse (using a session ticket) * is successful, we send back the client's "session ID" * (which doesn't actually identify the session). * - If it is a new session, we send back the new * session ID. * - However, if we want the new session to be single-use, * we send back a 0-length session ID. * s->hit is non-zero in either case of session reuse, * so the following won't overwrite an ID that we're supposed * to send back. */ if (s->session->not_resumable || (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER) && !s->hit)) s->session->session_id_length=0; sl=s->session->session_id_length; if (sl > (int)sizeof(s->session->session_id)) { SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR); return -1; } *(p++)=sl; memcpy(p,s->session->session_id,sl); p+=sl; /* put the cipher */ i=ssl3_put_cipher_by_char(s->s3->tmp.new_cipher,p); p+=i; /* put the compression method */ #ifdef OPENSSL_NO_COMP *(p++)=0; #else if (s->s3->tmp.new_compression == NULL) *(p++)=0; else *(p++)=s->s3->tmp.new_compression->id; #endif #ifndef OPENSSL_NO_TLSEXT if (ssl_prepare_serverhello_tlsext(s) <= 0) { SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT); return -1; } if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH, &al)) == NULL) { ssl3_send_alert(s, SSL3_AL_FATAL, al); SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,ERR_R_INTERNAL_ERROR); return -1; } #endif /* do the header */ l=(p-d); ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l); s->state=SSL3_ST_SW_SRVR_HELLO_B; } /* SSL3_ST_SW_SRVR_HELLO_B */ return ssl_do_write(s); } int ssl3_send_server_done(SSL *s) { if (s->state == SSL3_ST_SW_SRVR_DONE_A) { ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0); s->state = SSL3_ST_SW_SRVR_DONE_B; } /* SSL3_ST_SW_SRVR_DONE_B */ return ssl_do_write(s); } int ssl3_send_server_key_exchange(SSL *s) { #ifndef OPENSSL_NO_RSA unsigned char *q; int j,num; RSA *rsa; unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH]; unsigned int u; #endif #ifndef OPENSSL_NO_DH DH *dh=NULL,*dhp; #endif #ifndef OPENSSL_NO_ECDH EC_KEY *ecdh=NULL, *ecdhp; unsigned char *encodedPoint = NULL; int encodedlen = 0; int curve_id = 0; BN_CTX *bn_ctx = NULL; #endif EVP_PKEY *pkey; const EVP_MD *md = NULL; unsigned char *p,*d; int al,i; unsigned long type; int n; CERT *cert; BIGNUM *r[4]; int nr[4],kn; BUF_MEM *buf; EVP_MD_CTX md_ctx; EVP_MD_CTX_init(&md_ctx); if (s->state == SSL3_ST_SW_KEY_EXCH_A) { type=s->s3->tmp.new_cipher->algorithm_mkey; cert=s->cert; buf=s->init_buf; r[0]=r[1]=r[2]=r[3]=NULL; n=0; #ifndef OPENSSL_NO_RSA if (type & SSL_kRSA) { rsa=cert->rsa_tmp; if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) { rsa=s->cert->rsa_tmp_cb(s, SSL_C_IS_EXPORT(s->s3->tmp.new_cipher), SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)); if(rsa == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ERROR_GENERATING_TMP_RSA_KEY); goto f_err; } RSA_up_ref(rsa); cert->rsa_tmp=rsa; } if (rsa == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_KEY); goto f_err; } r[0]=rsa->n; r[1]=rsa->e; s->s3->tmp.use_rsa_tmp=1; } else #endif #ifndef OPENSSL_NO_DH if (type & SSL_kDHE) { if (s->cert->dh_tmp_auto) { dhp = ssl_get_auto_dh(s); if (dhp == NULL) { al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto f_err; } } else dhp=cert->dh_tmp; if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL)) dhp=s->cert->dh_tmp_cb(s, SSL_C_IS_EXPORT(s->s3->tmp.new_cipher), SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)); if (dhp == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY); goto f_err; } if (!ssl_security(s, SSL_SECOP_TMP_DH, DH_security_bits(dhp), 0, dhp)) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_DH_KEY_TOO_SMALL); goto f_err; } if (s->s3->tmp.dh != NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } if (s->cert->dh_tmp_auto) dh = dhp; else if ((dh=DHparams_dup(dhp)) == NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB); goto err; } s->s3->tmp.dh=dh; if ((dhp->pub_key == NULL || dhp->priv_key == NULL || (s->options & SSL_OP_SINGLE_DH_USE))) { if(!DH_generate_key(dh)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } } else { dh->pub_key=BN_dup(dhp->pub_key); dh->priv_key=BN_dup(dhp->priv_key); if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB); goto err; } } r[0]=dh->p; r[1]=dh->g; r[2]=dh->pub_key; } else #endif #ifndef OPENSSL_NO_ECDH if (type & SSL_kECDHE) { const EC_GROUP *group; ecdhp=cert->ecdh_tmp; if (s->cert->ecdh_tmp_auto) { /* Get NID of appropriate shared curve */ int nid = tls1_shared_curve(s, -2); if (nid != NID_undef) ecdhp = EC_KEY_new_by_curve_name(nid); } else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb) { ecdhp=s->cert->ecdh_tmp_cb(s, SSL_C_IS_EXPORT(s->s3->tmp.new_cipher), SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)); } if (ecdhp == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY); goto f_err; } if (s->s3->tmp.ecdh != NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } /* Duplicate the ECDH structure. */ if (ecdhp == NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB); goto err; } if (s->cert->ecdh_tmp_auto) ecdh = ecdhp; else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB); goto err; } s->s3->tmp.ecdh=ecdh; if ((EC_KEY_get0_public_key(ecdh) == NULL) || (EC_KEY_get0_private_key(ecdh) == NULL) || (s->options & SSL_OP_SINGLE_ECDH_USE)) { if(!EC_KEY_generate_key(ecdh)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB); goto err; } } if (((group = EC_KEY_get0_group(ecdh)) == NULL) || (EC_KEY_get0_public_key(ecdh) == NULL) || (EC_KEY_get0_private_key(ecdh) == NULL)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB); goto err; } if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && (EC_GROUP_get_degree(group) > 163)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER); goto err; } /* XXX: For now, we only support ephemeral ECDH * keys over named (not generic) curves. For * supported named curves, curve_id is non-zero. */ if ((curve_id = tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group))) == 0) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNSUPPORTED_ELLIPTIC_CURVE); goto err; } /* Encode the public key. * First check the size of encoding and * allocate memory accordingly. */ encodedlen = EC_POINT_point2oct(group, EC_KEY_get0_public_key(ecdh), POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL); encodedPoint = (unsigned char *) OPENSSL_malloc(encodedlen*sizeof(unsigned char)); bn_ctx = BN_CTX_new(); if ((encodedPoint == NULL) || (bn_ctx == NULL)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } encodedlen = EC_POINT_point2oct(group, EC_KEY_get0_public_key(ecdh), POINT_CONVERSION_UNCOMPRESSED, encodedPoint, encodedlen, bn_ctx); if (encodedlen == 0) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB); goto err; } BN_CTX_free(bn_ctx); bn_ctx=NULL; /* XXX: For now, we only support named (not * generic) curves in ECDH ephemeral key exchanges. * In this situation, we need four additional bytes * to encode the entire ServerECDHParams * structure. */ n = 4 + encodedlen; /* We'll generate the serverKeyExchange message * explicitly so we can set these to NULLs */ r[0]=NULL; r[1]=NULL; r[2]=NULL; r[3]=NULL; } else #endif /* !OPENSSL_NO_ECDH */ #ifndef OPENSSL_NO_PSK if (type & SSL_kPSK) { /* reserve size for record length and PSK identity hint*/ n+=2+strlen(s->ctx->psk_identity_hint); } else #endif /* !OPENSSL_NO_PSK */ #ifndef OPENSSL_NO_SRP if (type & SSL_kSRP) { if ((s->srp_ctx.N == NULL) || (s->srp_ctx.g == NULL) || (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_SRP_PARAM); goto err; } r[0]=s->srp_ctx.N; r[1]=s->srp_ctx.g; r[2]=s->srp_ctx.s; r[3]=s->srp_ctx.B; } else #endif { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE); goto f_err; } for (i=0; i < 4 && r[i] != NULL; i++) { nr[i]=BN_num_bytes(r[i]); #ifndef OPENSSL_NO_SRP if ((i == 2) && (type & SSL_kSRP)) n+=1+nr[i]; else #endif n+=2+nr[i]; } if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP)) && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher,&md)) == NULL) { al=SSL_AD_DECODE_ERROR; goto f_err; } kn=EVP_PKEY_size(pkey); } else { pkey=NULL; kn=0; } if (!BUF_MEM_grow_clean(buf,n+SSL_HM_HEADER_LENGTH(s)+kn)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF); goto err; } d = p = ssl_handshake_start(s); for (i=0; i < 4 && r[i] != NULL; i++) { #ifndef OPENSSL_NO_SRP if ((i == 2) && (type & SSL_kSRP)) { *p = nr[i]; p++; } else #endif s2n(nr[i],p); BN_bn2bin(r[i],p); p+=nr[i]; } #ifndef OPENSSL_NO_ECDH if (type & SSL_kECDHE) { /* XXX: For now, we only support named (not generic) curves. * In this situation, the serverKeyExchange message has: * [1 byte CurveType], [2 byte CurveName] * [1 byte length of encoded point], followed by * the actual encoded point itself */ *p = NAMED_CURVE_TYPE; p += 1; *p = 0; p += 1; *p = curve_id; p += 1; *p = encodedlen; p += 1; memcpy((unsigned char*)p, (unsigned char *)encodedPoint, encodedlen); OPENSSL_free(encodedPoint); encodedPoint = NULL; p += encodedlen; } #endif #ifndef OPENSSL_NO_PSK if (type & SSL_kPSK) { /* copy PSK identity hint */ s2n(strlen(s->ctx->psk_identity_hint), p); strncpy((char *)p, s->ctx->psk_identity_hint, strlen(s->ctx->psk_identity_hint)); p+=strlen(s->ctx->psk_identity_hint); } #endif /* not anonymous */ if (pkey != NULL) { /* n is the length of the params, they start at &(d[4]) * and p points to the space at the end. */ #ifndef OPENSSL_NO_RSA if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) { q=md_buf; j=0; for (num=2; num > 0; num--) { EVP_MD_CTX_set_flags(&md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); EVP_DigestInit_ex(&md_ctx,(num == 2) ?s->ctx->md5:s->ctx->sha1, NULL); EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,d,n); EVP_DigestFinal_ex(&md_ctx,q, (unsigned int *)&i); q+=i; j+=i; } if (RSA_sign(NID_md5_sha1, md_buf, j, &(p[2]), &u, pkey->pkey.rsa) <= 0) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_RSA); goto err; } s2n(u,p); n+=u+2; } else #endif if (md) { /* send signature algorithm */ if (SSL_USE_SIGALGS(s)) { if (!tls12_get_sigandhash(p, pkey, md)) { /* Should never happen */ al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto f_err; } p+=2; } #ifdef SSL_DEBUG fprintf(stderr, "Using hash %s\n", EVP_MD_name(md)); #endif EVP_SignInit_ex(&md_ctx, md, NULL); EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_SignUpdate(&md_ctx,d,n); if (!EVP_SignFinal(&md_ctx,&(p[2]), (unsigned int *)&i,pkey)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_EVP); goto err; } s2n(i,p); n+=i+2; if (SSL_USE_SIGALGS(s)) n+= 2; } else { /* Is this error check actually needed? */ al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_PKEY_TYPE); goto f_err; } } ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n); } s->state = SSL3_ST_SW_KEY_EXCH_B; EVP_MD_CTX_cleanup(&md_ctx); return ssl_do_write(s); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: #ifndef OPENSSL_NO_ECDH if (encodedPoint != NULL) OPENSSL_free(encodedPoint); BN_CTX_free(bn_ctx); #endif EVP_MD_CTX_cleanup(&md_ctx); return(-1); } int ssl3_send_certificate_request(SSL *s) { unsigned char *p,*d; int i,j,nl,off,n; STACK_OF(X509_NAME) *sk=NULL; X509_NAME *name; BUF_MEM *buf; if (s->state == SSL3_ST_SW_CERT_REQ_A) { buf=s->init_buf; d=p=ssl_handshake_start(s); /* get the list of acceptable cert types */ p++; n=ssl3_get_req_cert_type(s,p); d[0]=n; p+=n; n++; if (SSL_USE_SIGALGS(s)) { const unsigned char *psigs; unsigned char *etmp = p; nl = tls12_get_psigalgs(s, &psigs); /* Skip over length for now */ p += 2; nl = tls12_copy_sigalgs(s, p, psigs, nl); /* Now fill in length */ s2n(nl, etmp); p += nl; n += nl + 2; } off=n; p+=2; n+=2; sk=SSL_get_client_CA_list(s); nl=0; if (sk != NULL) { for (i=0; i<sk_X509_NAME_num(sk); i++) { name=sk_X509_NAME_value(sk,i); j=i2d_X509_NAME(name,NULL); if (!BUF_MEM_grow_clean(buf,SSL_HM_HEADER_LENGTH(s)+n+j+2)) { SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB); goto err; } p = ssl_handshake_start(s) + n; if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG)) { s2n(j,p); i2d_X509_NAME(name,&p); n+=2+j; nl+=2+j; } else { d=p; i2d_X509_NAME(name,&p); j-=2; s2n(j,d); j+=2; n+=j; nl+=j; } } } /* else no CA names */ p = ssl_handshake_start(s) + off; s2n(nl,p); ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n); #ifdef NETSCAPE_HANG_BUG if (!SSL_IS_DTLS(s)) { if (!BUF_MEM_grow_clean(buf, s->init_num + 4)) { SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB); goto err; } p=(unsigned char *)s->init_buf->data + s->init_num; /* do the header */ *(p++)=SSL3_MT_SERVER_DONE; *(p++)=0; *(p++)=0; *(p++)=0; s->init_num += 4; } #endif s->state = SSL3_ST_SW_CERT_REQ_B; } /* SSL3_ST_SW_CERT_REQ_B */ return ssl_do_write(s); err: return(-1); } int ssl3_get_client_key_exchange(SSL *s) { int i,al,ok; long n; unsigned long alg_k; unsigned char *p; #ifndef OPENSSL_NO_RSA RSA *rsa=NULL; EVP_PKEY *pkey=NULL; #endif #ifndef OPENSSL_NO_DH BIGNUM *pub=NULL; DH *dh_srvr, *dh_clnt = NULL; #endif #ifndef OPENSSL_NO_KRB5 KSSL_ERR kssl_err; #endif /* OPENSSL_NO_KRB5 */ #ifndef OPENSSL_NO_ECDH EC_KEY *srvr_ecdh = NULL; EVP_PKEY *clnt_pub_pkey = NULL; EC_POINT *clnt_ecpoint = NULL; BN_CTX *bn_ctx = NULL; #endif n=s->method->ssl_get_message(s, SSL3_ST_SR_KEY_EXCH_A, SSL3_ST_SR_KEY_EXCH_B, SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, /* ??? */ &ok); if (!ok) return((int)n); p=(unsigned char *)s->init_msg; alg_k=s->s3->tmp.new_cipher->algorithm_mkey; #ifndef OPENSSL_NO_RSA if (alg_k & SSL_kRSA) { unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH]; int decrypt_len; unsigned char decrypt_good, version_good; size_t j; /* FIX THIS UP EAY EAY EAY EAY */ if (s->s3->tmp.use_rsa_tmp) { if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL)) rsa=s->cert->rsa_tmp; /* Don't do a callback because rsa_tmp should * be sent already */ if (rsa == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_PKEY); goto f_err; } } else { pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey; if ( (pkey == NULL) || (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE); goto f_err; } rsa=pkey->pkey.rsa; } /* TLS and [incidentally] DTLS{0xFEFF} */ if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER) { n2s(p,i); if (n != i+2) { if (!(s->options & SSL_OP_TLS_D5_BUG)) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG); goto f_err; } else p-=2; } else n=i; } /* * Reject overly short RSA ciphertext because we want to be sure * that the buffer size makes it safe to iterate over the entire * size of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The * actual expected size is larger due to RSA padding, but the * bound is sufficient to be safe. */ if (n < SSL_MAX_MASTER_KEY_LENGTH) { al = SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG); goto f_err; } /* We must not leak whether a decryption failure occurs because * of Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see * RFC 2246, section 7.4.7.1). The code follows that advice of * the TLS RFC and generates a random premaster secret for the * case that the decrypt fails. See * https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */ /* should be RAND_bytes, but we cannot work around a failure. */ if (RAND_pseudo_bytes(rand_premaster_secret, sizeof(rand_premaster_secret)) <= 0) goto err; decrypt_len = RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING); ERR_clear_error(); /* decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. * decrypt_good will be 0xff if so and zero otherwise. */ decrypt_good = constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH); /* If the version in the decrypted pre-master secret is correct * then version_good will be 0xff, otherwise it'll be zero. * The Klima-Pokorny-Rosa extension of Bleichenbacher's attack * (http://eprint.iacr.org/2003/052/) exploits the version * number check as a "bad version oracle". Thus version checks * are done in constant time and are treated like any other * decryption error. */ version_good = constant_time_eq_8(p[0], (unsigned)(s->client_version>>8)); version_good &= constant_time_eq_8(p[1], (unsigned)(s->client_version&0xff)); /* The premaster secret must contain the same version number as * the ClientHello to detect version rollback attacks * (strangely, the protocol does not offer such protection for * DH ciphersuites). However, buggy clients exist that send the * negotiated protocol version instead if the server does not * support the requested protocol version. If * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */ if (s->options & SSL_OP_TLS_ROLLBACK_BUG) { unsigned char workaround_good; workaround_good = constant_time_eq_8(p[0], (unsigned)(s->version>>8)); workaround_good &= constant_time_eq_8(p[1], (unsigned)(s->version&0xff)); version_good |= workaround_good; } /* Both decryption and version must be good for decrypt_good * to remain non-zero (0xff). */ decrypt_good &= version_good; /* * Now copy rand_premaster_secret over from p using * decrypt_good_mask. If decryption failed, then p does not * contain valid plaintext, however, a check above guarantees * it is still sufficiently large to read from. */ for (j = 0; j < sizeof(rand_premaster_secret); j++) { p[j] = constant_time_select_8(decrypt_good, p[j], rand_premaster_secret[j]); } s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key, p,sizeof(rand_premaster_secret)); OPENSSL_cleanse(p,sizeof(rand_premaster_secret)); } else #endif #ifndef OPENSSL_NO_DH if (alg_k & (SSL_kDHE|SSL_kDHr|SSL_kDHd)) { int idx = -1; EVP_PKEY *skey = NULL; if (n) n2s(p,i); else i = 0; if (n && n != i+2) { if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG); goto err; } else { p-=2; i=(int)n; } } if (alg_k & SSL_kDHr) idx = SSL_PKEY_DH_RSA; else if (alg_k & SSL_kDHd) idx = SSL_PKEY_DH_DSA; if (idx >= 0) { skey = s->cert->pkeys[idx].privatekey; if ((skey == NULL) || (skey->type != EVP_PKEY_DH) || (skey->pkey.dh == NULL)) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE); goto f_err; } dh_srvr = skey->pkey.dh; } else if (s->s3->tmp.dh == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY); goto f_err; } else dh_srvr=s->s3->tmp.dh; if (n == 0L) { /* Get pubkey from cert */ EVP_PKEY *clkey=X509_get_pubkey(s->session->peer); if (clkey) { if (EVP_PKEY_cmp_parameters(clkey, skey) == 1) dh_clnt = EVP_PKEY_get1_DH(clkey); } if (dh_clnt == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY); goto f_err; } EVP_PKEY_free(clkey); pub = dh_clnt->pub_key; } else pub=BN_bin2bn(p,i,NULL); if (pub == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BN_LIB); goto err; } i=DH_compute_key(p,pub,dh_srvr); if (i <= 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); BN_clear_free(pub); goto err; } DH_free(s->s3->tmp.dh); s->s3->tmp.dh=NULL; if (dh_clnt) DH_free(dh_clnt); else BN_clear_free(pub); pub=NULL; s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key,p,i); OPENSSL_cleanse(p,i); if (dh_clnt) return 2; } else #endif #ifndef OPENSSL_NO_KRB5 if (alg_k & SSL_kKRB5) { krb5_error_code krb5rc; krb5_data enc_ticket; krb5_data authenticator; krb5_data enc_pms; KSSL_CTX *kssl_ctx = s->kssl_ctx; EVP_CIPHER_CTX ciph_ctx; const EVP_CIPHER *enc = NULL; unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_BLOCK_LENGTH]; int padl, outl; krb5_timestamp authtime = 0; krb5_ticket_times ttimes; EVP_CIPHER_CTX_init(&ciph_ctx); if (!kssl_ctx) kssl_ctx = kssl_ctx_new(); n2s(p,i); enc_ticket.length = i; if (n < (long)(enc_ticket.length + 6)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto err; } enc_ticket.data = (char *)p; p+=enc_ticket.length; n2s(p,i); authenticator.length = i; if (n < (long)(enc_ticket.length + authenticator.length + 6)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto err; } authenticator.data = (char *)p; p+=authenticator.length; n2s(p,i); enc_pms.length = i; enc_pms.data = (char *)p; p+=enc_pms.length; /* Note that the length is checked again below, ** after decryption */ if(enc_pms.length > sizeof pms) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto err; } if (n != (long)(enc_ticket.length + authenticator.length + enc_pms.length + 6)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto err; } if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes, &kssl_err)) != 0) { #ifdef KSSL_DEBUG fprintf(stderr,"kssl_sget_tkt rtn %d [%d]\n", krb5rc, kssl_err.reason); if (kssl_err.text) fprintf(stderr,"kssl_err text= %s\n", kssl_err.text); #endif /* KSSL_DEBUG */ SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason); goto err; } /* Note: no authenticator is not considered an error, ** but will return authtime == 0. */ if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator, &authtime, &kssl_err)) != 0) { #ifdef KSSL_DEBUG fprintf(stderr,"kssl_check_authent rtn %d [%d]\n", krb5rc, kssl_err.reason); if (kssl_err.text) fprintf(stderr,"kssl_err text= %s\n", kssl_err.text); #endif /* KSSL_DEBUG */ SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason); goto err; } if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc); goto err; } #ifdef KSSL_DEBUG kssl_ctx_show(kssl_ctx); #endif /* KSSL_DEBUG */ enc = kssl_map_enc(kssl_ctx->enctype); if (enc == NULL) goto err; memset(iv, 0, sizeof iv); /* per RFC 1510 */ if (!EVP_DecryptInit_ex(&ciph_ctx,enc,NULL,kssl_ctx->key,iv)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DECRYPTION_FAILED); goto err; } if (!EVP_DecryptUpdate(&ciph_ctx, pms,&outl, (unsigned char *)enc_pms.data, enc_pms.length)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DECRYPTION_FAILED); goto err; } if (outl > SSL_MAX_MASTER_KEY_LENGTH) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto err; } if (!EVP_DecryptFinal_ex(&ciph_ctx,&(pms[outl]),&padl)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DECRYPTION_FAILED); goto err; } outl += padl; if (outl > SSL_MAX_MASTER_KEY_LENGTH) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto err; } if (!((pms[0] == (s->client_version>>8)) && (pms[1] == (s->client_version & 0xff)))) { /* The premaster secret must contain the same version number as the * ClientHello to detect version rollback attacks (strangely, the * protocol does not offer such protection for DH ciphersuites). * However, buggy clients exist that send random bytes instead of * the protocol version. * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. * (Perhaps we should have a separate BUG value for the Kerberos cipher) */ if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_AD_DECODE_ERROR); goto err; } } EVP_CIPHER_CTX_cleanup(&ciph_ctx); s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key, pms, outl); if (kssl_ctx->client_princ) { size_t len = strlen(kssl_ctx->client_princ); if ( len < SSL_MAX_KRB5_PRINCIPAL_LENGTH ) { s->session->krb5_client_princ_len = len; memcpy(s->session->krb5_client_princ,kssl_ctx->client_princ,len); } } /*- Was doing kssl_ctx_free() here, * but it caused problems for apache. * kssl_ctx = kssl_ctx_free(kssl_ctx); * if (s->kssl_ctx) s->kssl_ctx = NULL; */ } else #endif /* OPENSSL_NO_KRB5 */ #ifndef OPENSSL_NO_ECDH if (alg_k & (SSL_kECDHE|SSL_kECDHr|SSL_kECDHe)) { int ret = 1; int field_size = 0; const EC_KEY *tkey; const EC_GROUP *group; const BIGNUM *priv_key; /* initialize structures for server's ECDH key pair */ if ((srvr_ecdh = EC_KEY_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } /* Let's get server private key and group information */ if (alg_k & (SSL_kECDHr|SSL_kECDHe)) { /* use the certificate */ tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec; } else { /* use the ephermeral values we saved when * generating the ServerKeyExchange msg. */ tkey = s->s3->tmp.ecdh; } group = EC_KEY_get0_group(tkey); priv_key = EC_KEY_get0_private_key(tkey); if (!EC_KEY_set_group(srvr_ecdh, group) || !EC_KEY_set_private_key(srvr_ecdh, priv_key)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB); goto err; } /* Let's get client's public key */ if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } if (n == 0L) { /* Client Publickey was in Client Certificate */ if (alg_k & SSL_kECDHE) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY); goto f_err; } if (((clnt_pub_pkey=X509_get_pubkey(s->session->peer)) == NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) { /* XXX: For now, we do not support client * authentication using ECDH certificates * so this branch (n == 0L) of the code is * never executed. When that support is * added, we ought to ensure the key * received in the certificate is * authorized for key agreement. * ECDH_compute_key implicitly checks that * the two ECDH shares are for the same * group. */ al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNABLE_TO_DECODE_ECDH_CERTS); goto f_err; } if (EC_POINT_copy(clnt_ecpoint, EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec)) == 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB); goto err; } ret = 2; /* Skip certificate verify processing */ } else { /* Get client's public key from encoded point * in the ClientKeyExchange message. */ if ((bn_ctx = BN_CTX_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } /* Get encoded point length */ i = *p; p += 1; if (n != 1 + i) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB); goto err; } if (EC_POINT_oct2point(group, clnt_ecpoint, p, i, bn_ctx) == 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB); goto err; } /* p is pointing to somewhere in the buffer * currently, so set it to the start */ p=(unsigned char *)s->init_buf->data; } /* Compute the shared pre-master secret */ field_size = EC_GROUP_get_degree(group); if (field_size <= 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } i = ECDH_compute_key(p, (field_size+7)/8, clnt_ecpoint, srvr_ecdh, NULL); if (i <= 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } EVP_PKEY_free(clnt_pub_pkey); EC_POINT_free(clnt_ecpoint); EC_KEY_free(srvr_ecdh); BN_CTX_free(bn_ctx); EC_KEY_free(s->s3->tmp.ecdh); s->s3->tmp.ecdh = NULL; /* Compute the master secret */ s->session->master_key_length = s->method->ssl3_enc-> \ generate_master_secret(s, s->session->master_key, p, i); OPENSSL_cleanse(p, i); return (ret); } else #endif #ifndef OPENSSL_NO_PSK if (alg_k & SSL_kPSK) { unsigned char *t = NULL; unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4]; unsigned int pre_ms_len = 0, psk_len = 0; int psk_err = 1; char tmp_id[PSK_MAX_IDENTITY_LEN+1]; al=SSL_AD_HANDSHAKE_FAILURE; n2s(p,i); if (n != i+2) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH); goto psk_err; } if (i > PSK_MAX_IDENTITY_LEN) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto psk_err; } if (s->psk_server_callback == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_PSK_NO_SERVER_CB); goto psk_err; } /* Create guaranteed NULL-terminated identity * string for the callback */ memcpy(tmp_id, p, i); memset(tmp_id+i, 0, PSK_MAX_IDENTITY_LEN+1-i); psk_len = s->psk_server_callback(s, tmp_id, psk_or_pre_ms, sizeof(psk_or_pre_ms)); OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN+1); if (psk_len > PSK_MAX_PSK_LEN) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto psk_err; } else if (psk_len == 0) { /* PSK related to the given identity not found */ SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_PSK_IDENTITY_NOT_FOUND); al=SSL_AD_UNKNOWN_PSK_IDENTITY; goto psk_err; } /* create PSK pre_master_secret */ pre_ms_len=2+psk_len+2+psk_len; t = psk_or_pre_ms; memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len); s2n(psk_len, t); memset(t, 0, psk_len); t+=psk_len; s2n(psk_len, t); if (s->session->psk_identity != NULL) OPENSSL_free(s->session->psk_identity); s->session->psk_identity = BUF_strdup((char *)p); if (s->session->psk_identity == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto psk_err; } if (s->session->psk_identity_hint != NULL) OPENSSL_free(s->session->psk_identity_hint); s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint); if (s->ctx->psk_identity_hint != NULL && s->session->psk_identity_hint == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto psk_err; } s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key, psk_or_pre_ms, pre_ms_len); psk_err = 0; psk_err: OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms)); if (psk_err != 0) goto f_err; } else #endif #ifndef OPENSSL_NO_SRP if (alg_k & SSL_kSRP) { int param_len; n2s(p,i); param_len=i+2; if (param_len > n) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_SRP_A_LENGTH); goto f_err; } if (!(s->srp_ctx.A=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS); goto f_err; } if (s->session->srp_username != NULL) OPENSSL_free(s->session->srp_username); s->session->srp_username = BUF_strdup(s->srp_ctx.login); if (s->session->srp_username == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } if ((s->session->master_key_length = SRP_generate_server_master_secret(s,s->session->master_key))<0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } p+=i; } else #endif /* OPENSSL_NO_SRP */ if (alg_k & SSL_kGOST) { int ret = 0; EVP_PKEY_CTX *pkey_ctx; EVP_PKEY *client_pub_pkey = NULL, *pk = NULL; unsigned char premaster_secret[32], *start; size_t outlen=32, inlen; unsigned long alg_a; int Ttag, Tclass; long Tlen; /* Get our certificate private key*/ alg_a = s->s3->tmp.new_cipher->algorithm_auth; if (alg_a & SSL_aGOST94) pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey; else if (alg_a & SSL_aGOST01) pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey; pkey_ctx = EVP_PKEY_CTX_new(pk,NULL); EVP_PKEY_decrypt_init(pkey_ctx); /* If client certificate is present and is of the same type, maybe * use it for key exchange. Don't mind errors from * EVP_PKEY_derive_set_peer, because it is completely valid to use * a client certificate for authorization only. */ client_pub_pkey = X509_get_pubkey(s->session->peer); if (client_pub_pkey) { if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0) ERR_clear_error(); } /* Decrypt session key */ if (ASN1_get_object((const unsigned char **)&p, &Tlen, &Ttag, &Tclass, n) != V_ASN1_CONSTRUCTED || Ttag != V_ASN1_SEQUENCE || Tclass != V_ASN1_UNIVERSAL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED); goto gerr; } start = p; inlen = Tlen; if (EVP_PKEY_decrypt(pkey_ctx,premaster_secret,&outlen,start,inlen) <=0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED); goto gerr; } /* Generate master secret */ s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key,premaster_secret,32); /* Check if pubkey from client certificate was used */ if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) ret = 2; else ret = 1; gerr: EVP_PKEY_free(client_pub_pkey); EVP_PKEY_CTX_free(pkey_ctx); if (ret) return ret; else goto err; } else { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE); goto f_err; } return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) || defined(OPENSSL_NO_SRP) err: #endif #ifndef OPENSSL_NO_ECDH EVP_PKEY_free(clnt_pub_pkey); EC_POINT_free(clnt_ecpoint); if (srvr_ecdh != NULL) EC_KEY_free(srvr_ecdh); BN_CTX_free(bn_ctx); #endif return(-1); } int ssl3_get_cert_verify(SSL *s) { EVP_PKEY *pkey=NULL; unsigned char *p; int al,ok,ret=0; long n; int type=0,i,j; X509 *peer; const EVP_MD *md = NULL; EVP_MD_CTX mctx; EVP_MD_CTX_init(&mctx); n=s->method->ssl_get_message(s, SSL3_ST_SR_CERT_VRFY_A, SSL3_ST_SR_CERT_VRFY_B, -1, SSL3_RT_MAX_PLAIN_LENGTH, &ok); if (!ok) return((int)n); if (s->session->peer != NULL) { peer=s->session->peer; pkey=X509_get_pubkey(peer); type=X509_certificate_type(peer,pkey); } else { peer=NULL; pkey=NULL; } if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY) { s->s3->tmp.reuse_message=1; if ((peer != NULL) && (type & EVP_PKT_SIGN)) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE); goto f_err; } ret=1; goto end; } if (peer == NULL) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED); al=SSL_AD_UNEXPECTED_MESSAGE; goto f_err; } if (!(type & EVP_PKT_SIGN)) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE); al=SSL_AD_ILLEGAL_PARAMETER; goto f_err; } if (s->s3->change_cipher_spec) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY); al=SSL_AD_UNEXPECTED_MESSAGE; goto f_err; } /* we now have a signature that we need to verify */ p=(unsigned char *)s->init_msg; /* Check for broken implementations of GOST ciphersuites */ /* If key is GOST and n is exactly 64, it is bare * signature without length field */ if (n==64 && (pkey->type==NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001) ) { i=64; } else { if (SSL_USE_SIGALGS(s)) { int rv = tls12_check_peer_sigalg(&md, s, p, pkey); if (rv == -1) { al = SSL_AD_INTERNAL_ERROR; goto f_err; } else if (rv == 0) { al = SSL_AD_DECODE_ERROR; goto f_err; } #ifdef SSL_DEBUG fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md)); #endif p += 2; n -= 2; } n2s(p,i); n-=2; if (i > n) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH); al=SSL_AD_DECODE_ERROR; goto f_err; } } j=EVP_PKEY_size(pkey); if ((i > j) || (n > j) || (n <= 0)) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE); al=SSL_AD_DECODE_ERROR; goto f_err; } if (SSL_USE_SIGALGS(s)) { long hdatalen = 0; void *hdata; hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata); if (hdatalen <= 0) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR); al=SSL_AD_INTERNAL_ERROR; goto f_err; } #ifdef SSL_DEBUG fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n", EVP_MD_name(md)); #endif if (!EVP_VerifyInit_ex(&mctx, md, NULL) || !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB); al=SSL_AD_INTERNAL_ERROR; goto f_err; } if (EVP_VerifyFinal(&mctx, p , i, pkey) <= 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_SIGNATURE); goto f_err; } } else #ifndef OPENSSL_NO_RSA if (pkey->type == EVP_PKEY_RSA) { i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md, MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i, pkey->pkey.rsa); if (i < 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT); goto f_err; } if (i == 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE); goto f_err; } } else #endif #ifndef OPENSSL_NO_DSA if (pkey->type == EVP_PKEY_DSA) { j=DSA_verify(pkey->save_type, &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]), SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa); if (j <= 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE); goto f_err; } } else #endif #ifndef OPENSSL_NO_ECDSA if (pkey->type == EVP_PKEY_EC) { j=ECDSA_verify(pkey->save_type, &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]), SHA_DIGEST_LENGTH,p,i,pkey->pkey.ec); if (j <= 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE); goto f_err; } } else #endif if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001) { unsigned char signature[64]; int idx; EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey,NULL); EVP_PKEY_verify_init(pctx); if (i!=64) { fprintf(stderr,"GOST signature length is %d",i); } for (idx=0;idx<64;idx++) { signature[63-idx]=p[idx]; } j=EVP_PKEY_verify(pctx,signature,64,s->s3->tmp.cert_verify_md,32); EVP_PKEY_CTX_free(pctx); if (j<=0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE); goto f_err; } } else { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR); al=SSL_AD_UNSUPPORTED_CERTIFICATE; goto f_err; } ret=1; if (0) { f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); } end: if (s->s3->handshake_buffer) { BIO_free(s->s3->handshake_buffer); s->s3->handshake_buffer = NULL; s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE; } EVP_MD_CTX_cleanup(&mctx); EVP_PKEY_free(pkey); return(ret); } int ssl3_get_client_certificate(SSL *s) { int i,ok,al,ret= -1; X509 *x=NULL; unsigned long l,nc,llen,n; const unsigned char *p,*q; unsigned char *d; STACK_OF(X509) *sk=NULL; n=s->method->ssl_get_message(s, SSL3_ST_SR_CERT_A, SSL3_ST_SR_CERT_B, -1, s->max_cert_list, &ok); if (!ok) return((int)n); if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) { if ( (s->verify_mode & SSL_VERIFY_PEER) && (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) { SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE); al=SSL_AD_HANDSHAKE_FAILURE; goto f_err; } /* If tls asked for a client cert, the client must return a 0 list */ if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request) { SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST); al=SSL_AD_UNEXPECTED_MESSAGE; goto f_err; } s->s3->tmp.reuse_message=1; return(1); } if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_WRONG_MESSAGE_TYPE); goto f_err; } p=d=(unsigned char *)s->init_msg; if ((sk=sk_X509_new_null()) == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE); goto err; } n2l3(p,llen); if (llen+3 != n) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_LENGTH_MISMATCH); goto f_err; } for (nc=0; nc<llen; ) { n2l3(p,l); if ((l+nc+3) > llen) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH); goto f_err; } q=p; x=d2i_X509(NULL,&p,l); if (x == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_ASN1_LIB); goto err; } if (p != (q+l)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH); goto f_err; } if (!sk_X509_push(sk,x)) { SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE); goto err; } x=NULL; nc+=l+3; } if (sk_X509_num(sk) <= 0) { /* TLS does not mind 0 certs returned */ if (s->version == SSL3_VERSION) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATES_RETURNED); goto f_err; } /* Fail for TLS only if we required a certificate */ else if ((s->verify_mode & SSL_VERIFY_PEER) && (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) { SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE); al=SSL_AD_HANDSHAKE_FAILURE; goto f_err; } /* No client certificate so digest cached records */ if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s)) { al=SSL_AD_INTERNAL_ERROR; goto f_err; } } else { EVP_PKEY *pkey; i=ssl_verify_cert_chain(s,sk); if (i <= 0) { al=ssl_verify_alarm_type(s->verify_result); SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED); goto f_err; } if (i > 1) { SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, i); al = SSL_AD_HANDSHAKE_FAILURE; goto f_err; } pkey = X509_get_pubkey(sk_X509_value(sk, 0)); if (pkey == NULL) { al=SSL3_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_UNKNOWN_CERTIFICATE_TYPE); goto f_err; } EVP_PKEY_free(pkey); } if (s->session->peer != NULL) /* This should not be needed */ X509_free(s->session->peer); s->session->peer=sk_X509_shift(sk); s->session->verify_result = s->verify_result; /* With the current implementation, sess_cert will always be NULL * when we arrive here. */ if (s->session->sess_cert == NULL) { s->session->sess_cert = ssl_sess_cert_new(); if (s->session->sess_cert == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE); goto err; } } if (s->session->sess_cert->cert_chain != NULL) sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free); s->session->sess_cert->cert_chain=sk; /* Inconsistency alert: cert_chain does *not* include the * peer's own certificate, while we do include it in s3_clnt.c */ sk=NULL; ret=1; if (0) { f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); } err: if (x != NULL) X509_free(x); if (sk != NULL) sk_X509_pop_free(sk,X509_free); return(ret); } int ssl3_send_server_certificate(SSL *s) { CERT_PKEY *cpk; if (s->state == SSL3_ST_SW_CERT_A) { cpk=ssl_get_server_send_pkey(s); if (cpk == NULL) { /* VRS: allow null cert if auth == KRB5 */ if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5)) { SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR); return(0); } } if (!ssl3_output_cert_chain(s,cpk)) { SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR); return(0); } s->state=SSL3_ST_SW_CERT_B; } /* SSL3_ST_SW_CERT_B */ return ssl_do_write(s); } #ifndef OPENSSL_NO_TLSEXT /* send a new session ticket (not necessarily for a new session) */ int ssl3_send_newsession_ticket(SSL *s) { if (s->state == SSL3_ST_SW_SESSION_TICKET_A) { unsigned char *p, *senc, *macstart; const unsigned char *const_p; int len, slen_full, slen; SSL_SESSION *sess; unsigned int hlen; EVP_CIPHER_CTX ctx; HMAC_CTX hctx; SSL_CTX *tctx = s->initial_ctx; unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char key_name[16]; /* get session encoding length */ slen_full = i2d_SSL_SESSION(s->session, NULL); /* Some length values are 16 bits, so forget it if session is * too long */ if (slen_full > 0xFF00) return -1; senc = OPENSSL_malloc(slen_full); if (!senc) return -1; p = senc; i2d_SSL_SESSION(s->session, &p); /* create a fresh copy (not shared with other threads) to clean up */ const_p = senc; sess = d2i_SSL_SESSION(NULL, &const_p, slen_full); if (sess == NULL) { OPENSSL_free(senc); return -1; } sess->session_id_length = 0; /* ID is irrelevant for the ticket */ slen = i2d_SSL_SESSION(sess, NULL); if (slen > slen_full) /* shouldn't ever happen */ { OPENSSL_free(senc); return -1; } p = senc; i2d_SSL_SESSION(sess, &p); SSL_SESSION_free(sess); /*- * Grow buffer if need be: the length calculation is as * follows handshake_header_length + * 4 (ticket lifetime hint) + 2 (ticket length) + * 16 (key name) + max_iv_len (iv length) + * session_length + max_enc_block_size (max encrypted session * length) + max_md_size (HMAC). */ if (!BUF_MEM_grow(s->init_buf, SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen)) return -1; p = ssl_handshake_start(s); EVP_CIPHER_CTX_init(&ctx); HMAC_CTX_init(&hctx); /* Initialize HMAC and cipher contexts. If callback present * it does all the work otherwise use generated values * from parent ctx. */ if (tctx->tlsext_ticket_key_cb) { if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx, &hctx, 1) < 0) { OPENSSL_free(senc); return -1; } } else { RAND_pseudo_bytes(iv, 16); EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, tctx->tlsext_tick_aes_key, iv); HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16, tlsext_tick_md(), NULL); memcpy(key_name, tctx->tlsext_tick_key_name, 16); } /* Ticket lifetime hint (advisory only): * We leave this unspecified for resumed session (for simplicity), * and guess that tickets for new sessions will live as long * as their sessions. */ l2n(s->hit ? 0 : s->session->timeout, p); /* Skip ticket length for now */ p += 2; /* Output key name */ macstart = p; memcpy(p, key_name, 16); p += 16; /* output IV */ memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx)); p += EVP_CIPHER_CTX_iv_length(&ctx); /* Encrypt session data */ EVP_EncryptUpdate(&ctx, p, &len, senc, slen); p += len; EVP_EncryptFinal(&ctx, p, &len); p += len; EVP_CIPHER_CTX_cleanup(&ctx); HMAC_Update(&hctx, macstart, p - macstart); HMAC_Final(&hctx, p, &hlen); HMAC_CTX_cleanup(&hctx); p += hlen; /* Now write out lengths: p points to end of data written */ /* Total length */ len = p - ssl_handshake_start(s); ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len); /* Skip ticket lifetime hint */ p = ssl_handshake_start(s) + 4; s2n(len - 6, p); s->state=SSL3_ST_SW_SESSION_TICKET_B; OPENSSL_free(senc); } /* SSL3_ST_SW_SESSION_TICKET_B */ return ssl_do_write(s); } int ssl3_send_cert_status(SSL *s) { if (s->state == SSL3_ST_SW_CERT_STATUS_A) { unsigned char *p; /*- * Grow buffer if need be: the length calculation is as * follows 1 (message type) + 3 (message length) + * 1 (ocsp response type) + 3 (ocsp response length) * + (ocsp response) */ if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen)) return -1; p=(unsigned char *)s->init_buf->data; /* do the header */ *(p++)=SSL3_MT_CERTIFICATE_STATUS; /* message length */ l2n3(s->tlsext_ocsp_resplen + 4, p); /* status type */ *(p++)= s->tlsext_status_type; /* length of OCSP response */ l2n3(s->tlsext_ocsp_resplen, p); /* actual response */ memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen); /* number of bytes to write */ s->init_num = 8 + s->tlsext_ocsp_resplen; s->state=SSL3_ST_SW_CERT_STATUS_B; s->init_off = 0; } /* SSL3_ST_SW_CERT_STATUS_B */ return(ssl3_do_write(s,SSL3_RT_HANDSHAKE)); } # ifndef OPENSSL_NO_NEXTPROTONEG /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It * sets the next_proto member in s if found */ int ssl3_get_next_proto(SSL *s) { int ok; int proto_len, padding_len; long n; const unsigned char *p; /* Clients cannot send a NextProtocol message if we didn't see the * extension in their ClientHello */ if (!s->s3->next_proto_neg_seen) { SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION); return -1; } n=s->method->ssl_get_message(s, SSL3_ST_SR_NEXT_PROTO_A, SSL3_ST_SR_NEXT_PROTO_B, SSL3_MT_NEXT_PROTO, 514, /* See the payload format below */ &ok); if (!ok) return((int)n); /* s->state doesn't reflect whether ChangeCipherSpec has been received * in this handshake, but s->s3->change_cipher_spec does (will be reset * by ssl3_get_finished). */ if (!s->s3->change_cipher_spec) { SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS); return -1; } if (n < 2) return 0; /* The body must be > 1 bytes long */ p=(unsigned char *)s->init_msg; /*- * The payload looks like: * uint8 proto_len; * uint8 proto[proto_len]; * uint8 padding_len; * uint8 padding[padding_len]; */ proto_len = p[0]; if (proto_len + 2 > s->init_num) return 0; padding_len = p[proto_len + 1]; if (proto_len + padding_len + 2 != s->init_num) return 0; s->next_proto_negotiated = OPENSSL_malloc(proto_len); if (!s->next_proto_negotiated) { SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,ERR_R_MALLOC_FAILURE); return 0; } memcpy(s->next_proto_negotiated, p + 1, proto_len); s->next_proto_negotiated_len = proto_len; return 1; } # endif #endif
./CrossVul/dataset_final_sorted/CWE-310/c/bad_1446_0
crossvul-cpp_data_good_3783_3
/* * Copyright (C) 2007 Oracle. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License v2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 021110-1307, USA. */ #include <linux/kernel.h> #include <linux/bio.h> #include <linux/buffer_head.h> #include <linux/file.h> #include <linux/fs.h> #include <linux/fsnotify.h> #include <linux/pagemap.h> #include <linux/highmem.h> #include <linux/time.h> #include <linux/init.h> #include <linux/string.h> #include <linux/backing-dev.h> #include <linux/mount.h> #include <linux/mpage.h> #include <linux/namei.h> #include <linux/swap.h> #include <linux/writeback.h> #include <linux/statfs.h> #include <linux/compat.h> #include <linux/bit_spinlock.h> #include <linux/security.h> #include <linux/xattr.h> #include <linux/vmalloc.h> #include <linux/slab.h> #include <linux/blkdev.h> #include <linux/uuid.h> #include "compat.h" #include "ctree.h" #include "disk-io.h" #include "transaction.h" #include "btrfs_inode.h" #include "ioctl.h" #include "print-tree.h" #include "volumes.h" #include "locking.h" #include "inode-map.h" #include "backref.h" #include "rcu-string.h" #include "send.h" #include "dev-replace.h" /* Mask out flags that are inappropriate for the given type of inode. */ static inline __u32 btrfs_mask_flags(umode_t mode, __u32 flags) { if (S_ISDIR(mode)) return flags; else if (S_ISREG(mode)) return flags & ~FS_DIRSYNC_FL; else return flags & (FS_NODUMP_FL | FS_NOATIME_FL); } /* * Export inode flags to the format expected by the FS_IOC_GETFLAGS ioctl. */ static unsigned int btrfs_flags_to_ioctl(unsigned int flags) { unsigned int iflags = 0; if (flags & BTRFS_INODE_SYNC) iflags |= FS_SYNC_FL; if (flags & BTRFS_INODE_IMMUTABLE) iflags |= FS_IMMUTABLE_FL; if (flags & BTRFS_INODE_APPEND) iflags |= FS_APPEND_FL; if (flags & BTRFS_INODE_NODUMP) iflags |= FS_NODUMP_FL; if (flags & BTRFS_INODE_NOATIME) iflags |= FS_NOATIME_FL; if (flags & BTRFS_INODE_DIRSYNC) iflags |= FS_DIRSYNC_FL; if (flags & BTRFS_INODE_NODATACOW) iflags |= FS_NOCOW_FL; if ((flags & BTRFS_INODE_COMPRESS) && !(flags & BTRFS_INODE_NOCOMPRESS)) iflags |= FS_COMPR_FL; else if (flags & BTRFS_INODE_NOCOMPRESS) iflags |= FS_NOCOMP_FL; return iflags; } /* * Update inode->i_flags based on the btrfs internal flags. */ void btrfs_update_iflags(struct inode *inode) { struct btrfs_inode *ip = BTRFS_I(inode); inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC); if (ip->flags & BTRFS_INODE_SYNC) inode->i_flags |= S_SYNC; if (ip->flags & BTRFS_INODE_IMMUTABLE) inode->i_flags |= S_IMMUTABLE; if (ip->flags & BTRFS_INODE_APPEND) inode->i_flags |= S_APPEND; if (ip->flags & BTRFS_INODE_NOATIME) inode->i_flags |= S_NOATIME; if (ip->flags & BTRFS_INODE_DIRSYNC) inode->i_flags |= S_DIRSYNC; } /* * Inherit flags from the parent inode. * * Currently only the compression flags and the cow flags are inherited. */ void btrfs_inherit_iflags(struct inode *inode, struct inode *dir) { unsigned int flags; if (!dir) return; flags = BTRFS_I(dir)->flags; if (flags & BTRFS_INODE_NOCOMPRESS) { BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS; BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS; } else if (flags & BTRFS_INODE_COMPRESS) { BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS; BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS; } if (flags & BTRFS_INODE_NODATACOW) BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW; btrfs_update_iflags(inode); } static int btrfs_ioctl_getflags(struct file *file, void __user *arg) { struct btrfs_inode *ip = BTRFS_I(file->f_path.dentry->d_inode); unsigned int flags = btrfs_flags_to_ioctl(ip->flags); if (copy_to_user(arg, &flags, sizeof(flags))) return -EFAULT; return 0; } static int check_flags(unsigned int flags) { if (flags & ~(FS_IMMUTABLE_FL | FS_APPEND_FL | \ FS_NOATIME_FL | FS_NODUMP_FL | \ FS_SYNC_FL | FS_DIRSYNC_FL | \ FS_NOCOMP_FL | FS_COMPR_FL | FS_NOCOW_FL)) return -EOPNOTSUPP; if ((flags & FS_NOCOMP_FL) && (flags & FS_COMPR_FL)) return -EINVAL; return 0; } static int btrfs_ioctl_setflags(struct file *file, void __user *arg) { struct inode *inode = file->f_path.dentry->d_inode; struct btrfs_inode *ip = BTRFS_I(inode); struct btrfs_root *root = ip->root; struct btrfs_trans_handle *trans; unsigned int flags, oldflags; int ret; u64 ip_oldflags; unsigned int i_oldflags; umode_t mode; if (btrfs_root_readonly(root)) return -EROFS; if (copy_from_user(&flags, arg, sizeof(flags))) return -EFAULT; ret = check_flags(flags); if (ret) return ret; if (!inode_owner_or_capable(inode)) return -EACCES; ret = mnt_want_write_file(file); if (ret) return ret; mutex_lock(&inode->i_mutex); ip_oldflags = ip->flags; i_oldflags = inode->i_flags; mode = inode->i_mode; flags = btrfs_mask_flags(inode->i_mode, flags); oldflags = btrfs_flags_to_ioctl(ip->flags); if ((flags ^ oldflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) { if (!capable(CAP_LINUX_IMMUTABLE)) { ret = -EPERM; goto out_unlock; } } if (flags & FS_SYNC_FL) ip->flags |= BTRFS_INODE_SYNC; else ip->flags &= ~BTRFS_INODE_SYNC; if (flags & FS_IMMUTABLE_FL) ip->flags |= BTRFS_INODE_IMMUTABLE; else ip->flags &= ~BTRFS_INODE_IMMUTABLE; if (flags & FS_APPEND_FL) ip->flags |= BTRFS_INODE_APPEND; else ip->flags &= ~BTRFS_INODE_APPEND; if (flags & FS_NODUMP_FL) ip->flags |= BTRFS_INODE_NODUMP; else ip->flags &= ~BTRFS_INODE_NODUMP; if (flags & FS_NOATIME_FL) ip->flags |= BTRFS_INODE_NOATIME; else ip->flags &= ~BTRFS_INODE_NOATIME; if (flags & FS_DIRSYNC_FL) ip->flags |= BTRFS_INODE_DIRSYNC; else ip->flags &= ~BTRFS_INODE_DIRSYNC; if (flags & FS_NOCOW_FL) { if (S_ISREG(mode)) { /* * It's safe to turn csums off here, no extents exist. * Otherwise we want the flag to reflect the real COW * status of the file and will not set it. */ if (inode->i_size == 0) ip->flags |= BTRFS_INODE_NODATACOW | BTRFS_INODE_NODATASUM; } else { ip->flags |= BTRFS_INODE_NODATACOW; } } else { /* * Revert back under same assuptions as above */ if (S_ISREG(mode)) { if (inode->i_size == 0) ip->flags &= ~(BTRFS_INODE_NODATACOW | BTRFS_INODE_NODATASUM); } else { ip->flags &= ~BTRFS_INODE_NODATACOW; } } /* * The COMPRESS flag can only be changed by users, while the NOCOMPRESS * flag may be changed automatically if compression code won't make * things smaller. */ if (flags & FS_NOCOMP_FL) { ip->flags &= ~BTRFS_INODE_COMPRESS; ip->flags |= BTRFS_INODE_NOCOMPRESS; } else if (flags & FS_COMPR_FL) { ip->flags |= BTRFS_INODE_COMPRESS; ip->flags &= ~BTRFS_INODE_NOCOMPRESS; } else { ip->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS); } trans = btrfs_start_transaction(root, 1); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out_drop; } btrfs_update_iflags(inode); inode_inc_iversion(inode); inode->i_ctime = CURRENT_TIME; ret = btrfs_update_inode(trans, root, inode); btrfs_end_transaction(trans, root); out_drop: if (ret) { ip->flags = ip_oldflags; inode->i_flags = i_oldflags; } out_unlock: mutex_unlock(&inode->i_mutex); mnt_drop_write_file(file); return ret; } static int btrfs_ioctl_getversion(struct file *file, int __user *arg) { struct inode *inode = file->f_path.dentry->d_inode; return put_user(inode->i_generation, arg); } static noinline int btrfs_ioctl_fitrim(struct file *file, void __user *arg) { struct btrfs_fs_info *fs_info = btrfs_sb(fdentry(file)->d_sb); struct btrfs_device *device; struct request_queue *q; struct fstrim_range range; u64 minlen = ULLONG_MAX; u64 num_devices = 0; u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy); int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; rcu_read_lock(); list_for_each_entry_rcu(device, &fs_info->fs_devices->devices, dev_list) { if (!device->bdev) continue; q = bdev_get_queue(device->bdev); if (blk_queue_discard(q)) { num_devices++; minlen = min((u64)q->limits.discard_granularity, minlen); } } rcu_read_unlock(); if (!num_devices) return -EOPNOTSUPP; if (copy_from_user(&range, arg, sizeof(range))) return -EFAULT; if (range.start > total_bytes || range.len < fs_info->sb->s_blocksize) return -EINVAL; range.len = min(range.len, total_bytes - range.start); range.minlen = max(range.minlen, minlen); ret = btrfs_trim_fs(fs_info->tree_root, &range); if (ret < 0) return ret; if (copy_to_user(arg, &range, sizeof(range))) return -EFAULT; return 0; } static noinline int create_subvol(struct btrfs_root *root, struct dentry *dentry, char *name, int namelen, u64 *async_transid, struct btrfs_qgroup_inherit **inherit) { struct btrfs_trans_handle *trans; struct btrfs_key key; struct btrfs_root_item root_item; struct btrfs_inode_item *inode_item; struct extent_buffer *leaf; struct btrfs_root *new_root; struct dentry *parent = dentry->d_parent; struct inode *dir; struct timespec cur_time = CURRENT_TIME; int ret; int err; u64 objectid; u64 new_dirid = BTRFS_FIRST_FREE_OBJECTID; u64 index = 0; uuid_le new_uuid; ret = btrfs_find_free_objectid(root->fs_info->tree_root, &objectid); if (ret) return ret; dir = parent->d_inode; /* * 1 - inode item * 2 - refs * 1 - root item * 2 - dir items */ trans = btrfs_start_transaction(root, 6); if (IS_ERR(trans)) return PTR_ERR(trans); ret = btrfs_qgroup_inherit(trans, root->fs_info, 0, objectid, inherit ? *inherit : NULL); if (ret) goto fail; leaf = btrfs_alloc_free_block(trans, root, root->leafsize, 0, objectid, NULL, 0, 0, 0); if (IS_ERR(leaf)) { ret = PTR_ERR(leaf); goto fail; } memset_extent_buffer(leaf, 0, 0, sizeof(struct btrfs_header)); btrfs_set_header_bytenr(leaf, leaf->start); btrfs_set_header_generation(leaf, trans->transid); btrfs_set_header_backref_rev(leaf, BTRFS_MIXED_BACKREF_REV); btrfs_set_header_owner(leaf, objectid); write_extent_buffer(leaf, root->fs_info->fsid, (unsigned long)btrfs_header_fsid(leaf), BTRFS_FSID_SIZE); write_extent_buffer(leaf, root->fs_info->chunk_tree_uuid, (unsigned long)btrfs_header_chunk_tree_uuid(leaf), BTRFS_UUID_SIZE); btrfs_mark_buffer_dirty(leaf); memset(&root_item, 0, sizeof(root_item)); inode_item = &root_item.inode; inode_item->generation = cpu_to_le64(1); inode_item->size = cpu_to_le64(3); inode_item->nlink = cpu_to_le32(1); inode_item->nbytes = cpu_to_le64(root->leafsize); inode_item->mode = cpu_to_le32(S_IFDIR | 0755); root_item.flags = 0; root_item.byte_limit = 0; inode_item->flags = cpu_to_le64(BTRFS_INODE_ROOT_ITEM_INIT); btrfs_set_root_bytenr(&root_item, leaf->start); btrfs_set_root_generation(&root_item, trans->transid); btrfs_set_root_level(&root_item, 0); btrfs_set_root_refs(&root_item, 1); btrfs_set_root_used(&root_item, leaf->len); btrfs_set_root_last_snapshot(&root_item, 0); btrfs_set_root_generation_v2(&root_item, btrfs_root_generation(&root_item)); uuid_le_gen(&new_uuid); memcpy(root_item.uuid, new_uuid.b, BTRFS_UUID_SIZE); root_item.otime.sec = cpu_to_le64(cur_time.tv_sec); root_item.otime.nsec = cpu_to_le32(cur_time.tv_nsec); root_item.ctime = root_item.otime; btrfs_set_root_ctransid(&root_item, trans->transid); btrfs_set_root_otransid(&root_item, trans->transid); btrfs_tree_unlock(leaf); free_extent_buffer(leaf); leaf = NULL; btrfs_set_root_dirid(&root_item, new_dirid); key.objectid = objectid; key.offset = 0; btrfs_set_key_type(&key, BTRFS_ROOT_ITEM_KEY); ret = btrfs_insert_root(trans, root->fs_info->tree_root, &key, &root_item); if (ret) goto fail; key.offset = (u64)-1; new_root = btrfs_read_fs_root_no_name(root->fs_info, &key); if (IS_ERR(new_root)) { btrfs_abort_transaction(trans, root, PTR_ERR(new_root)); ret = PTR_ERR(new_root); goto fail; } btrfs_record_root_in_trans(trans, new_root); ret = btrfs_create_subvol_root(trans, new_root, new_dirid); if (ret) { /* We potentially lose an unused inode item here */ btrfs_abort_transaction(trans, root, ret); goto fail; } /* * insert the directory item */ ret = btrfs_set_inode_index(dir, &index); if (ret) { btrfs_abort_transaction(trans, root, ret); goto fail; } ret = btrfs_insert_dir_item(trans, root, name, namelen, dir, &key, BTRFS_FT_DIR, index); if (ret) { btrfs_abort_transaction(trans, root, ret); goto fail; } btrfs_i_size_write(dir, dir->i_size + namelen * 2); ret = btrfs_update_inode(trans, root, dir); BUG_ON(ret); ret = btrfs_add_root_ref(trans, root->fs_info->tree_root, objectid, root->root_key.objectid, btrfs_ino(dir), index, name, namelen); BUG_ON(ret); d_instantiate(dentry, btrfs_lookup_dentry(dir, dentry)); fail: if (async_transid) { *async_transid = trans->transid; err = btrfs_commit_transaction_async(trans, root, 1); } else { err = btrfs_commit_transaction(trans, root); } if (err && !ret) ret = err; return ret; } static int create_snapshot(struct btrfs_root *root, struct dentry *dentry, char *name, int namelen, u64 *async_transid, bool readonly, struct btrfs_qgroup_inherit **inherit) { struct inode *inode; struct btrfs_pending_snapshot *pending_snapshot; struct btrfs_trans_handle *trans; int ret; if (!root->ref_cows) return -EINVAL; pending_snapshot = kzalloc(sizeof(*pending_snapshot), GFP_NOFS); if (!pending_snapshot) return -ENOMEM; btrfs_init_block_rsv(&pending_snapshot->block_rsv, BTRFS_BLOCK_RSV_TEMP); pending_snapshot->dentry = dentry; pending_snapshot->root = root; pending_snapshot->readonly = readonly; if (inherit) { pending_snapshot->inherit = *inherit; *inherit = NULL; /* take responsibility to free it */ } trans = btrfs_start_transaction(root->fs_info->extent_root, 6); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto fail; } ret = btrfs_snap_reserve_metadata(trans, pending_snapshot); BUG_ON(ret); spin_lock(&root->fs_info->trans_lock); list_add(&pending_snapshot->list, &trans->transaction->pending_snapshots); spin_unlock(&root->fs_info->trans_lock); if (async_transid) { *async_transid = trans->transid; ret = btrfs_commit_transaction_async(trans, root->fs_info->extent_root, 1); } else { ret = btrfs_commit_transaction(trans, root->fs_info->extent_root); } if (ret) { /* cleanup_transaction has freed this for us */ if (trans->aborted) pending_snapshot = NULL; goto fail; } ret = pending_snapshot->error; if (ret) goto fail; ret = btrfs_orphan_cleanup(pending_snapshot->snap); if (ret) goto fail; inode = btrfs_lookup_dentry(dentry->d_parent->d_inode, dentry); if (IS_ERR(inode)) { ret = PTR_ERR(inode); goto fail; } BUG_ON(!inode); d_instantiate(dentry, inode); ret = 0; fail: kfree(pending_snapshot); return ret; } /* copy of check_sticky in fs/namei.c() * It's inline, so penalty for filesystems that don't use sticky bit is * minimal. */ static inline int btrfs_check_sticky(struct inode *dir, struct inode *inode) { kuid_t fsuid = current_fsuid(); if (!(dir->i_mode & S_ISVTX)) return 0; if (uid_eq(inode->i_uid, fsuid)) return 0; if (uid_eq(dir->i_uid, fsuid)) return 0; return !capable(CAP_FOWNER); } /* copy of may_delete in fs/namei.c() * Check whether we can remove a link victim from directory dir, check * whether the type of victim is right. * 1. We can't do it if dir is read-only (done in permission()) * 2. We should have write and exec permissions on dir * 3. We can't remove anything from append-only dir * 4. We can't do anything with immutable dir (done in permission()) * 5. If the sticky bit on dir is set we should either * a. be owner of dir, or * b. be owner of victim, or * c. have CAP_FOWNER capability * 6. If the victim is append-only or immutable we can't do antyhing with * links pointing to it. * 7. If we were asked to remove a directory and victim isn't one - ENOTDIR. * 8. If we were asked to remove a non-directory and victim isn't one - EISDIR. * 9. We can't remove a root or mountpoint. * 10. We don't allow removal of NFS sillyrenamed files; it's handled by * nfs_async_unlink(). */ static int btrfs_may_delete(struct inode *dir,struct dentry *victim,int isdir) { int error; if (!victim->d_inode) return -ENOENT; BUG_ON(victim->d_parent->d_inode != dir); audit_inode_child(dir, victim, AUDIT_TYPE_CHILD_DELETE); error = inode_permission(dir, MAY_WRITE | MAY_EXEC); if (error) return error; if (IS_APPEND(dir)) return -EPERM; if (btrfs_check_sticky(dir, victim->d_inode)|| IS_APPEND(victim->d_inode)|| IS_IMMUTABLE(victim->d_inode) || IS_SWAPFILE(victim->d_inode)) return -EPERM; if (isdir) { if (!S_ISDIR(victim->d_inode->i_mode)) return -ENOTDIR; if (IS_ROOT(victim)) return -EBUSY; } else if (S_ISDIR(victim->d_inode->i_mode)) return -EISDIR; if (IS_DEADDIR(dir)) return -ENOENT; if (victim->d_flags & DCACHE_NFSFS_RENAMED) return -EBUSY; return 0; } /* copy of may_create in fs/namei.c() */ static inline int btrfs_may_create(struct inode *dir, struct dentry *child) { if (child->d_inode) return -EEXIST; if (IS_DEADDIR(dir)) return -ENOENT; return inode_permission(dir, MAY_WRITE | MAY_EXEC); } /* * Create a new subvolume below @parent. This is largely modeled after * sys_mkdirat and vfs_mkdir, but we only do a single component lookup * inside this filesystem so it's quite a bit simpler. */ static noinline int btrfs_mksubvol(struct path *parent, char *name, int namelen, struct btrfs_root *snap_src, u64 *async_transid, bool readonly, struct btrfs_qgroup_inherit **inherit) { struct inode *dir = parent->dentry->d_inode; struct dentry *dentry; int error; mutex_lock_nested(&dir->i_mutex, I_MUTEX_PARENT); dentry = lookup_one_len(name, parent->dentry, namelen); error = PTR_ERR(dentry); if (IS_ERR(dentry)) goto out_unlock; error = -EEXIST; if (dentry->d_inode) goto out_dput; error = btrfs_may_create(dir, dentry); if (error) goto out_dput; /* * even if this name doesn't exist, we may get hash collisions. * check for them now when we can safely fail */ error = btrfs_check_dir_item_collision(BTRFS_I(dir)->root, dir->i_ino, name, namelen); if (error) goto out_dput; down_read(&BTRFS_I(dir)->root->fs_info->subvol_sem); if (btrfs_root_refs(&BTRFS_I(dir)->root->root_item) == 0) goto out_up_read; if (snap_src) { error = create_snapshot(snap_src, dentry, name, namelen, async_transid, readonly, inherit); } else { error = create_subvol(BTRFS_I(dir)->root, dentry, name, namelen, async_transid, inherit); } if (!error) fsnotify_mkdir(dir, dentry); out_up_read: up_read(&BTRFS_I(dir)->root->fs_info->subvol_sem); out_dput: dput(dentry); out_unlock: mutex_unlock(&dir->i_mutex); return error; } /* * When we're defragging a range, we don't want to kick it off again * if it is really just waiting for delalloc to send it down. * If we find a nice big extent or delalloc range for the bytes in the * file you want to defrag, we return 0 to let you know to skip this * part of the file */ static int check_defrag_in_cache(struct inode *inode, u64 offset, int thresh) { struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct extent_map *em = NULL; struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; u64 end; read_lock(&em_tree->lock); em = lookup_extent_mapping(em_tree, offset, PAGE_CACHE_SIZE); read_unlock(&em_tree->lock); if (em) { end = extent_map_end(em); free_extent_map(em); if (end - offset > thresh) return 0; } /* if we already have a nice delalloc here, just stop */ thresh /= 2; end = count_range_bits(io_tree, &offset, offset + thresh, thresh, EXTENT_DELALLOC, 1); if (end >= thresh) return 0; return 1; } /* * helper function to walk through a file and find extents * newer than a specific transid, and smaller than thresh. * * This is used by the defragging code to find new and small * extents */ static int find_new_extents(struct btrfs_root *root, struct inode *inode, u64 newer_than, u64 *off, int thresh) { struct btrfs_path *path; struct btrfs_key min_key; struct btrfs_key max_key; struct extent_buffer *leaf; struct btrfs_file_extent_item *extent; int type; int ret; u64 ino = btrfs_ino(inode); path = btrfs_alloc_path(); if (!path) return -ENOMEM; min_key.objectid = ino; min_key.type = BTRFS_EXTENT_DATA_KEY; min_key.offset = *off; max_key.objectid = ino; max_key.type = (u8)-1; max_key.offset = (u64)-1; path->keep_locks = 1; while(1) { ret = btrfs_search_forward(root, &min_key, &max_key, path, 0, newer_than); if (ret != 0) goto none; if (min_key.objectid != ino) goto none; if (min_key.type != BTRFS_EXTENT_DATA_KEY) goto none; leaf = path->nodes[0]; extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); type = btrfs_file_extent_type(leaf, extent); if (type == BTRFS_FILE_EXTENT_REG && btrfs_file_extent_num_bytes(leaf, extent) < thresh && check_defrag_in_cache(inode, min_key.offset, thresh)) { *off = min_key.offset; btrfs_free_path(path); return 0; } if (min_key.offset == (u64)-1) goto none; min_key.offset++; btrfs_release_path(path); } none: btrfs_free_path(path); return -ENOENT; } static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start) { struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct extent_map *em; u64 len = PAGE_CACHE_SIZE; /* * hopefully we have this extent in the tree already, try without * the full extent lock */ read_lock(&em_tree->lock); em = lookup_extent_mapping(em_tree, start, len); read_unlock(&em_tree->lock); if (!em) { /* get the big lock and read metadata off disk */ lock_extent(io_tree, start, start + len - 1); em = btrfs_get_extent(inode, NULL, 0, start, len, 0); unlock_extent(io_tree, start, start + len - 1); if (IS_ERR(em)) return NULL; } return em; } static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em) { struct extent_map *next; bool ret = true; /* this is the last extent */ if (em->start + em->len >= i_size_read(inode)) return false; next = defrag_lookup_extent(inode, em->start + em->len); if (!next || next->block_start >= EXTENT_MAP_LAST_BYTE) ret = false; free_extent_map(next); return ret; } static int should_defrag_range(struct inode *inode, u64 start, int thresh, u64 *last_len, u64 *skip, u64 *defrag_end, int compress) { struct extent_map *em; int ret = 1; bool next_mergeable = true; /* * make sure that once we start defragging an extent, we keep on * defragging it */ if (start < *defrag_end) return 1; *skip = 0; em = defrag_lookup_extent(inode, start); if (!em) return 0; /* this will cover holes, and inline extents */ if (em->block_start >= EXTENT_MAP_LAST_BYTE) { ret = 0; goto out; } next_mergeable = defrag_check_next_extent(inode, em); /* * we hit a real extent, if it is big or the next extent is not a * real extent, don't bother defragging it */ if (!compress && (*last_len == 0 || *last_len >= thresh) && (em->len >= thresh || !next_mergeable)) ret = 0; out: /* * last_len ends up being a counter of how many bytes we've defragged. * every time we choose not to defrag an extent, we reset *last_len * so that the next tiny extent will force a defrag. * * The end result of this is that tiny extents before a single big * extent will force at least part of that big extent to be defragged. */ if (ret) { *defrag_end = extent_map_end(em); } else { *last_len = 0; *skip = extent_map_end(em); *defrag_end = 0; } free_extent_map(em); return ret; } /* * it doesn't do much good to defrag one or two pages * at a time. This pulls in a nice chunk of pages * to COW and defrag. * * It also makes sure the delalloc code has enough * dirty data to avoid making new small extents as part * of the defrag * * It's a good idea to start RA on this range * before calling this. */ static int cluster_pages_for_defrag(struct inode *inode, struct page **pages, unsigned long start_index, int num_pages) { unsigned long file_end; u64 isize = i_size_read(inode); u64 page_start; u64 page_end; u64 page_cnt; int ret; int i; int i_done; struct btrfs_ordered_extent *ordered; struct extent_state *cached_state = NULL; struct extent_io_tree *tree; gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping); file_end = (isize - 1) >> PAGE_CACHE_SHIFT; if (!isize || start_index > file_end) return 0; page_cnt = min_t(u64, (u64)num_pages, (u64)file_end - start_index + 1); ret = btrfs_delalloc_reserve_space(inode, page_cnt << PAGE_CACHE_SHIFT); if (ret) return ret; i_done = 0; tree = &BTRFS_I(inode)->io_tree; /* step one, lock all the pages */ for (i = 0; i < page_cnt; i++) { struct page *page; again: page = find_or_create_page(inode->i_mapping, start_index + i, mask); if (!page) break; page_start = page_offset(page); page_end = page_start + PAGE_CACHE_SIZE - 1; while (1) { lock_extent(tree, page_start, page_end); ordered = btrfs_lookup_ordered_extent(inode, page_start); unlock_extent(tree, page_start, page_end); if (!ordered) break; unlock_page(page); btrfs_start_ordered_extent(inode, ordered, 1); btrfs_put_ordered_extent(ordered); lock_page(page); /* * we unlocked the page above, so we need check if * it was released or not. */ if (page->mapping != inode->i_mapping) { unlock_page(page); page_cache_release(page); goto again; } } if (!PageUptodate(page)) { btrfs_readpage(NULL, page); lock_page(page); if (!PageUptodate(page)) { unlock_page(page); page_cache_release(page); ret = -EIO; break; } } if (page->mapping != inode->i_mapping) { unlock_page(page); page_cache_release(page); goto again; } pages[i] = page; i_done++; } if (!i_done || ret) goto out; if (!(inode->i_sb->s_flags & MS_ACTIVE)) goto out; /* * so now we have a nice long stream of locked * and up to date pages, lets wait on them */ for (i = 0; i < i_done; i++) wait_on_page_writeback(pages[i]); page_start = page_offset(pages[0]); page_end = page_offset(pages[i_done - 1]) + PAGE_CACHE_SIZE; lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end - 1, 0, &cached_state); clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end - 1, EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS); if (i_done != page_cnt) { spin_lock(&BTRFS_I(inode)->lock); BTRFS_I(inode)->outstanding_extents++; spin_unlock(&BTRFS_I(inode)->lock); btrfs_delalloc_release_space(inode, (page_cnt - i_done) << PAGE_CACHE_SHIFT); } set_extent_defrag(&BTRFS_I(inode)->io_tree, page_start, page_end - 1, &cached_state, GFP_NOFS); unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end - 1, &cached_state, GFP_NOFS); for (i = 0; i < i_done; i++) { clear_page_dirty_for_io(pages[i]); ClearPageChecked(pages[i]); set_page_extent_mapped(pages[i]); set_page_dirty(pages[i]); unlock_page(pages[i]); page_cache_release(pages[i]); } return i_done; out: for (i = 0; i < i_done; i++) { unlock_page(pages[i]); page_cache_release(pages[i]); } btrfs_delalloc_release_space(inode, page_cnt << PAGE_CACHE_SHIFT); return ret; } int btrfs_defrag_file(struct inode *inode, struct file *file, struct btrfs_ioctl_defrag_range_args *range, u64 newer_than, unsigned long max_to_defrag) { struct btrfs_root *root = BTRFS_I(inode)->root; struct file_ra_state *ra = NULL; unsigned long last_index; u64 isize = i_size_read(inode); u64 last_len = 0; u64 skip = 0; u64 defrag_end = 0; u64 newer_off = range->start; unsigned long i; unsigned long ra_index = 0; int ret; int defrag_count = 0; int compress_type = BTRFS_COMPRESS_ZLIB; int extent_thresh = range->extent_thresh; int max_cluster = (256 * 1024) >> PAGE_CACHE_SHIFT; int cluster = max_cluster; u64 new_align = ~((u64)128 * 1024 - 1); struct page **pages = NULL; if (extent_thresh == 0) extent_thresh = 256 * 1024; if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) { if (range->compress_type > BTRFS_COMPRESS_TYPES) return -EINVAL; if (range->compress_type) compress_type = range->compress_type; } if (isize == 0) return 0; /* * if we were not given a file, allocate a readahead * context */ if (!file) { ra = kzalloc(sizeof(*ra), GFP_NOFS); if (!ra) return -ENOMEM; file_ra_state_init(ra, inode->i_mapping); } else { ra = &file->f_ra; } pages = kmalloc(sizeof(struct page *) * max_cluster, GFP_NOFS); if (!pages) { ret = -ENOMEM; goto out_ra; } /* find the last page to defrag */ if (range->start + range->len > range->start) { last_index = min_t(u64, isize - 1, range->start + range->len - 1) >> PAGE_CACHE_SHIFT; } else { last_index = (isize - 1) >> PAGE_CACHE_SHIFT; } if (newer_than) { ret = find_new_extents(root, inode, newer_than, &newer_off, 64 * 1024); if (!ret) { range->start = newer_off; /* * we always align our defrag to help keep * the extents in the file evenly spaced */ i = (newer_off & new_align) >> PAGE_CACHE_SHIFT; } else goto out_ra; } else { i = range->start >> PAGE_CACHE_SHIFT; } if (!max_to_defrag) max_to_defrag = last_index + 1; /* * make writeback starts from i, so the defrag range can be * written sequentially. */ if (i < inode->i_mapping->writeback_index) inode->i_mapping->writeback_index = i; while (i <= last_index && defrag_count < max_to_defrag && (i < (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT)) { /* * make sure we stop running if someone unmounts * the FS */ if (!(inode->i_sb->s_flags & MS_ACTIVE)) break; if (!should_defrag_range(inode, (u64)i << PAGE_CACHE_SHIFT, extent_thresh, &last_len, &skip, &defrag_end, range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) { unsigned long next; /* * the should_defrag function tells us how much to skip * bump our counter by the suggested amount */ next = (skip + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT; i = max(i + 1, next); continue; } if (!newer_than) { cluster = (PAGE_CACHE_ALIGN(defrag_end) >> PAGE_CACHE_SHIFT) - i; cluster = min(cluster, max_cluster); } else { cluster = max_cluster; } if (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS) BTRFS_I(inode)->force_compress = compress_type; if (i + cluster > ra_index) { ra_index = max(i, ra_index); btrfs_force_ra(inode->i_mapping, ra, file, ra_index, cluster); ra_index += max_cluster; } mutex_lock(&inode->i_mutex); ret = cluster_pages_for_defrag(inode, pages, i, cluster); if (ret < 0) { mutex_unlock(&inode->i_mutex); goto out_ra; } defrag_count += ret; balance_dirty_pages_ratelimited_nr(inode->i_mapping, ret); mutex_unlock(&inode->i_mutex); if (newer_than) { if (newer_off == (u64)-1) break; if (ret > 0) i += ret; newer_off = max(newer_off + 1, (u64)i << PAGE_CACHE_SHIFT); ret = find_new_extents(root, inode, newer_than, &newer_off, 64 * 1024); if (!ret) { range->start = newer_off; i = (newer_off & new_align) >> PAGE_CACHE_SHIFT; } else { break; } } else { if (ret > 0) { i += ret; last_len += ret << PAGE_CACHE_SHIFT; } else { i++; last_len = 0; } } } if ((range->flags & BTRFS_DEFRAG_RANGE_START_IO)) filemap_flush(inode->i_mapping); if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) { /* the filemap_flush will queue IO into the worker threads, but * we have to make sure the IO is actually started and that * ordered extents get created before we return */ atomic_inc(&root->fs_info->async_submit_draining); while (atomic_read(&root->fs_info->nr_async_submits) || atomic_read(&root->fs_info->async_delalloc_pages)) { wait_event(root->fs_info->async_submit_wait, (atomic_read(&root->fs_info->nr_async_submits) == 0 && atomic_read(&root->fs_info->async_delalloc_pages) == 0)); } atomic_dec(&root->fs_info->async_submit_draining); mutex_lock(&inode->i_mutex); BTRFS_I(inode)->force_compress = BTRFS_COMPRESS_NONE; mutex_unlock(&inode->i_mutex); } if (range->compress_type == BTRFS_COMPRESS_LZO) { btrfs_set_fs_incompat(root->fs_info, COMPRESS_LZO); } ret = defrag_count; out_ra: if (!file) kfree(ra); kfree(pages); return ret; } static noinline int btrfs_ioctl_resize(struct file *file, void __user *arg) { u64 new_size; u64 old_size; u64 devid = 1; struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root; struct btrfs_ioctl_vol_args *vol_args; struct btrfs_trans_handle *trans; struct btrfs_device *device = NULL; char *sizestr; char *devstr = NULL; int ret = 0; int mod = 0; if (root->fs_info->sb->s_flags & MS_RDONLY) return -EROFS; if (!capable(CAP_SYS_ADMIN)) return -EPERM; ret = mnt_want_write_file(file); if (ret) return ret; if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running, 1)) { pr_info("btrfs: dev add/delete/balance/replace/resize operation in progress\n"); return -EINPROGRESS; } mutex_lock(&root->fs_info->volume_mutex); vol_args = memdup_user(arg, sizeof(*vol_args)); if (IS_ERR(vol_args)) { ret = PTR_ERR(vol_args); goto out; } vol_args->name[BTRFS_PATH_NAME_MAX] = '\0'; sizestr = vol_args->name; devstr = strchr(sizestr, ':'); if (devstr) { char *end; sizestr = devstr + 1; *devstr = '\0'; devstr = vol_args->name; devid = simple_strtoull(devstr, &end, 10); printk(KERN_INFO "btrfs: resizing devid %llu\n", (unsigned long long)devid); } device = btrfs_find_device(root->fs_info, devid, NULL, NULL); if (!device) { printk(KERN_INFO "btrfs: resizer unable to find device %llu\n", (unsigned long long)devid); ret = -EINVAL; goto out_free; } if (device->fs_devices && device->fs_devices->seeding) { printk(KERN_INFO "btrfs: resizer unable to apply on " "seeding device %llu\n", (unsigned long long)devid); ret = -EINVAL; goto out_free; } if (!strcmp(sizestr, "max")) new_size = device->bdev->bd_inode->i_size; else { if (sizestr[0] == '-') { mod = -1; sizestr++; } else if (sizestr[0] == '+') { mod = 1; sizestr++; } new_size = memparse(sizestr, NULL); if (new_size == 0) { ret = -EINVAL; goto out_free; } } if (device->is_tgtdev_for_dev_replace) { ret = -EINVAL; goto out_free; } old_size = device->total_bytes; if (mod < 0) { if (new_size > old_size) { ret = -EINVAL; goto out_free; } new_size = old_size - new_size; } else if (mod > 0) { new_size = old_size + new_size; } if (new_size < 256 * 1024 * 1024) { ret = -EINVAL; goto out_free; } if (new_size > device->bdev->bd_inode->i_size) { ret = -EFBIG; goto out_free; } do_div(new_size, root->sectorsize); new_size *= root->sectorsize; printk_in_rcu(KERN_INFO "btrfs: new size for %s is %llu\n", rcu_str_deref(device->name), (unsigned long long)new_size); if (new_size > old_size) { trans = btrfs_start_transaction(root, 0); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out_free; } ret = btrfs_grow_device(trans, device, new_size); btrfs_commit_transaction(trans, root); } else if (new_size < old_size) { ret = btrfs_shrink_device(device, new_size); } /* equal, nothing need to do */ out_free: kfree(vol_args); out: mutex_unlock(&root->fs_info->volume_mutex); mnt_drop_write_file(file); atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0); return ret; } static noinline int btrfs_ioctl_snap_create_transid(struct file *file, char *name, unsigned long fd, int subvol, u64 *transid, bool readonly, struct btrfs_qgroup_inherit **inherit) { int namelen; int ret = 0; ret = mnt_want_write_file(file); if (ret) goto out; namelen = strlen(name); if (strchr(name, '/')) { ret = -EINVAL; goto out_drop_write; } if (name[0] == '.' && (namelen == 1 || (name[1] == '.' && namelen == 2))) { ret = -EEXIST; goto out_drop_write; } if (subvol) { ret = btrfs_mksubvol(&file->f_path, name, namelen, NULL, transid, readonly, inherit); } else { struct fd src = fdget(fd); struct inode *src_inode; if (!src.file) { ret = -EINVAL; goto out_drop_write; } src_inode = src.file->f_path.dentry->d_inode; if (src_inode->i_sb != file->f_path.dentry->d_inode->i_sb) { printk(KERN_INFO "btrfs: Snapshot src from " "another FS\n"); ret = -EINVAL; } else { ret = btrfs_mksubvol(&file->f_path, name, namelen, BTRFS_I(src_inode)->root, transid, readonly, inherit); } fdput(src); } out_drop_write: mnt_drop_write_file(file); out: return ret; } static noinline int btrfs_ioctl_snap_create(struct file *file, void __user *arg, int subvol) { struct btrfs_ioctl_vol_args *vol_args; int ret; vol_args = memdup_user(arg, sizeof(*vol_args)); if (IS_ERR(vol_args)) return PTR_ERR(vol_args); vol_args->name[BTRFS_PATH_NAME_MAX] = '\0'; ret = btrfs_ioctl_snap_create_transid(file, vol_args->name, vol_args->fd, subvol, NULL, false, NULL); kfree(vol_args); return ret; } static noinline int btrfs_ioctl_snap_create_v2(struct file *file, void __user *arg, int subvol) { struct btrfs_ioctl_vol_args_v2 *vol_args; int ret; u64 transid = 0; u64 *ptr = NULL; bool readonly = false; struct btrfs_qgroup_inherit *inherit = NULL; vol_args = memdup_user(arg, sizeof(*vol_args)); if (IS_ERR(vol_args)) return PTR_ERR(vol_args); vol_args->name[BTRFS_SUBVOL_NAME_MAX] = '\0'; if (vol_args->flags & ~(BTRFS_SUBVOL_CREATE_ASYNC | BTRFS_SUBVOL_RDONLY | BTRFS_SUBVOL_QGROUP_INHERIT)) { ret = -EOPNOTSUPP; goto out; } if (vol_args->flags & BTRFS_SUBVOL_CREATE_ASYNC) ptr = &transid; if (vol_args->flags & BTRFS_SUBVOL_RDONLY) readonly = true; if (vol_args->flags & BTRFS_SUBVOL_QGROUP_INHERIT) { if (vol_args->size > PAGE_CACHE_SIZE) { ret = -EINVAL; goto out; } inherit = memdup_user(vol_args->qgroup_inherit, vol_args->size); if (IS_ERR(inherit)) { ret = PTR_ERR(inherit); goto out; } } ret = btrfs_ioctl_snap_create_transid(file, vol_args->name, vol_args->fd, subvol, ptr, readonly, &inherit); if (ret == 0 && ptr && copy_to_user(arg + offsetof(struct btrfs_ioctl_vol_args_v2, transid), ptr, sizeof(*ptr))) ret = -EFAULT; out: kfree(vol_args); kfree(inherit); return ret; } static noinline int btrfs_ioctl_subvol_getflags(struct file *file, void __user *arg) { struct inode *inode = fdentry(file)->d_inode; struct btrfs_root *root = BTRFS_I(inode)->root; int ret = 0; u64 flags = 0; if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) return -EINVAL; down_read(&root->fs_info->subvol_sem); if (btrfs_root_readonly(root)) flags |= BTRFS_SUBVOL_RDONLY; up_read(&root->fs_info->subvol_sem); if (copy_to_user(arg, &flags, sizeof(flags))) ret = -EFAULT; return ret; } static noinline int btrfs_ioctl_subvol_setflags(struct file *file, void __user *arg) { struct inode *inode = fdentry(file)->d_inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; u64 root_flags; u64 flags; int ret = 0; ret = mnt_want_write_file(file); if (ret) goto out; if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) { ret = -EINVAL; goto out_drop_write; } if (copy_from_user(&flags, arg, sizeof(flags))) { ret = -EFAULT; goto out_drop_write; } if (flags & BTRFS_SUBVOL_CREATE_ASYNC) { ret = -EINVAL; goto out_drop_write; } if (flags & ~BTRFS_SUBVOL_RDONLY) { ret = -EOPNOTSUPP; goto out_drop_write; } if (!inode_owner_or_capable(inode)) { ret = -EACCES; goto out_drop_write; } down_write(&root->fs_info->subvol_sem); /* nothing to do */ if (!!(flags & BTRFS_SUBVOL_RDONLY) == btrfs_root_readonly(root)) goto out_drop_sem; root_flags = btrfs_root_flags(&root->root_item); if (flags & BTRFS_SUBVOL_RDONLY) btrfs_set_root_flags(&root->root_item, root_flags | BTRFS_ROOT_SUBVOL_RDONLY); else btrfs_set_root_flags(&root->root_item, root_flags & ~BTRFS_ROOT_SUBVOL_RDONLY); trans = btrfs_start_transaction(root, 1); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out_reset; } ret = btrfs_update_root(trans, root->fs_info->tree_root, &root->root_key, &root->root_item); btrfs_commit_transaction(trans, root); out_reset: if (ret) btrfs_set_root_flags(&root->root_item, root_flags); out_drop_sem: up_write(&root->fs_info->subvol_sem); out_drop_write: mnt_drop_write_file(file); out: return ret; } /* * helper to check if the subvolume references other subvolumes */ static noinline int may_destroy_subvol(struct btrfs_root *root) { struct btrfs_path *path; struct btrfs_key key; int ret; path = btrfs_alloc_path(); if (!path) return -ENOMEM; key.objectid = root->root_key.objectid; key.type = BTRFS_ROOT_REF_KEY; key.offset = (u64)-1; ret = btrfs_search_slot(NULL, root->fs_info->tree_root, &key, path, 0, 0); if (ret < 0) goto out; BUG_ON(ret == 0); ret = 0; if (path->slots[0] > 0) { path->slots[0]--; btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]); if (key.objectid == root->root_key.objectid && key.type == BTRFS_ROOT_REF_KEY) ret = -ENOTEMPTY; } out: btrfs_free_path(path); return ret; } static noinline int key_in_sk(struct btrfs_key *key, struct btrfs_ioctl_search_key *sk) { struct btrfs_key test; int ret; test.objectid = sk->min_objectid; test.type = sk->min_type; test.offset = sk->min_offset; ret = btrfs_comp_cpu_keys(key, &test); if (ret < 0) return 0; test.objectid = sk->max_objectid; test.type = sk->max_type; test.offset = sk->max_offset; ret = btrfs_comp_cpu_keys(key, &test); if (ret > 0) return 0; return 1; } static noinline int copy_to_sk(struct btrfs_root *root, struct btrfs_path *path, struct btrfs_key *key, struct btrfs_ioctl_search_key *sk, char *buf, unsigned long *sk_offset, int *num_found) { u64 found_transid; struct extent_buffer *leaf; struct btrfs_ioctl_search_header sh; unsigned long item_off; unsigned long item_len; int nritems; int i; int slot; int ret = 0; leaf = path->nodes[0]; slot = path->slots[0]; nritems = btrfs_header_nritems(leaf); if (btrfs_header_generation(leaf) > sk->max_transid) { i = nritems; goto advance_key; } found_transid = btrfs_header_generation(leaf); for (i = slot; i < nritems; i++) { item_off = btrfs_item_ptr_offset(leaf, i); item_len = btrfs_item_size_nr(leaf, i); if (item_len > BTRFS_SEARCH_ARGS_BUFSIZE) item_len = 0; if (sizeof(sh) + item_len + *sk_offset > BTRFS_SEARCH_ARGS_BUFSIZE) { ret = 1; goto overflow; } btrfs_item_key_to_cpu(leaf, key, i); if (!key_in_sk(key, sk)) continue; sh.objectid = key->objectid; sh.offset = key->offset; sh.type = key->type; sh.len = item_len; sh.transid = found_transid; /* copy search result header */ memcpy(buf + *sk_offset, &sh, sizeof(sh)); *sk_offset += sizeof(sh); if (item_len) { char *p = buf + *sk_offset; /* copy the item */ read_extent_buffer(leaf, p, item_off, item_len); *sk_offset += item_len; } (*num_found)++; if (*num_found >= sk->nr_items) break; } advance_key: ret = 0; if (key->offset < (u64)-1 && key->offset < sk->max_offset) key->offset++; else if (key->type < (u8)-1 && key->type < sk->max_type) { key->offset = 0; key->type++; } else if (key->objectid < (u64)-1 && key->objectid < sk->max_objectid) { key->offset = 0; key->type = 0; key->objectid++; } else ret = 1; overflow: return ret; } static noinline int search_ioctl(struct inode *inode, struct btrfs_ioctl_search_args *args) { struct btrfs_root *root; struct btrfs_key key; struct btrfs_key max_key; struct btrfs_path *path; struct btrfs_ioctl_search_key *sk = &args->key; struct btrfs_fs_info *info = BTRFS_I(inode)->root->fs_info; int ret; int num_found = 0; unsigned long sk_offset = 0; path = btrfs_alloc_path(); if (!path) return -ENOMEM; if (sk->tree_id == 0) { /* search the root of the inode that was passed */ root = BTRFS_I(inode)->root; } else { key.objectid = sk->tree_id; key.type = BTRFS_ROOT_ITEM_KEY; key.offset = (u64)-1; root = btrfs_read_fs_root_no_name(info, &key); if (IS_ERR(root)) { printk(KERN_ERR "could not find root %llu\n", sk->tree_id); btrfs_free_path(path); return -ENOENT; } } key.objectid = sk->min_objectid; key.type = sk->min_type; key.offset = sk->min_offset; max_key.objectid = sk->max_objectid; max_key.type = sk->max_type; max_key.offset = sk->max_offset; path->keep_locks = 1; while(1) { ret = btrfs_search_forward(root, &key, &max_key, path, 0, sk->min_transid); if (ret != 0) { if (ret > 0) ret = 0; goto err; } ret = copy_to_sk(root, path, &key, sk, args->buf, &sk_offset, &num_found); btrfs_release_path(path); if (ret || num_found >= sk->nr_items) break; } ret = 0; err: sk->nr_items = num_found; btrfs_free_path(path); return ret; } static noinline int btrfs_ioctl_tree_search(struct file *file, void __user *argp) { struct btrfs_ioctl_search_args *args; struct inode *inode; int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; args = memdup_user(argp, sizeof(*args)); if (IS_ERR(args)) return PTR_ERR(args); inode = fdentry(file)->d_inode; ret = search_ioctl(inode, args); if (ret == 0 && copy_to_user(argp, args, sizeof(*args))) ret = -EFAULT; kfree(args); return ret; } /* * Search INODE_REFs to identify path name of 'dirid' directory * in a 'tree_id' tree. and sets path name to 'name'. */ static noinline int btrfs_search_path_in_tree(struct btrfs_fs_info *info, u64 tree_id, u64 dirid, char *name) { struct btrfs_root *root; struct btrfs_key key; char *ptr; int ret = -1; int slot; int len; int total_len = 0; struct btrfs_inode_ref *iref; struct extent_buffer *l; struct btrfs_path *path; if (dirid == BTRFS_FIRST_FREE_OBJECTID) { name[0]='\0'; return 0; } path = btrfs_alloc_path(); if (!path) return -ENOMEM; ptr = &name[BTRFS_INO_LOOKUP_PATH_MAX]; key.objectid = tree_id; key.type = BTRFS_ROOT_ITEM_KEY; key.offset = (u64)-1; root = btrfs_read_fs_root_no_name(info, &key); if (IS_ERR(root)) { printk(KERN_ERR "could not find root %llu\n", tree_id); ret = -ENOENT; goto out; } key.objectid = dirid; key.type = BTRFS_INODE_REF_KEY; key.offset = (u64)-1; while(1) { ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) goto out; l = path->nodes[0]; slot = path->slots[0]; if (ret > 0 && slot > 0) slot--; btrfs_item_key_to_cpu(l, &key, slot); if (ret > 0 && (key.objectid != dirid || key.type != BTRFS_INODE_REF_KEY)) { ret = -ENOENT; goto out; } iref = btrfs_item_ptr(l, slot, struct btrfs_inode_ref); len = btrfs_inode_ref_name_len(l, iref); ptr -= len + 1; total_len += len + 1; if (ptr < name) goto out; *(ptr + len) = '/'; read_extent_buffer(l, ptr,(unsigned long)(iref + 1), len); if (key.offset == BTRFS_FIRST_FREE_OBJECTID) break; btrfs_release_path(path); key.objectid = key.offset; key.offset = (u64)-1; dirid = key.objectid; } if (ptr < name) goto out; memmove(name, ptr, total_len); name[total_len]='\0'; ret = 0; out: btrfs_free_path(path); return ret; } static noinline int btrfs_ioctl_ino_lookup(struct file *file, void __user *argp) { struct btrfs_ioctl_ino_lookup_args *args; struct inode *inode; int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; args = memdup_user(argp, sizeof(*args)); if (IS_ERR(args)) return PTR_ERR(args); inode = fdentry(file)->d_inode; if (args->treeid == 0) args->treeid = BTRFS_I(inode)->root->root_key.objectid; ret = btrfs_search_path_in_tree(BTRFS_I(inode)->root->fs_info, args->treeid, args->objectid, args->name); if (ret == 0 && copy_to_user(argp, args, sizeof(*args))) ret = -EFAULT; kfree(args); return ret; } static noinline int btrfs_ioctl_snap_destroy(struct file *file, void __user *arg) { struct dentry *parent = fdentry(file); struct dentry *dentry; struct inode *dir = parent->d_inode; struct inode *inode; struct btrfs_root *root = BTRFS_I(dir)->root; struct btrfs_root *dest = NULL; struct btrfs_ioctl_vol_args *vol_args; struct btrfs_trans_handle *trans; int namelen; int ret; int err = 0; vol_args = memdup_user(arg, sizeof(*vol_args)); if (IS_ERR(vol_args)) return PTR_ERR(vol_args); vol_args->name[BTRFS_PATH_NAME_MAX] = '\0'; namelen = strlen(vol_args->name); if (strchr(vol_args->name, '/') || strncmp(vol_args->name, "..", namelen) == 0) { err = -EINVAL; goto out; } err = mnt_want_write_file(file); if (err) goto out; mutex_lock_nested(&dir->i_mutex, I_MUTEX_PARENT); dentry = lookup_one_len(vol_args->name, parent, namelen); if (IS_ERR(dentry)) { err = PTR_ERR(dentry); goto out_unlock_dir; } if (!dentry->d_inode) { err = -ENOENT; goto out_dput; } inode = dentry->d_inode; dest = BTRFS_I(inode)->root; if (!capable(CAP_SYS_ADMIN)){ /* * Regular user. Only allow this with a special mount * option, when the user has write+exec access to the * subvol root, and when rmdir(2) would have been * allowed. * * Note that this is _not_ check that the subvol is * empty or doesn't contain data that we wouldn't * otherwise be able to delete. * * Users who want to delete empty subvols should try * rmdir(2). */ err = -EPERM; if (!btrfs_test_opt(root, USER_SUBVOL_RM_ALLOWED)) goto out_dput; /* * Do not allow deletion if the parent dir is the same * as the dir to be deleted. That means the ioctl * must be called on the dentry referencing the root * of the subvol, not a random directory contained * within it. */ err = -EINVAL; if (root == dest) goto out_dput; err = inode_permission(inode, MAY_WRITE | MAY_EXEC); if (err) goto out_dput; /* check if subvolume may be deleted by a non-root user */ err = btrfs_may_delete(dir, dentry, 1); if (err) goto out_dput; } if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) { err = -EINVAL; goto out_dput; } mutex_lock(&inode->i_mutex); err = d_invalidate(dentry); if (err) goto out_unlock; down_write(&root->fs_info->subvol_sem); err = may_destroy_subvol(dest); if (err) goto out_up_write; trans = btrfs_start_transaction(root, 0); if (IS_ERR(trans)) { err = PTR_ERR(trans); goto out_up_write; } trans->block_rsv = &root->fs_info->global_block_rsv; ret = btrfs_unlink_subvol(trans, root, dir, dest->root_key.objectid, dentry->d_name.name, dentry->d_name.len); if (ret) { err = ret; btrfs_abort_transaction(trans, root, ret); goto out_end_trans; } btrfs_record_root_in_trans(trans, dest); memset(&dest->root_item.drop_progress, 0, sizeof(dest->root_item.drop_progress)); dest->root_item.drop_level = 0; btrfs_set_root_refs(&dest->root_item, 0); if (!xchg(&dest->orphan_item_inserted, 1)) { ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root, dest->root_key.objectid); if (ret) { btrfs_abort_transaction(trans, root, ret); err = ret; goto out_end_trans; } } out_end_trans: ret = btrfs_end_transaction(trans, root); if (ret && !err) err = ret; inode->i_flags |= S_DEAD; out_up_write: up_write(&root->fs_info->subvol_sem); out_unlock: mutex_unlock(&inode->i_mutex); if (!err) { shrink_dcache_sb(root->fs_info->sb); btrfs_invalidate_inodes(dest); d_delete(dentry); } out_dput: dput(dentry); out_unlock_dir: mutex_unlock(&dir->i_mutex); mnt_drop_write_file(file); out: kfree(vol_args); return err; } static int btrfs_ioctl_defrag(struct file *file, void __user *argp) { struct inode *inode = fdentry(file)->d_inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_ioctl_defrag_range_args *range; int ret; if (btrfs_root_readonly(root)) return -EROFS; if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running, 1)) { pr_info("btrfs: dev add/delete/balance/replace/resize operation in progress\n"); return -EINPROGRESS; } ret = mnt_want_write_file(file); if (ret) { atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0); return ret; } switch (inode->i_mode & S_IFMT) { case S_IFDIR: if (!capable(CAP_SYS_ADMIN)) { ret = -EPERM; goto out; } ret = btrfs_defrag_root(root, 0); if (ret) goto out; ret = btrfs_defrag_root(root->fs_info->extent_root, 0); break; case S_IFREG: if (!(file->f_mode & FMODE_WRITE)) { ret = -EINVAL; goto out; } range = kzalloc(sizeof(*range), GFP_KERNEL); if (!range) { ret = -ENOMEM; goto out; } if (argp) { if (copy_from_user(range, argp, sizeof(*range))) { ret = -EFAULT; kfree(range); goto out; } /* compression requires us to start the IO */ if ((range->flags & BTRFS_DEFRAG_RANGE_COMPRESS)) { range->flags |= BTRFS_DEFRAG_RANGE_START_IO; range->extent_thresh = (u32)-1; } } else { /* the rest are all set to zero by kzalloc */ range->len = (u64)-1; } ret = btrfs_defrag_file(fdentry(file)->d_inode, file, range, 0, 0); if (ret > 0) ret = 0; kfree(range); break; default: ret = -EINVAL; } out: mnt_drop_write_file(file); atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0); return ret; } static long btrfs_ioctl_add_dev(struct btrfs_root *root, void __user *arg) { struct btrfs_ioctl_vol_args *vol_args; int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running, 1)) { pr_info("btrfs: dev add/delete/balance/replace/resize operation in progress\n"); return -EINPROGRESS; } mutex_lock(&root->fs_info->volume_mutex); vol_args = memdup_user(arg, sizeof(*vol_args)); if (IS_ERR(vol_args)) { ret = PTR_ERR(vol_args); goto out; } vol_args->name[BTRFS_PATH_NAME_MAX] = '\0'; ret = btrfs_init_new_device(root, vol_args->name); kfree(vol_args); out: mutex_unlock(&root->fs_info->volume_mutex); atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0); return ret; } static long btrfs_ioctl_rm_dev(struct file *file, void __user *arg) { struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root; struct btrfs_ioctl_vol_args *vol_args; int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; ret = mnt_want_write_file(file); if (ret) return ret; if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running, 1)) { pr_info("btrfs: dev add/delete/balance/replace/resize operation in progress\n"); mnt_drop_write_file(file); return -EINPROGRESS; } mutex_lock(&root->fs_info->volume_mutex); vol_args = memdup_user(arg, sizeof(*vol_args)); if (IS_ERR(vol_args)) { ret = PTR_ERR(vol_args); goto out; } vol_args->name[BTRFS_PATH_NAME_MAX] = '\0'; ret = btrfs_rm_device(root, vol_args->name); kfree(vol_args); out: mutex_unlock(&root->fs_info->volume_mutex); mnt_drop_write_file(file); atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0); return ret; } static long btrfs_ioctl_fs_info(struct btrfs_root *root, void __user *arg) { struct btrfs_ioctl_fs_info_args *fi_args; struct btrfs_device *device; struct btrfs_device *next; struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices; int ret = 0; if (!capable(CAP_SYS_ADMIN)) return -EPERM; fi_args = kzalloc(sizeof(*fi_args), GFP_KERNEL); if (!fi_args) return -ENOMEM; fi_args->num_devices = fs_devices->num_devices; memcpy(&fi_args->fsid, root->fs_info->fsid, sizeof(fi_args->fsid)); mutex_lock(&fs_devices->device_list_mutex); list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) { if (device->devid > fi_args->max_id) fi_args->max_id = device->devid; } mutex_unlock(&fs_devices->device_list_mutex); if (copy_to_user(arg, fi_args, sizeof(*fi_args))) ret = -EFAULT; kfree(fi_args); return ret; } static long btrfs_ioctl_dev_info(struct btrfs_root *root, void __user *arg) { struct btrfs_ioctl_dev_info_args *di_args; struct btrfs_device *dev; struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices; int ret = 0; char *s_uuid = NULL; char empty_uuid[BTRFS_UUID_SIZE] = {0}; if (!capable(CAP_SYS_ADMIN)) return -EPERM; di_args = memdup_user(arg, sizeof(*di_args)); if (IS_ERR(di_args)) return PTR_ERR(di_args); if (memcmp(empty_uuid, di_args->uuid, BTRFS_UUID_SIZE) != 0) s_uuid = di_args->uuid; mutex_lock(&fs_devices->device_list_mutex); dev = btrfs_find_device(root->fs_info, di_args->devid, s_uuid, NULL); mutex_unlock(&fs_devices->device_list_mutex); if (!dev) { ret = -ENODEV; goto out; } di_args->devid = dev->devid; di_args->bytes_used = dev->bytes_used; di_args->total_bytes = dev->total_bytes; memcpy(di_args->uuid, dev->uuid, sizeof(di_args->uuid)); if (dev->name) { struct rcu_string *name; rcu_read_lock(); name = rcu_dereference(dev->name); strncpy(di_args->path, name->str, sizeof(di_args->path)); rcu_read_unlock(); di_args->path[sizeof(di_args->path) - 1] = 0; } else { di_args->path[0] = '\0'; } out: if (ret == 0 && copy_to_user(arg, di_args, sizeof(*di_args))) ret = -EFAULT; kfree(di_args); return ret; } static noinline long btrfs_ioctl_clone(struct file *file, unsigned long srcfd, u64 off, u64 olen, u64 destoff) { struct inode *inode = fdentry(file)->d_inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct fd src_file; struct inode *src; struct btrfs_trans_handle *trans; struct btrfs_path *path; struct extent_buffer *leaf; char *buf; struct btrfs_key key; u32 nritems; int slot; int ret; u64 len = olen; u64 bs = root->fs_info->sb->s_blocksize; /* * TODO: * - split compressed inline extents. annoying: we need to * decompress into destination's address_space (the file offset * may change, so source mapping won't do), then recompress (or * otherwise reinsert) a subrange. * - allow ranges within the same file to be cloned (provided * they don't overlap)? */ /* the destination must be opened for writing */ if (!(file->f_mode & FMODE_WRITE) || (file->f_flags & O_APPEND)) return -EINVAL; if (btrfs_root_readonly(root)) return -EROFS; ret = mnt_want_write_file(file); if (ret) return ret; src_file = fdget(srcfd); if (!src_file.file) { ret = -EBADF; goto out_drop_write; } ret = -EXDEV; if (src_file.file->f_path.mnt != file->f_path.mnt) goto out_fput; src = src_file.file->f_dentry->d_inode; ret = -EINVAL; if (src == inode) goto out_fput; /* the src must be open for reading */ if (!(src_file.file->f_mode & FMODE_READ)) goto out_fput; /* don't make the dst file partly checksummed */ if ((BTRFS_I(src)->flags & BTRFS_INODE_NODATASUM) != (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) goto out_fput; ret = -EISDIR; if (S_ISDIR(src->i_mode) || S_ISDIR(inode->i_mode)) goto out_fput; ret = -EXDEV; if (src->i_sb != inode->i_sb) goto out_fput; ret = -ENOMEM; buf = vmalloc(btrfs_level_size(root, 0)); if (!buf) goto out_fput; path = btrfs_alloc_path(); if (!path) { vfree(buf); goto out_fput; } path->reada = 2; if (inode < src) { mutex_lock_nested(&inode->i_mutex, I_MUTEX_PARENT); mutex_lock_nested(&src->i_mutex, I_MUTEX_CHILD); } else { mutex_lock_nested(&src->i_mutex, I_MUTEX_PARENT); mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD); } /* determine range to clone */ ret = -EINVAL; if (off + len > src->i_size || off + len < off) goto out_unlock; if (len == 0) olen = len = src->i_size - off; /* if we extend to eof, continue to block boundary */ if (off + len == src->i_size) len = ALIGN(src->i_size, bs) - off; /* verify the end result is block aligned */ if (!IS_ALIGNED(off, bs) || !IS_ALIGNED(off + len, bs) || !IS_ALIGNED(destoff, bs)) goto out_unlock; if (destoff > inode->i_size) { ret = btrfs_cont_expand(inode, inode->i_size, destoff); if (ret) goto out_unlock; } /* truncate page cache pages from target inode range */ truncate_inode_pages_range(&inode->i_data, destoff, PAGE_CACHE_ALIGN(destoff + len) - 1); /* do any pending delalloc/csum calc on src, one way or another, and lock file content */ while (1) { struct btrfs_ordered_extent *ordered; lock_extent(&BTRFS_I(src)->io_tree, off, off + len - 1); ordered = btrfs_lookup_first_ordered_extent(src, off + len - 1); if (!ordered && !test_range_bit(&BTRFS_I(src)->io_tree, off, off + len - 1, EXTENT_DELALLOC, 0, NULL)) break; unlock_extent(&BTRFS_I(src)->io_tree, off, off + len - 1); if (ordered) btrfs_put_ordered_extent(ordered); btrfs_wait_ordered_range(src, off, len); } /* clone data */ key.objectid = btrfs_ino(src); key.type = BTRFS_EXTENT_DATA_KEY; key.offset = 0; while (1) { /* * note the key will change type as we walk through the * tree. */ ret = btrfs_search_slot(NULL, BTRFS_I(src)->root, &key, path, 0, 0); if (ret < 0) goto out; nritems = btrfs_header_nritems(path->nodes[0]); if (path->slots[0] >= nritems) { ret = btrfs_next_leaf(BTRFS_I(src)->root, path); if (ret < 0) goto out; if (ret > 0) break; nritems = btrfs_header_nritems(path->nodes[0]); } leaf = path->nodes[0]; slot = path->slots[0]; btrfs_item_key_to_cpu(leaf, &key, slot); if (btrfs_key_type(&key) > BTRFS_EXTENT_DATA_KEY || key.objectid != btrfs_ino(src)) break; if (btrfs_key_type(&key) == BTRFS_EXTENT_DATA_KEY) { struct btrfs_file_extent_item *extent; int type; u32 size; struct btrfs_key new_key; u64 disko = 0, diskl = 0; u64 datao = 0, datal = 0; u8 comp; u64 endoff; size = btrfs_item_size_nr(leaf, slot); read_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf, slot), size); extent = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item); comp = btrfs_file_extent_compression(leaf, extent); type = btrfs_file_extent_type(leaf, extent); if (type == BTRFS_FILE_EXTENT_REG || type == BTRFS_FILE_EXTENT_PREALLOC) { disko = btrfs_file_extent_disk_bytenr(leaf, extent); diskl = btrfs_file_extent_disk_num_bytes(leaf, extent); datao = btrfs_file_extent_offset(leaf, extent); datal = btrfs_file_extent_num_bytes(leaf, extent); } else if (type == BTRFS_FILE_EXTENT_INLINE) { /* take upper bound, may be compressed */ datal = btrfs_file_extent_ram_bytes(leaf, extent); } btrfs_release_path(path); if (key.offset + datal <= off || key.offset >= off + len - 1) goto next; memcpy(&new_key, &key, sizeof(new_key)); new_key.objectid = btrfs_ino(inode); if (off <= key.offset) new_key.offset = key.offset + destoff - off; else new_key.offset = destoff; /* * 1 - adjusting old extent (we may have to split it) * 1 - add new extent * 1 - inode update */ trans = btrfs_start_transaction(root, 3); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out; } if (type == BTRFS_FILE_EXTENT_REG || type == BTRFS_FILE_EXTENT_PREALLOC) { /* * a | --- range to clone ---| b * | ------------- extent ------------- | */ /* substract range b */ if (key.offset + datal > off + len) datal = off + len - key.offset; /* substract range a */ if (off > key.offset) { datao += off - key.offset; datal -= off - key.offset; } ret = btrfs_drop_extents(trans, root, inode, new_key.offset, new_key.offset + datal, 1); if (ret) { btrfs_abort_transaction(trans, root, ret); btrfs_end_transaction(trans, root); goto out; } ret = btrfs_insert_empty_item(trans, root, path, &new_key, size); if (ret) { btrfs_abort_transaction(trans, root, ret); btrfs_end_transaction(trans, root); goto out; } leaf = path->nodes[0]; slot = path->slots[0]; write_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf, slot), size); extent = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item); /* disko == 0 means it's a hole */ if (!disko) datao = 0; btrfs_set_file_extent_offset(leaf, extent, datao); btrfs_set_file_extent_num_bytes(leaf, extent, datal); if (disko) { inode_add_bytes(inode, datal); ret = btrfs_inc_extent_ref(trans, root, disko, diskl, 0, root->root_key.objectid, btrfs_ino(inode), new_key.offset - datao, 0); if (ret) { btrfs_abort_transaction(trans, root, ret); btrfs_end_transaction(trans, root); goto out; } } } else if (type == BTRFS_FILE_EXTENT_INLINE) { u64 skip = 0; u64 trim = 0; if (off > key.offset) { skip = off - key.offset; new_key.offset += skip; } if (key.offset + datal > off + len) trim = key.offset + datal - (off + len); if (comp && (skip || trim)) { ret = -EINVAL; btrfs_end_transaction(trans, root); goto out; } size -= skip + trim; datal -= skip + trim; ret = btrfs_drop_extents(trans, root, inode, new_key.offset, new_key.offset + datal, 1); if (ret) { btrfs_abort_transaction(trans, root, ret); btrfs_end_transaction(trans, root); goto out; } ret = btrfs_insert_empty_item(trans, root, path, &new_key, size); if (ret) { btrfs_abort_transaction(trans, root, ret); btrfs_end_transaction(trans, root); goto out; } if (skip) { u32 start = btrfs_file_extent_calc_inline_size(0); memmove(buf+start, buf+start+skip, datal); } leaf = path->nodes[0]; slot = path->slots[0]; write_extent_buffer(leaf, buf, btrfs_item_ptr_offset(leaf, slot), size); inode_add_bytes(inode, datal); } btrfs_mark_buffer_dirty(leaf); btrfs_release_path(path); inode_inc_iversion(inode); inode->i_mtime = inode->i_ctime = CURRENT_TIME; /* * we round up to the block size at eof when * determining which extents to clone above, * but shouldn't round up the file size */ endoff = new_key.offset + datal; if (endoff > destoff+olen) endoff = destoff+olen; if (endoff > inode->i_size) btrfs_i_size_write(inode, endoff); ret = btrfs_update_inode(trans, root, inode); if (ret) { btrfs_abort_transaction(trans, root, ret); btrfs_end_transaction(trans, root); goto out; } ret = btrfs_end_transaction(trans, root); } next: btrfs_release_path(path); key.offset++; } ret = 0; out: btrfs_release_path(path); unlock_extent(&BTRFS_I(src)->io_tree, off, off + len - 1); out_unlock: mutex_unlock(&src->i_mutex); mutex_unlock(&inode->i_mutex); vfree(buf); btrfs_free_path(path); out_fput: fdput(src_file); out_drop_write: mnt_drop_write_file(file); return ret; } static long btrfs_ioctl_clone_range(struct file *file, void __user *argp) { struct btrfs_ioctl_clone_range_args args; if (copy_from_user(&args, argp, sizeof(args))) return -EFAULT; return btrfs_ioctl_clone(file, args.src_fd, args.src_offset, args.src_length, args.dest_offset); } /* * there are many ways the trans_start and trans_end ioctls can lead * to deadlocks. They should only be used by applications that * basically own the machine, and have a very in depth understanding * of all the possible deadlocks and enospc problems. */ static long btrfs_ioctl_trans_start(struct file *file) { struct inode *inode = fdentry(file)->d_inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; int ret; ret = -EPERM; if (!capable(CAP_SYS_ADMIN)) goto out; ret = -EINPROGRESS; if (file->private_data) goto out; ret = -EROFS; if (btrfs_root_readonly(root)) goto out; ret = mnt_want_write_file(file); if (ret) goto out; atomic_inc(&root->fs_info->open_ioctl_trans); ret = -ENOMEM; trans = btrfs_start_ioctl_transaction(root); if (IS_ERR(trans)) goto out_drop; file->private_data = trans; return 0; out_drop: atomic_dec(&root->fs_info->open_ioctl_trans); mnt_drop_write_file(file); out: return ret; } static long btrfs_ioctl_default_subvol(struct file *file, void __user *argp) { struct inode *inode = fdentry(file)->d_inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_root *new_root; struct btrfs_dir_item *di; struct btrfs_trans_handle *trans; struct btrfs_path *path; struct btrfs_key location; struct btrfs_disk_key disk_key; u64 objectid = 0; u64 dir_id; int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; ret = mnt_want_write_file(file); if (ret) return ret; if (copy_from_user(&objectid, argp, sizeof(objectid))) { ret = -EFAULT; goto out; } if (!objectid) objectid = root->root_key.objectid; location.objectid = objectid; location.type = BTRFS_ROOT_ITEM_KEY; location.offset = (u64)-1; new_root = btrfs_read_fs_root_no_name(root->fs_info, &location); if (IS_ERR(new_root)) { ret = PTR_ERR(new_root); goto out; } if (btrfs_root_refs(&new_root->root_item) == 0) { ret = -ENOENT; goto out; } path = btrfs_alloc_path(); if (!path) { ret = -ENOMEM; goto out; } path->leave_spinning = 1; trans = btrfs_start_transaction(root, 1); if (IS_ERR(trans)) { btrfs_free_path(path); ret = PTR_ERR(trans); goto out; } dir_id = btrfs_super_root_dir(root->fs_info->super_copy); di = btrfs_lookup_dir_item(trans, root->fs_info->tree_root, path, dir_id, "default", 7, 1); if (IS_ERR_OR_NULL(di)) { btrfs_free_path(path); btrfs_end_transaction(trans, root); printk(KERN_ERR "Umm, you don't have the default dir item, " "this isn't going to work\n"); ret = -ENOENT; goto out; } btrfs_cpu_key_to_disk(&disk_key, &new_root->root_key); btrfs_set_dir_item_key(path->nodes[0], di, &disk_key); btrfs_mark_buffer_dirty(path->nodes[0]); btrfs_free_path(path); btrfs_set_fs_incompat(root->fs_info, DEFAULT_SUBVOL); btrfs_end_transaction(trans, root); out: mnt_drop_write_file(file); return ret; } void btrfs_get_block_group_info(struct list_head *groups_list, struct btrfs_ioctl_space_info *space) { struct btrfs_block_group_cache *block_group; space->total_bytes = 0; space->used_bytes = 0; space->flags = 0; list_for_each_entry(block_group, groups_list, list) { space->flags = block_group->flags; space->total_bytes += block_group->key.offset; space->used_bytes += btrfs_block_group_used(&block_group->item); } } long btrfs_ioctl_space_info(struct btrfs_root *root, void __user *arg) { struct btrfs_ioctl_space_args space_args; struct btrfs_ioctl_space_info space; struct btrfs_ioctl_space_info *dest; struct btrfs_ioctl_space_info *dest_orig; struct btrfs_ioctl_space_info __user *user_dest; struct btrfs_space_info *info; u64 types[] = {BTRFS_BLOCK_GROUP_DATA, BTRFS_BLOCK_GROUP_SYSTEM, BTRFS_BLOCK_GROUP_METADATA, BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA}; int num_types = 4; int alloc_size; int ret = 0; u64 slot_count = 0; int i, c; if (copy_from_user(&space_args, (struct btrfs_ioctl_space_args __user *)arg, sizeof(space_args))) return -EFAULT; for (i = 0; i < num_types; i++) { struct btrfs_space_info *tmp; info = NULL; rcu_read_lock(); list_for_each_entry_rcu(tmp, &root->fs_info->space_info, list) { if (tmp->flags == types[i]) { info = tmp; break; } } rcu_read_unlock(); if (!info) continue; down_read(&info->groups_sem); for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) { if (!list_empty(&info->block_groups[c])) slot_count++; } up_read(&info->groups_sem); } /* space_slots == 0 means they are asking for a count */ if (space_args.space_slots == 0) { space_args.total_spaces = slot_count; goto out; } slot_count = min_t(u64, space_args.space_slots, slot_count); alloc_size = sizeof(*dest) * slot_count; /* we generally have at most 6 or so space infos, one for each raid * level. So, a whole page should be more than enough for everyone */ if (alloc_size > PAGE_CACHE_SIZE) return -ENOMEM; space_args.total_spaces = 0; dest = kmalloc(alloc_size, GFP_NOFS); if (!dest) return -ENOMEM; dest_orig = dest; /* now we have a buffer to copy into */ for (i = 0; i < num_types; i++) { struct btrfs_space_info *tmp; if (!slot_count) break; info = NULL; rcu_read_lock(); list_for_each_entry_rcu(tmp, &root->fs_info->space_info, list) { if (tmp->flags == types[i]) { info = tmp; break; } } rcu_read_unlock(); if (!info) continue; down_read(&info->groups_sem); for (c = 0; c < BTRFS_NR_RAID_TYPES; c++) { if (!list_empty(&info->block_groups[c])) { btrfs_get_block_group_info( &info->block_groups[c], &space); memcpy(dest, &space, sizeof(space)); dest++; space_args.total_spaces++; slot_count--; } if (!slot_count) break; } up_read(&info->groups_sem); } user_dest = (struct btrfs_ioctl_space_info __user *) (arg + sizeof(struct btrfs_ioctl_space_args)); if (copy_to_user(user_dest, dest_orig, alloc_size)) ret = -EFAULT; kfree(dest_orig); out: if (ret == 0 && copy_to_user(arg, &space_args, sizeof(space_args))) ret = -EFAULT; return ret; } /* * there are many ways the trans_start and trans_end ioctls can lead * to deadlocks. They should only be used by applications that * basically own the machine, and have a very in depth understanding * of all the possible deadlocks and enospc problems. */ long btrfs_ioctl_trans_end(struct file *file) { struct inode *inode = fdentry(file)->d_inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; trans = file->private_data; if (!trans) return -EINVAL; file->private_data = NULL; btrfs_end_transaction(trans, root); atomic_dec(&root->fs_info->open_ioctl_trans); mnt_drop_write_file(file); return 0; } static noinline long btrfs_ioctl_start_sync(struct btrfs_root *root, void __user *argp) { struct btrfs_trans_handle *trans; u64 transid; int ret; trans = btrfs_attach_transaction(root); if (IS_ERR(trans)) { if (PTR_ERR(trans) != -ENOENT) return PTR_ERR(trans); /* No running transaction, don't bother */ transid = root->fs_info->last_trans_committed; goto out; } transid = trans->transid; ret = btrfs_commit_transaction_async(trans, root, 0); if (ret) { btrfs_end_transaction(trans, root); return ret; } out: if (argp) if (copy_to_user(argp, &transid, sizeof(transid))) return -EFAULT; return 0; } static noinline long btrfs_ioctl_wait_sync(struct btrfs_root *root, void __user *argp) { u64 transid; if (argp) { if (copy_from_user(&transid, argp, sizeof(transid))) return -EFAULT; } else { transid = 0; /* current trans */ } return btrfs_wait_for_commit(root, transid); } static long btrfs_ioctl_scrub(struct file *file, void __user *arg) { struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root; struct btrfs_ioctl_scrub_args *sa; int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; sa = memdup_user(arg, sizeof(*sa)); if (IS_ERR(sa)) return PTR_ERR(sa); if (!(sa->flags & BTRFS_SCRUB_READONLY)) { ret = mnt_want_write_file(file); if (ret) goto out; } ret = btrfs_scrub_dev(root->fs_info, sa->devid, sa->start, sa->end, &sa->progress, sa->flags & BTRFS_SCRUB_READONLY, 0); if (copy_to_user(arg, sa, sizeof(*sa))) ret = -EFAULT; if (!(sa->flags & BTRFS_SCRUB_READONLY)) mnt_drop_write_file(file); out: kfree(sa); return ret; } static long btrfs_ioctl_scrub_cancel(struct btrfs_root *root, void __user *arg) { if (!capable(CAP_SYS_ADMIN)) return -EPERM; return btrfs_scrub_cancel(root->fs_info); } static long btrfs_ioctl_scrub_progress(struct btrfs_root *root, void __user *arg) { struct btrfs_ioctl_scrub_args *sa; int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; sa = memdup_user(arg, sizeof(*sa)); if (IS_ERR(sa)) return PTR_ERR(sa); ret = btrfs_scrub_progress(root, sa->devid, &sa->progress); if (copy_to_user(arg, sa, sizeof(*sa))) ret = -EFAULT; kfree(sa); return ret; } static long btrfs_ioctl_get_dev_stats(struct btrfs_root *root, void __user *arg) { struct btrfs_ioctl_get_dev_stats *sa; int ret; sa = memdup_user(arg, sizeof(*sa)); if (IS_ERR(sa)) return PTR_ERR(sa); if ((sa->flags & BTRFS_DEV_STATS_RESET) && !capable(CAP_SYS_ADMIN)) { kfree(sa); return -EPERM; } ret = btrfs_get_dev_stats(root, sa); if (copy_to_user(arg, sa, sizeof(*sa))) ret = -EFAULT; kfree(sa); return ret; } static long btrfs_ioctl_dev_replace(struct btrfs_root *root, void __user *arg) { struct btrfs_ioctl_dev_replace_args *p; int ret; if (!capable(CAP_SYS_ADMIN)) return -EPERM; p = memdup_user(arg, sizeof(*p)); if (IS_ERR(p)) return PTR_ERR(p); switch (p->cmd) { case BTRFS_IOCTL_DEV_REPLACE_CMD_START: if (atomic_xchg( &root->fs_info->mutually_exclusive_operation_running, 1)) { pr_info("btrfs: dev add/delete/balance/replace/resize operation in progress\n"); ret = -EINPROGRESS; } else { ret = btrfs_dev_replace_start(root, p); atomic_set( &root->fs_info->mutually_exclusive_operation_running, 0); } break; case BTRFS_IOCTL_DEV_REPLACE_CMD_STATUS: btrfs_dev_replace_status(root->fs_info, p); ret = 0; break; case BTRFS_IOCTL_DEV_REPLACE_CMD_CANCEL: ret = btrfs_dev_replace_cancel(root->fs_info, p); break; default: ret = -EINVAL; break; } if (copy_to_user(arg, p, sizeof(*p))) ret = -EFAULT; kfree(p); return ret; } static long btrfs_ioctl_ino_to_path(struct btrfs_root *root, void __user *arg) { int ret = 0; int i; u64 rel_ptr; int size; struct btrfs_ioctl_ino_path_args *ipa = NULL; struct inode_fs_paths *ipath = NULL; struct btrfs_path *path; if (!capable(CAP_SYS_ADMIN)) return -EPERM; path = btrfs_alloc_path(); if (!path) { ret = -ENOMEM; goto out; } ipa = memdup_user(arg, sizeof(*ipa)); if (IS_ERR(ipa)) { ret = PTR_ERR(ipa); ipa = NULL; goto out; } size = min_t(u32, ipa->size, 4096); ipath = init_ipath(size, root, path); if (IS_ERR(ipath)) { ret = PTR_ERR(ipath); ipath = NULL; goto out; } ret = paths_from_inode(ipa->inum, ipath); if (ret < 0) goto out; for (i = 0; i < ipath->fspath->elem_cnt; ++i) { rel_ptr = ipath->fspath->val[i] - (u64)(unsigned long)ipath->fspath->val; ipath->fspath->val[i] = rel_ptr; } ret = copy_to_user((void *)(unsigned long)ipa->fspath, (void *)(unsigned long)ipath->fspath, size); if (ret) { ret = -EFAULT; goto out; } out: btrfs_free_path(path); free_ipath(ipath); kfree(ipa); return ret; } static int build_ino_list(u64 inum, u64 offset, u64 root, void *ctx) { struct btrfs_data_container *inodes = ctx; const size_t c = 3 * sizeof(u64); if (inodes->bytes_left >= c) { inodes->bytes_left -= c; inodes->val[inodes->elem_cnt] = inum; inodes->val[inodes->elem_cnt + 1] = offset; inodes->val[inodes->elem_cnt + 2] = root; inodes->elem_cnt += 3; } else { inodes->bytes_missing += c - inodes->bytes_left; inodes->bytes_left = 0; inodes->elem_missed += 3; } return 0; } static long btrfs_ioctl_logical_to_ino(struct btrfs_root *root, void __user *arg) { int ret = 0; int size; struct btrfs_ioctl_logical_ino_args *loi; struct btrfs_data_container *inodes = NULL; struct btrfs_path *path = NULL; if (!capable(CAP_SYS_ADMIN)) return -EPERM; loi = memdup_user(arg, sizeof(*loi)); if (IS_ERR(loi)) { ret = PTR_ERR(loi); loi = NULL; goto out; } path = btrfs_alloc_path(); if (!path) { ret = -ENOMEM; goto out; } size = min_t(u32, loi->size, 64 * 1024); inodes = init_data_container(size); if (IS_ERR(inodes)) { ret = PTR_ERR(inodes); inodes = NULL; goto out; } ret = iterate_inodes_from_logical(loi->logical, root->fs_info, path, build_ino_list, inodes); if (ret == -EINVAL) ret = -ENOENT; if (ret < 0) goto out; ret = copy_to_user((void *)(unsigned long)loi->inodes, (void *)(unsigned long)inodes, size); if (ret) ret = -EFAULT; out: btrfs_free_path(path); vfree(inodes); kfree(loi); return ret; } void update_ioctl_balance_args(struct btrfs_fs_info *fs_info, int lock, struct btrfs_ioctl_balance_args *bargs) { struct btrfs_balance_control *bctl = fs_info->balance_ctl; bargs->flags = bctl->flags; if (atomic_read(&fs_info->balance_running)) bargs->state |= BTRFS_BALANCE_STATE_RUNNING; if (atomic_read(&fs_info->balance_pause_req)) bargs->state |= BTRFS_BALANCE_STATE_PAUSE_REQ; if (atomic_read(&fs_info->balance_cancel_req)) bargs->state |= BTRFS_BALANCE_STATE_CANCEL_REQ; memcpy(&bargs->data, &bctl->data, sizeof(bargs->data)); memcpy(&bargs->meta, &bctl->meta, sizeof(bargs->meta)); memcpy(&bargs->sys, &bctl->sys, sizeof(bargs->sys)); if (lock) { spin_lock(&fs_info->balance_lock); memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat)); spin_unlock(&fs_info->balance_lock); } else { memcpy(&bargs->stat, &bctl->stat, sizeof(bargs->stat)); } } static long btrfs_ioctl_balance(struct file *file, void __user *arg) { struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root; struct btrfs_fs_info *fs_info = root->fs_info; struct btrfs_ioctl_balance_args *bargs; struct btrfs_balance_control *bctl; int ret; int need_to_clear_lock = 0; if (!capable(CAP_SYS_ADMIN)) return -EPERM; ret = mnt_want_write_file(file); if (ret) return ret; mutex_lock(&fs_info->volume_mutex); mutex_lock(&fs_info->balance_mutex); if (arg) { bargs = memdup_user(arg, sizeof(*bargs)); if (IS_ERR(bargs)) { ret = PTR_ERR(bargs); goto out; } if (bargs->flags & BTRFS_BALANCE_RESUME) { if (!fs_info->balance_ctl) { ret = -ENOTCONN; goto out_bargs; } bctl = fs_info->balance_ctl; spin_lock(&fs_info->balance_lock); bctl->flags |= BTRFS_BALANCE_RESUME; spin_unlock(&fs_info->balance_lock); goto do_balance; } } else { bargs = NULL; } if (atomic_xchg(&root->fs_info->mutually_exclusive_operation_running, 1)) { pr_info("btrfs: dev add/delete/balance/replace/resize operation in progress\n"); ret = -EINPROGRESS; goto out_bargs; } need_to_clear_lock = 1; bctl = kzalloc(sizeof(*bctl), GFP_NOFS); if (!bctl) { ret = -ENOMEM; goto out_bargs; } bctl->fs_info = fs_info; if (arg) { memcpy(&bctl->data, &bargs->data, sizeof(bctl->data)); memcpy(&bctl->meta, &bargs->meta, sizeof(bctl->meta)); memcpy(&bctl->sys, &bargs->sys, sizeof(bctl->sys)); bctl->flags = bargs->flags; } else { /* balance everything - no filters */ bctl->flags |= BTRFS_BALANCE_TYPE_MASK; } do_balance: ret = btrfs_balance(bctl, bargs); /* * bctl is freed in __cancel_balance or in free_fs_info if * restriper was paused all the way until unmount */ if (arg) { if (copy_to_user(arg, bargs, sizeof(*bargs))) ret = -EFAULT; } out_bargs: kfree(bargs); out: if (need_to_clear_lock) atomic_set(&root->fs_info->mutually_exclusive_operation_running, 0); mutex_unlock(&fs_info->balance_mutex); mutex_unlock(&fs_info->volume_mutex); mnt_drop_write_file(file); return ret; } static long btrfs_ioctl_balance_ctl(struct btrfs_root *root, int cmd) { if (!capable(CAP_SYS_ADMIN)) return -EPERM; switch (cmd) { case BTRFS_BALANCE_CTL_PAUSE: return btrfs_pause_balance(root->fs_info); case BTRFS_BALANCE_CTL_CANCEL: return btrfs_cancel_balance(root->fs_info); } return -EINVAL; } static long btrfs_ioctl_balance_progress(struct btrfs_root *root, void __user *arg) { struct btrfs_fs_info *fs_info = root->fs_info; struct btrfs_ioctl_balance_args *bargs; int ret = 0; if (!capable(CAP_SYS_ADMIN)) return -EPERM; mutex_lock(&fs_info->balance_mutex); if (!fs_info->balance_ctl) { ret = -ENOTCONN; goto out; } bargs = kzalloc(sizeof(*bargs), GFP_NOFS); if (!bargs) { ret = -ENOMEM; goto out; } update_ioctl_balance_args(fs_info, 1, bargs); if (copy_to_user(arg, bargs, sizeof(*bargs))) ret = -EFAULT; kfree(bargs); out: mutex_unlock(&fs_info->balance_mutex); return ret; } static long btrfs_ioctl_quota_ctl(struct file *file, void __user *arg) { struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root; struct btrfs_ioctl_quota_ctl_args *sa; struct btrfs_trans_handle *trans = NULL; int ret; int err; if (!capable(CAP_SYS_ADMIN)) return -EPERM; ret = mnt_want_write_file(file); if (ret) return ret; sa = memdup_user(arg, sizeof(*sa)); if (IS_ERR(sa)) { ret = PTR_ERR(sa); goto drop_write; } if (sa->cmd != BTRFS_QUOTA_CTL_RESCAN) { trans = btrfs_start_transaction(root, 2); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out; } } switch (sa->cmd) { case BTRFS_QUOTA_CTL_ENABLE: ret = btrfs_quota_enable(trans, root->fs_info); break; case BTRFS_QUOTA_CTL_DISABLE: ret = btrfs_quota_disable(trans, root->fs_info); break; case BTRFS_QUOTA_CTL_RESCAN: ret = btrfs_quota_rescan(root->fs_info); break; default: ret = -EINVAL; break; } if (copy_to_user(arg, sa, sizeof(*sa))) ret = -EFAULT; if (trans) { err = btrfs_commit_transaction(trans, root); if (err && !ret) ret = err; } out: kfree(sa); drop_write: mnt_drop_write_file(file); return ret; } static long btrfs_ioctl_qgroup_assign(struct file *file, void __user *arg) { struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root; struct btrfs_ioctl_qgroup_assign_args *sa; struct btrfs_trans_handle *trans; int ret; int err; if (!capable(CAP_SYS_ADMIN)) return -EPERM; ret = mnt_want_write_file(file); if (ret) return ret; sa = memdup_user(arg, sizeof(*sa)); if (IS_ERR(sa)) { ret = PTR_ERR(sa); goto drop_write; } trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out; } /* FIXME: check if the IDs really exist */ if (sa->assign) { ret = btrfs_add_qgroup_relation(trans, root->fs_info, sa->src, sa->dst); } else { ret = btrfs_del_qgroup_relation(trans, root->fs_info, sa->src, sa->dst); } err = btrfs_end_transaction(trans, root); if (err && !ret) ret = err; out: kfree(sa); drop_write: mnt_drop_write_file(file); return ret; } static long btrfs_ioctl_qgroup_create(struct file *file, void __user *arg) { struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root; struct btrfs_ioctl_qgroup_create_args *sa; struct btrfs_trans_handle *trans; int ret; int err; if (!capable(CAP_SYS_ADMIN)) return -EPERM; ret = mnt_want_write_file(file); if (ret) return ret; sa = memdup_user(arg, sizeof(*sa)); if (IS_ERR(sa)) { ret = PTR_ERR(sa); goto drop_write; } trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out; } /* FIXME: check if the IDs really exist */ if (sa->create) { ret = btrfs_create_qgroup(trans, root->fs_info, sa->qgroupid, NULL); } else { ret = btrfs_remove_qgroup(trans, root->fs_info, sa->qgroupid); } err = btrfs_end_transaction(trans, root); if (err && !ret) ret = err; out: kfree(sa); drop_write: mnt_drop_write_file(file); return ret; } static long btrfs_ioctl_qgroup_limit(struct file *file, void __user *arg) { struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root; struct btrfs_ioctl_qgroup_limit_args *sa; struct btrfs_trans_handle *trans; int ret; int err; u64 qgroupid; if (!capable(CAP_SYS_ADMIN)) return -EPERM; ret = mnt_want_write_file(file); if (ret) return ret; sa = memdup_user(arg, sizeof(*sa)); if (IS_ERR(sa)) { ret = PTR_ERR(sa); goto drop_write; } trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out; } qgroupid = sa->qgroupid; if (!qgroupid) { /* take the current subvol as qgroup */ qgroupid = root->root_key.objectid; } /* FIXME: check if the IDs really exist */ ret = btrfs_limit_qgroup(trans, root->fs_info, qgroupid, &sa->lim); err = btrfs_end_transaction(trans, root); if (err && !ret) ret = err; out: kfree(sa); drop_write: mnt_drop_write_file(file); return ret; } static long btrfs_ioctl_set_received_subvol(struct file *file, void __user *arg) { struct btrfs_ioctl_received_subvol_args *sa = NULL; struct inode *inode = fdentry(file)->d_inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_root_item *root_item = &root->root_item; struct btrfs_trans_handle *trans; struct timespec ct = CURRENT_TIME; int ret = 0; ret = mnt_want_write_file(file); if (ret < 0) return ret; down_write(&root->fs_info->subvol_sem); if (btrfs_ino(inode) != BTRFS_FIRST_FREE_OBJECTID) { ret = -EINVAL; goto out; } if (btrfs_root_readonly(root)) { ret = -EROFS; goto out; } if (!inode_owner_or_capable(inode)) { ret = -EACCES; goto out; } sa = memdup_user(arg, sizeof(*sa)); if (IS_ERR(sa)) { ret = PTR_ERR(sa); sa = NULL; goto out; } trans = btrfs_start_transaction(root, 1); if (IS_ERR(trans)) { ret = PTR_ERR(trans); trans = NULL; goto out; } sa->rtransid = trans->transid; sa->rtime.sec = ct.tv_sec; sa->rtime.nsec = ct.tv_nsec; memcpy(root_item->received_uuid, sa->uuid, BTRFS_UUID_SIZE); btrfs_set_root_stransid(root_item, sa->stransid); btrfs_set_root_rtransid(root_item, sa->rtransid); root_item->stime.sec = cpu_to_le64(sa->stime.sec); root_item->stime.nsec = cpu_to_le32(sa->stime.nsec); root_item->rtime.sec = cpu_to_le64(sa->rtime.sec); root_item->rtime.nsec = cpu_to_le32(sa->rtime.nsec); ret = btrfs_update_root(trans, root->fs_info->tree_root, &root->root_key, &root->root_item); if (ret < 0) { btrfs_end_transaction(trans, root); trans = NULL; goto out; } else { ret = btrfs_commit_transaction(trans, root); if (ret < 0) goto out; } ret = copy_to_user(arg, sa, sizeof(*sa)); if (ret) ret = -EFAULT; out: kfree(sa); up_write(&root->fs_info->subvol_sem); mnt_drop_write_file(file); return ret; } long btrfs_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct btrfs_root *root = BTRFS_I(fdentry(file)->d_inode)->root; void __user *argp = (void __user *)arg; switch (cmd) { case FS_IOC_GETFLAGS: return btrfs_ioctl_getflags(file, argp); case FS_IOC_SETFLAGS: return btrfs_ioctl_setflags(file, argp); case FS_IOC_GETVERSION: return btrfs_ioctl_getversion(file, argp); case FITRIM: return btrfs_ioctl_fitrim(file, argp); case BTRFS_IOC_SNAP_CREATE: return btrfs_ioctl_snap_create(file, argp, 0); case BTRFS_IOC_SNAP_CREATE_V2: return btrfs_ioctl_snap_create_v2(file, argp, 0); case BTRFS_IOC_SUBVOL_CREATE: return btrfs_ioctl_snap_create(file, argp, 1); case BTRFS_IOC_SUBVOL_CREATE_V2: return btrfs_ioctl_snap_create_v2(file, argp, 1); case BTRFS_IOC_SNAP_DESTROY: return btrfs_ioctl_snap_destroy(file, argp); case BTRFS_IOC_SUBVOL_GETFLAGS: return btrfs_ioctl_subvol_getflags(file, argp); case BTRFS_IOC_SUBVOL_SETFLAGS: return btrfs_ioctl_subvol_setflags(file, argp); case BTRFS_IOC_DEFAULT_SUBVOL: return btrfs_ioctl_default_subvol(file, argp); case BTRFS_IOC_DEFRAG: return btrfs_ioctl_defrag(file, NULL); case BTRFS_IOC_DEFRAG_RANGE: return btrfs_ioctl_defrag(file, argp); case BTRFS_IOC_RESIZE: return btrfs_ioctl_resize(file, argp); case BTRFS_IOC_ADD_DEV: return btrfs_ioctl_add_dev(root, argp); case BTRFS_IOC_RM_DEV: return btrfs_ioctl_rm_dev(file, argp); case BTRFS_IOC_FS_INFO: return btrfs_ioctl_fs_info(root, argp); case BTRFS_IOC_DEV_INFO: return btrfs_ioctl_dev_info(root, argp); case BTRFS_IOC_BALANCE: return btrfs_ioctl_balance(file, NULL); case BTRFS_IOC_CLONE: return btrfs_ioctl_clone(file, arg, 0, 0, 0); case BTRFS_IOC_CLONE_RANGE: return btrfs_ioctl_clone_range(file, argp); case BTRFS_IOC_TRANS_START: return btrfs_ioctl_trans_start(file); case BTRFS_IOC_TRANS_END: return btrfs_ioctl_trans_end(file); case BTRFS_IOC_TREE_SEARCH: return btrfs_ioctl_tree_search(file, argp); case BTRFS_IOC_INO_LOOKUP: return btrfs_ioctl_ino_lookup(file, argp); case BTRFS_IOC_INO_PATHS: return btrfs_ioctl_ino_to_path(root, argp); case BTRFS_IOC_LOGICAL_INO: return btrfs_ioctl_logical_to_ino(root, argp); case BTRFS_IOC_SPACE_INFO: return btrfs_ioctl_space_info(root, argp); case BTRFS_IOC_SYNC: btrfs_sync_fs(file->f_dentry->d_sb, 1); return 0; case BTRFS_IOC_START_SYNC: return btrfs_ioctl_start_sync(root, argp); case BTRFS_IOC_WAIT_SYNC: return btrfs_ioctl_wait_sync(root, argp); case BTRFS_IOC_SCRUB: return btrfs_ioctl_scrub(file, argp); case BTRFS_IOC_SCRUB_CANCEL: return btrfs_ioctl_scrub_cancel(root, argp); case BTRFS_IOC_SCRUB_PROGRESS: return btrfs_ioctl_scrub_progress(root, argp); case BTRFS_IOC_BALANCE_V2: return btrfs_ioctl_balance(file, argp); case BTRFS_IOC_BALANCE_CTL: return btrfs_ioctl_balance_ctl(root, arg); case BTRFS_IOC_BALANCE_PROGRESS: return btrfs_ioctl_balance_progress(root, argp); case BTRFS_IOC_SET_RECEIVED_SUBVOL: return btrfs_ioctl_set_received_subvol(file, argp); case BTRFS_IOC_SEND: return btrfs_ioctl_send(file, argp); case BTRFS_IOC_GET_DEV_STATS: return btrfs_ioctl_get_dev_stats(root, argp); case BTRFS_IOC_QUOTA_CTL: return btrfs_ioctl_quota_ctl(file, argp); case BTRFS_IOC_QGROUP_ASSIGN: return btrfs_ioctl_qgroup_assign(file, argp); case BTRFS_IOC_QGROUP_CREATE: return btrfs_ioctl_qgroup_create(file, argp); case BTRFS_IOC_QGROUP_LIMIT: return btrfs_ioctl_qgroup_limit(file, argp); case BTRFS_IOC_DEV_REPLACE: return btrfs_ioctl_dev_replace(root, argp); } return -ENOTTY; }
./CrossVul/dataset_final_sorted/CWE-310/c/good_3783_3
crossvul-cpp_data_bad_1445_4
/* ssl/s3_clnt.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ /* ==================================================================== * Copyright (c) 1998-2007 The OpenSSL 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: * * 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. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* ==================================================================== * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * * Portions of the attached software ("Contribution") are developed by * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project. * * The Contribution is licensed pursuant to the OpenSSL open source * license provided above. * * ECC cipher suite support in OpenSSL originally written by * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories. * */ /* ==================================================================== * Copyright 2005 Nokia. All rights reserved. * * The portions of the attached software ("Contribution") is developed by * Nokia Corporation and is licensed pursuant to the OpenSSL open source * license. * * The Contribution, originally written by Mika Kousa and Pasi Eronen of * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites * support (see RFC 4279) to OpenSSL. * * No patent licenses or other rights except those expressly stated in * the OpenSSL open source license shall be deemed granted or received * expressly, by implication, estoppel, or otherwise. * * No assurances are provided by Nokia that the Contribution does not * infringe the patent or other intellectual property rights of any third * party or that the license provides you with all the necessary rights * to make use of the Contribution. * * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR * OTHERWISE. */ #include <stdio.h> #include "ssl_locl.h" #include "kssl_lcl.h" #include <openssl/buffer.h> #include <openssl/rand.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/md5.h> #ifndef OPENSSL_NO_DH #include <openssl/dh.h> #endif #include <openssl/bn.h> #ifndef OPENSSL_NO_ENGINE #include <openssl/engine.h> #endif static int ca_dn_cmp(const X509_NAME * const *a,const X509_NAME * const *b); #ifndef OPENSSL_NO_SSL3_METHOD static const SSL_METHOD *ssl3_get_client_method(int ver) { if (ver == SSL3_VERSION) return(SSLv3_client_method()); else return(NULL); } IMPLEMENT_ssl3_meth_func(SSLv3_client_method, ssl_undefined_function, ssl3_connect, ssl3_get_client_method) #endif int ssl3_connect(SSL *s) { BUF_MEM *buf=NULL; unsigned long Time=(unsigned long)time(NULL); void (*cb)(const SSL *ssl,int type,int val)=NULL; int ret= -1; int new_state,state,skip=0; RAND_add(&Time,sizeof(Time),0); ERR_clear_error(); clear_sys_error(); if (s->info_callback != NULL) cb=s->info_callback; else if (s->ctx->info_callback != NULL) cb=s->ctx->info_callback; s->in_handshake++; if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); #ifndef OPENSSL_NO_HEARTBEATS /* If we're awaiting a HeartbeatResponse, pretend we * already got and don't await it anymore, because * Heartbeats don't make sense during handshakes anyway. */ if (s->tlsext_hb_pending) { s->tlsext_hb_pending = 0; s->tlsext_hb_seq++; } #endif for (;;) { state=s->state; switch(s->state) { case SSL_ST_RENEGOTIATE: s->renegotiate=1; s->state=SSL_ST_CONNECT; s->ctx->stats.sess_connect_renegotiate++; /* break */ case SSL_ST_BEFORE: case SSL_ST_CONNECT: case SSL_ST_BEFORE|SSL_ST_CONNECT: case SSL_ST_OK|SSL_ST_CONNECT: s->server=0; if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1); if ((s->version & 0xff00 ) != 0x0300) { SSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR); ret = -1; goto end; } if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) { SSLerr(SSL_F_SSL3_CONNECT, SSL_R_VERSION_TOO_LOW); return -1; } /* s->version=SSL3_VERSION; */ s->type=SSL_ST_CONNECT; if (s->init_buf == NULL) { if ((buf=BUF_MEM_new()) == NULL) { ret= -1; goto end; } if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH)) { ret= -1; goto end; } s->init_buf=buf; buf=NULL; } if (!ssl3_setup_buffers(s)) { ret= -1; goto end; } /* setup buffing BIO */ if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; } /* don't push the buffering BIO quite yet */ ssl3_init_finished_mac(s); s->state=SSL3_ST_CW_CLNT_HELLO_A; s->ctx->stats.sess_connect++; s->init_num=0; s->s3->flags &= ~SSL3_FLAGS_CCS_OK; /* Should have been reset by ssl3_get_finished, too. */ s->s3->change_cipher_spec = 0; break; case SSL3_ST_CW_CLNT_HELLO_A: case SSL3_ST_CW_CLNT_HELLO_B: s->shutdown=0; ret=ssl3_client_hello(s); if (ret <= 0) goto end; s->state=SSL3_ST_CR_SRVR_HELLO_A; s->init_num=0; /* turn on buffering for the next lot of output */ if (s->bbio != s->wbio) s->wbio=BIO_push(s->bbio,s->wbio); break; case SSL3_ST_CR_SRVR_HELLO_A: case SSL3_ST_CR_SRVR_HELLO_B: ret=ssl3_get_server_hello(s); if (ret <= 0) goto end; if (s->hit) { s->state=SSL3_ST_CR_FINISHED_A; #ifndef OPENSSL_NO_TLSEXT if (s->tlsext_ticket_expected) { /* receive renewed session ticket */ s->state=SSL3_ST_CR_SESSION_TICKET_A; } #endif } else { s->state=SSL3_ST_CR_CERT_A; } s->init_num=0; break; case SSL3_ST_CR_CERT_A: case SSL3_ST_CR_CERT_B: /* Check if it is anon DH/ECDH, SRP auth */ /* or PSK */ if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP)) && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { ret=ssl3_get_server_certificate(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_TLSEXT if (s->tlsext_status_expected) s->state=SSL3_ST_CR_CERT_STATUS_A; else s->state=SSL3_ST_CR_KEY_EXCH_A; } else { skip = 1; s->state=SSL3_ST_CR_KEY_EXCH_A; } #else } else skip=1; s->state=SSL3_ST_CR_KEY_EXCH_A; #endif s->init_num=0; break; case SSL3_ST_CR_KEY_EXCH_A: case SSL3_ST_CR_KEY_EXCH_B: ret=ssl3_get_key_exchange(s); if (ret <= 0) goto end; s->state=SSL3_ST_CR_CERT_REQ_A; s->init_num=0; /* at this point we check that we have the * required stuff from the server */ if (!ssl3_check_cert_and_algorithm(s)) { ret= -1; goto end; } break; case SSL3_ST_CR_CERT_REQ_A: case SSL3_ST_CR_CERT_REQ_B: ret=ssl3_get_certificate_request(s); if (ret <= 0) goto end; s->state=SSL3_ST_CR_SRVR_DONE_A; s->init_num=0; break; case SSL3_ST_CR_SRVR_DONE_A: case SSL3_ST_CR_SRVR_DONE_B: ret=ssl3_get_server_done(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_SRP if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) { if ((ret = SRP_Calc_A_param(s))<=0) { SSLerr(SSL_F_SSL3_CONNECT,SSL_R_SRP_A_CALC); ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR); goto end; } } #endif if (s->s3->tmp.cert_req) s->state=SSL3_ST_CW_CERT_A; else s->state=SSL3_ST_CW_KEY_EXCH_A; s->init_num=0; break; case SSL3_ST_CW_CERT_A: case SSL3_ST_CW_CERT_B: case SSL3_ST_CW_CERT_C: case SSL3_ST_CW_CERT_D: ret=ssl3_send_client_certificate(s); if (ret <= 0) goto end; s->state=SSL3_ST_CW_KEY_EXCH_A; s->init_num=0; break; case SSL3_ST_CW_KEY_EXCH_A: case SSL3_ST_CW_KEY_EXCH_B: ret=ssl3_send_client_key_exchange(s); if (ret <= 0) goto end; /* EAY EAY EAY need to check for DH fix cert * sent back */ /* For TLS, cert_req is set to 2, so a cert chain * of nothing is sent, but no verify packet is sent */ /* XXX: For now, we do not support client * authentication in ECDH cipher suites with * ECDH (rather than ECDSA) certificates. * We need to skip the certificate verify * message when client's ECDH public key is sent * inside the client certificate. */ if (s->s3->tmp.cert_req == 1) { s->state=SSL3_ST_CW_CERT_VRFY_A; } else { s->state=SSL3_ST_CW_CHANGE_A; } if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) { s->state=SSL3_ST_CW_CHANGE_A; } s->init_num=0; break; case SSL3_ST_CW_CERT_VRFY_A: case SSL3_ST_CW_CERT_VRFY_B: ret=ssl3_send_client_verify(s); if (ret <= 0) goto end; s->state=SSL3_ST_CW_CHANGE_A; s->init_num=0; break; case SSL3_ST_CW_CHANGE_A: case SSL3_ST_CW_CHANGE_B: ret=ssl3_send_change_cipher_spec(s, SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B); if (ret <= 0) goto end; #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) s->state=SSL3_ST_CW_FINISHED_A; #else if (s->s3->next_proto_neg_seen) s->state=SSL3_ST_CW_NEXT_PROTO_A; else s->state=SSL3_ST_CW_FINISHED_A; #endif s->init_num=0; s->session->cipher=s->s3->tmp.new_cipher; #ifdef OPENSSL_NO_COMP s->session->compress_meth=0; #else if (s->s3->tmp.new_compression == NULL) s->session->compress_meth=0; else s->session->compress_meth= s->s3->tmp.new_compression->id; #endif if (!s->method->ssl3_enc->setup_key_block(s)) { ret= -1; goto end; } if (!s->method->ssl3_enc->change_cipher_state(s, SSL3_CHANGE_CIPHER_CLIENT_WRITE)) { ret= -1; goto end; } break; #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) case SSL3_ST_CW_NEXT_PROTO_A: case SSL3_ST_CW_NEXT_PROTO_B: ret=ssl3_send_next_proto(s); if (ret <= 0) goto end; s->state=SSL3_ST_CW_FINISHED_A; break; #endif case SSL3_ST_CW_FINISHED_A: case SSL3_ST_CW_FINISHED_B: ret=ssl3_send_finished(s, SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B, s->method->ssl3_enc->client_finished_label, s->method->ssl3_enc->client_finished_label_len); if (ret <= 0) goto end; s->state=SSL3_ST_CW_FLUSH; /* clear flags */ s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER; if (s->hit) { s->s3->tmp.next_state=SSL_ST_OK; if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED) { s->state=SSL_ST_OK; s->s3->flags|=SSL3_FLAGS_POP_BUFFER; s->s3->delay_buf_pop_ret=0; } } else { #ifndef OPENSSL_NO_TLSEXT /* Allow NewSessionTicket if ticket expected */ if (s->tlsext_ticket_expected) s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A; else #endif s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A; } s->init_num=0; break; #ifndef OPENSSL_NO_TLSEXT case SSL3_ST_CR_SESSION_TICKET_A: case SSL3_ST_CR_SESSION_TICKET_B: ret=ssl3_get_new_session_ticket(s); if (ret <= 0) goto end; s->state=SSL3_ST_CR_FINISHED_A; s->init_num=0; break; case SSL3_ST_CR_CERT_STATUS_A: case SSL3_ST_CR_CERT_STATUS_B: ret=ssl3_get_cert_status(s); if (ret <= 0) goto end; s->state=SSL3_ST_CR_KEY_EXCH_A; s->init_num=0; break; #endif case SSL3_ST_CR_FINISHED_A: case SSL3_ST_CR_FINISHED_B: s->s3->flags |= SSL3_FLAGS_CCS_OK; ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A, SSL3_ST_CR_FINISHED_B); if (ret <= 0) goto end; if (s->hit) s->state=SSL3_ST_CW_CHANGE_A; else s->state=SSL_ST_OK; s->init_num=0; break; case SSL3_ST_CW_FLUSH: s->rwstate=SSL_WRITING; if (BIO_flush(s->wbio) <= 0) { ret= -1; goto end; } s->rwstate=SSL_NOTHING; s->state=s->s3->tmp.next_state; break; case SSL_ST_OK: /* clean a few things up */ ssl3_cleanup_key_block(s); if (s->init_buf != NULL) { BUF_MEM_free(s->init_buf); s->init_buf=NULL; } /* If we are not 'joining' the last two packets, * remove the buffering now */ if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER)) ssl_free_wbio_buffer(s); /* else do it later in ssl3_write */ s->init_num=0; s->renegotiate=0; s->new_session=0; ssl_update_cache(s,SSL_SESS_CACHE_CLIENT); if (s->hit) s->ctx->stats.sess_hit++; ret=1; /* s->server=0; */ s->handshake_func=ssl3_connect; s->ctx->stats.sess_connect_good++; if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1); goto end; /* break; */ default: SSLerr(SSL_F_SSL3_CONNECT,SSL_R_UNKNOWN_STATE); ret= -1; goto end; /* break; */ } /* did we do anything */ if (!s->s3->tmp.reuse_message && !skip) { if (s->debug) { if ((ret=BIO_flush(s->wbio)) <= 0) goto end; } if ((cb != NULL) && (s->state != state)) { new_state=s->state; s->state=state; cb(s,SSL_CB_CONNECT_LOOP,1); s->state=new_state; } } skip=0; } end: s->in_handshake--; if (buf != NULL) BUF_MEM_free(buf); if (cb != NULL) cb(s,SSL_CB_CONNECT_EXIT,ret); return(ret); } int ssl3_client_hello(SSL *s) { unsigned char *buf; unsigned char *p,*d; int i; unsigned long l; int al = 0; #ifndef OPENSSL_NO_COMP int j; SSL_COMP *comp; #endif buf=(unsigned char *)s->init_buf->data; if (s->state == SSL3_ST_CW_CLNT_HELLO_A) { SSL_SESSION *sess = s->session; if ((sess == NULL) || (sess->ssl_version != s->version) || !sess->session_id_length || (sess->not_resumable)) { if (!ssl_get_new_session(s,0)) goto err; } if (s->method->version == DTLS_ANY_VERSION) { /* Determine which DTLS version to use */ int options = s->options; /* If DTLS 1.2 disabled correct the version number */ if (options & SSL_OP_NO_DTLSv1_2) { if (tls1_suiteb(s)) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE); goto err; } /* Disabling all versions is silly: return an * error. */ if (options & SSL_OP_NO_DTLSv1) { SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_WRONG_SSL_VERSION); goto err; } /* Update method so we don't use any DTLS 1.2 * features. */ s->method = DTLSv1_client_method(); s->version = DTLS1_VERSION; } else { /* We only support one version: update method */ if (options & SSL_OP_NO_DTLSv1) s->method = DTLSv1_2_client_method(); s->version = DTLS1_2_VERSION; } s->client_version = s->version; } /* else use the pre-loaded session */ p=s->s3->client_random; /* for DTLS if client_random is initialized, reuse it, we are * required to use same upon reply to HelloVerify */ if (SSL_IS_DTLS(s)) { size_t idx; i = 1; for (idx=0; idx < sizeof(s->s3->client_random); idx++) { if (p[idx]) { i = 0; break; } } } else i = 1; if (i) ssl_fill_hello_random(s, 0, p, sizeof(s->s3->client_random)); /* Do the message type and length last */ d=p= ssl_handshake_start(s); /*- * version indicates the negotiated version: for example from * an SSLv2/v3 compatible client hello). The client_version * field is the maximum version we permit and it is also * used in RSA encrypted premaster secrets. Some servers can * choke if we initially report a higher version then * renegotiate to a lower one in the premaster secret. This * didn't happen with TLS 1.0 as most servers supported it * but it can with TLS 1.1 or later if the server only supports * 1.0. * * Possible scenario with previous logic: * 1. Client hello indicates TLS 1.2 * 2. Server hello says TLS 1.0 * 3. RSA encrypted premaster secret uses 1.2. * 4. Handhaked proceeds using TLS 1.0. * 5. Server sends hello request to renegotiate. * 6. Client hello indicates TLS v1.0 as we now * know that is maximum server supports. * 7. Server chokes on RSA encrypted premaster secret * containing version 1.0. * * For interoperability it should be OK to always use the * maximum version we support in client hello and then rely * on the checking of version to ensure the servers isn't * being inconsistent: for example initially negotiating with * TLS 1.0 and renegotiating with TLS 1.2. We do this by using * client_version in client hello and not resetting it to * the negotiated version. */ #if 0 *(p++)=s->version>>8; *(p++)=s->version&0xff; s->client_version=s->version; #else *(p++)=s->client_version>>8; *(p++)=s->client_version&0xff; #endif /* Random stuff */ memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE); p+=SSL3_RANDOM_SIZE; /* Session ID */ if (s->new_session) i=0; else i=s->session->session_id_length; *(p++)=i; if (i != 0) { if (i > (int)sizeof(s->session->session_id)) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } memcpy(p,s->session->session_id,i); p+=i; } /* cookie stuff for DTLS */ if (SSL_IS_DTLS(s)) { if ( s->d1->cookie_len > sizeof(s->d1->cookie)) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } *(p++) = s->d1->cookie_len; memcpy(p, s->d1->cookie, s->d1->cookie_len); p += s->d1->cookie_len; } /* Ciphers supported */ i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0); if (i == 0) { SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE); goto err; } #ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH /* Some servers hang if client hello > 256 bytes * as hack workaround chop number of supported ciphers * to keep it well below this if we use TLS v1.2 */ if (TLS1_get_version(s) >= TLS1_2_VERSION && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH) i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1; #endif s2n(i,p); p+=i; /* COMPRESSION */ #ifdef OPENSSL_NO_COMP *(p++)=1; #else if (!ssl_allow_compression(s) || !s->ctx->comp_methods) j=0; else j=sk_SSL_COMP_num(s->ctx->comp_methods); *(p++)=1+j; for (i=0; i<j; i++) { comp=sk_SSL_COMP_value(s->ctx->comp_methods,i); *(p++)=comp->id; } #endif *(p++)=0; /* Add the NULL method */ #ifndef OPENSSL_NO_TLSEXT /* TLS extensions*/ if (ssl_prepare_clienthello_tlsext(s) <= 0) { SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT); goto err; } if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH, &al)) == NULL) { ssl3_send_alert(s,SSL3_AL_FATAL,al); SSLerr(SSL_F_SSL3_CLIENT_HELLO,ERR_R_INTERNAL_ERROR); goto err; } #endif l= p-d; ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l); s->state=SSL3_ST_CW_CLNT_HELLO_B; } /* SSL3_ST_CW_CLNT_HELLO_B */ return ssl_do_write(s); err: return(-1); } int ssl3_get_server_hello(SSL *s) { STACK_OF(SSL_CIPHER) *sk; const SSL_CIPHER *c; CERT *ct = s->cert; unsigned char *p,*d; int i,al=SSL_AD_INTERNAL_ERROR,ok; unsigned int j; long n; #ifndef OPENSSL_NO_COMP SSL_COMP *comp; #endif /* Hello verify request and/or server hello version may not * match so set first packet if we're negotiating version. */ if (SSL_IS_DTLS(s)) s->first_packet = 1; n=s->method->ssl_get_message(s, SSL3_ST_CR_SRVR_HELLO_A, SSL3_ST_CR_SRVR_HELLO_B, -1, 20000, /* ?? */ &ok); if (!ok) return((int)n); if (SSL_IS_DTLS(s)) { s->first_packet = 0; if ( s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST) { if ( s->d1->send_cookie == 0) { s->s3->tmp.reuse_message = 1; return 1; } else /* already sent a cookie */ { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } } } if ( s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } d=p=(unsigned char *)s->init_msg; if (s->method->version == DTLS_ANY_VERSION) { /* Work out correct protocol version to use */ int hversion = (p[0] << 8)|p[1]; int options = s->options; if (hversion == DTLS1_2_VERSION && !(options & SSL_OP_NO_DTLSv1_2)) s->method = DTLSv1_2_client_method(); else if (tls1_suiteb(s)) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE); s->version = hversion; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } else if (hversion == DTLS1_VERSION && !(options & SSL_OP_NO_DTLSv1)) s->method = DTLSv1_client_method(); else { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION); s->version = hversion; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } s->version = s->method->version; } if ((p[0] != (s->version>>8)) || (p[1] != (s->version&0xff))) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION); s->version=(s->version&0xff00)|p[1]; al=SSL_AD_PROTOCOL_VERSION; goto f_err; } p+=2; /* load the server hello data */ /* load the server random */ memcpy(s->s3->server_random,p,SSL3_RANDOM_SIZE); p+=SSL3_RANDOM_SIZE; s->hit = 0; /* get the session-id */ j= *(p++); if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SSL3_SESSION_ID_TOO_LONG); goto f_err; } #ifndef OPENSSL_NO_TLSEXT /* check if we want to resume the session based on external pre-shared secret */ if (s->version >= TLS1_VERSION && s->tls_session_secret_cb) { SSL_CIPHER *pref_cipher=NULL; s->session->master_key_length=sizeof(s->session->master_key); if (s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length, NULL, &pref_cipher, s->tls_session_secret_cb_arg)) { s->session->cipher = pref_cipher ? pref_cipher : ssl_get_cipher_by_char(s, p+j); s->hit = 1; } } #endif /* OPENSSL_NO_TLSEXT */ if (!s->hit && j != 0 && j == s->session->session_id_length && memcmp(p,s->session->session_id,j) == 0) { if(s->sid_ctx_length != s->session->sid_ctx_length || memcmp(s->session->sid_ctx,s->sid_ctx,s->sid_ctx_length)) { /* actually a client application bug */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT); goto f_err; } s->hit=1; } /* a miss or crap from the other end */ if (!s->hit) { /* If we were trying for session-id reuse, make a new * SSL_SESSION so we don't stuff up other people */ if (s->session->session_id_length > 0) { if (!ssl_get_new_session(s,0)) { goto f_err; } } s->session->session_id_length=j; memcpy(s->session->session_id,p,j); /* j could be 0 */ } p+=j; c=ssl_get_cipher_by_char(s,p); if (c == NULL) { /* unknown cipher */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNKNOWN_CIPHER_RETURNED); goto f_err; } /* Set version disabled mask now we know version */ if (!SSL_USE_TLS1_2_CIPHERS(s)) ct->mask_ssl = SSL_TLSV1_2; else ct->mask_ssl = 0; /* If it is a disabled cipher we didn't send it in client hello, * so return an error. */ if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_CHECK)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED); goto f_err; } p+=ssl_put_cipher_by_char(s,NULL,NULL); sk=ssl_get_ciphers_by_id(s); i=sk_SSL_CIPHER_find(sk,c); if (i < 0) { /* we did not say we would use this cipher */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED); goto f_err; } /* Depending on the session caching (internal/external), the cipher and/or cipher_id values may not be set. Make sure that cipher_id is set and use it for comparison. */ if (s->session->cipher) s->session->cipher_id = s->session->cipher->id; if (s->hit && (s->session->cipher_id != c->id)) { /* Workaround is now obsolete */ #if 0 if (!(s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)) #endif { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED); goto f_err; } } s->s3->tmp.new_cipher=c; /* Don't digest cached records if no sigalgs: we may need them for * client authentication. */ if (!SSL_USE_SIGALGS(s) && !ssl3_digest_cached_records(s)) goto f_err; /* lets get the compression algorithm */ /* COMPRESSION */ #ifdef OPENSSL_NO_COMP if (*(p++) != 0) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM); goto f_err; } /* If compression is disabled we'd better not try to resume a session * using compression. */ if (s->session->compress_meth != 0) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } #else j= *(p++); if (s->hit && j != s->session->compress_meth) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED); goto f_err; } if (j == 0) comp=NULL; else if (!ssl_allow_compression(s)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_COMPRESSION_DISABLED); goto f_err; } else comp=ssl3_comp_find(s->ctx->comp_methods,j); if ((j != 0) && (comp == NULL)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM); goto f_err; } else { s->s3->tmp.new_compression=comp; } #endif #ifndef OPENSSL_NO_TLSEXT /* TLS extensions*/ if (!ssl_parse_serverhello_tlsext(s,&p,d,n)) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_PARSE_TLSEXT); goto err; } #endif if (p != (d+n)) { /* wrong packet length */ al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_PACKET_LENGTH); goto f_err; } return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(-1); } int ssl3_get_server_certificate(SSL *s) { int al,i,ok,ret= -1; unsigned long n,nc,llen,l; X509 *x=NULL; const unsigned char *q,*p; unsigned char *d; STACK_OF(X509) *sk=NULL; SESS_CERT *sc; EVP_PKEY *pkey=NULL; int need_cert = 1; /* VRS: 0=> will allow null cert if auth == KRB5 */ n=s->method->ssl_get_message(s, SSL3_ST_CR_CERT_A, SSL3_ST_CR_CERT_B, -1, s->max_cert_list, &ok); if (!ok) return((int)n); if ((s->s3->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) || ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) && (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE))) { s->s3->tmp.reuse_message=1; return(1); } if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } p=d=(unsigned char *)s->init_msg; if ((sk=sk_X509_new_null()) == NULL) { SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE); goto err; } n2l3(p,llen); if (llen+3 != n) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_LENGTH_MISMATCH); goto f_err; } for (nc=0; nc<llen; ) { n2l3(p,l); if ((l+nc+3) > llen) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH); goto f_err; } q=p; x=d2i_X509(NULL,&q,l); if (x == NULL) { al=SSL_AD_BAD_CERTIFICATE; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_ASN1_LIB); goto f_err; } if (q != (p+l)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH); goto f_err; } if (!sk_X509_push(sk,x)) { SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE); goto err; } x=NULL; nc+=l+3; p=q; } i=ssl_verify_cert_chain(s,sk); if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0) #ifndef OPENSSL_NO_KRB5 && !((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) && (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5)) #endif /* OPENSSL_NO_KRB5 */ ) { al=ssl_verify_alarm_type(s->verify_result); SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED); goto f_err; } ERR_clear_error(); /* but we keep s->verify_result */ if (i > 1) { SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, i); al = SSL_AD_HANDSHAKE_FAILURE; goto f_err; } sc=ssl_sess_cert_new(); if (sc == NULL) goto err; if (s->session->sess_cert) ssl_sess_cert_free(s->session->sess_cert); s->session->sess_cert=sc; sc->cert_chain=sk; /* Inconsistency alert: cert_chain does include the peer's * certificate, which we don't include in s3_srvr.c */ x=sk_X509_value(sk,0); sk=NULL; /* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/ pkey=X509_get_pubkey(x); /* VRS: allow null cert if auth == KRB5 */ need_cert = ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) && (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5)) ? 0 : 1; #ifdef KSSL_DEBUG fprintf(stderr,"pkey,x = %p, %p\n", pkey,x); fprintf(stderr,"ssl_cert_type(x,pkey) = %d\n", ssl_cert_type(x,pkey)); fprintf(stderr,"cipher, alg, nc = %s, %lx, %lx, %d\n", s->s3->tmp.new_cipher->name, s->s3->tmp.new_cipher->algorithm_mkey, s->s3->tmp.new_cipher->algorithm_auth, need_cert); #endif /* KSSL_DEBUG */ if (need_cert && ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey))) { x=NULL; al=SSL3_AL_FATAL; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS); goto f_err; } i=ssl_cert_type(x,pkey); if (need_cert && i < 0) { x=NULL; al=SSL3_AL_FATAL; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_UNKNOWN_CERTIFICATE_TYPE); goto f_err; } if (need_cert) { int exp_idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher); if (exp_idx >= 0 && i != exp_idx) { x=NULL; al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_WRONG_CERTIFICATE_TYPE); goto f_err; } sc->peer_cert_type=i; CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509); /* Why would the following ever happen? * We just created sc a couple of lines ago. */ if (sc->peer_pkeys[i].x509 != NULL) X509_free(sc->peer_pkeys[i].x509); sc->peer_pkeys[i].x509=x; sc->peer_key= &(sc->peer_pkeys[i]); if (s->session->peer != NULL) X509_free(s->session->peer); CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509); s->session->peer=x; } else { sc->peer_cert_type=i; sc->peer_key= NULL; if (s->session->peer != NULL) X509_free(s->session->peer); s->session->peer=NULL; } s->session->verify_result = s->verify_result; x=NULL; ret=1; if (0) { f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); } err: EVP_PKEY_free(pkey); X509_free(x); sk_X509_pop_free(sk,X509_free); return(ret); } int ssl3_get_key_exchange(SSL *s) { #ifndef OPENSSL_NO_RSA unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2]; #endif EVP_MD_CTX md_ctx; unsigned char *param,*p; int al,j,ok; long i,param_len,n,alg_k,alg_a; EVP_PKEY *pkey=NULL; const EVP_MD *md = NULL; #ifndef OPENSSL_NO_RSA RSA *rsa=NULL; #endif #ifndef OPENSSL_NO_DH DH *dh=NULL; #endif #ifndef OPENSSL_NO_ECDH EC_KEY *ecdh = NULL; BN_CTX *bn_ctx = NULL; EC_POINT *srvr_ecpoint = NULL; int curve_nid = 0; int encoded_pt_len = 0; #endif EVP_MD_CTX_init(&md_ctx); /* use same message size as in ssl3_get_certificate_request() * as ServerKeyExchange message may be skipped */ n=s->method->ssl_get_message(s, SSL3_ST_CR_KEY_EXCH_A, SSL3_ST_CR_KEY_EXCH_B, -1, s->max_cert_list, &ok); if (!ok) return((int)n); alg_k=s->s3->tmp.new_cipher->algorithm_mkey; if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) { /* * Can't skip server key exchange if this is an ephemeral * ciphersuite. */ if (alg_k & (SSL_kDHE|SSL_kECDHE)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE); al = SSL_AD_UNEXPECTED_MESSAGE; goto f_err; } #ifndef OPENSSL_NO_PSK /* In plain PSK ciphersuite, ServerKeyExchange can be omitted if no identity hint is sent. Set session->sess_cert anyway to avoid problems later.*/ if (alg_k & SSL_kPSK) { s->session->sess_cert=ssl_sess_cert_new(); if (s->ctx->psk_identity_hint) OPENSSL_free(s->ctx->psk_identity_hint); s->ctx->psk_identity_hint = NULL; } #endif s->s3->tmp.reuse_message=1; return(1); } param=p=(unsigned char *)s->init_msg; if (s->session->sess_cert != NULL) { #ifndef OPENSSL_NO_RSA if (s->session->sess_cert->peer_rsa_tmp != NULL) { RSA_free(s->session->sess_cert->peer_rsa_tmp); s->session->sess_cert->peer_rsa_tmp=NULL; } #endif #ifndef OPENSSL_NO_DH if (s->session->sess_cert->peer_dh_tmp) { DH_free(s->session->sess_cert->peer_dh_tmp); s->session->sess_cert->peer_dh_tmp=NULL; } #endif #ifndef OPENSSL_NO_ECDH if (s->session->sess_cert->peer_ecdh_tmp) { EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp); s->session->sess_cert->peer_ecdh_tmp=NULL; } #endif } else { s->session->sess_cert=ssl_sess_cert_new(); } /* Total length of the parameters including the length prefix */ param_len=0; alg_a=s->s3->tmp.new_cipher->algorithm_auth; al=SSL_AD_DECODE_ERROR; #ifndef OPENSSL_NO_PSK if (alg_k & SSL_kPSK) { char tmp_id_hint[PSK_MAX_IDENTITY_LEN+1]; param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); /* Store PSK identity hint for later use, hint is used * in ssl3_send_client_key_exchange. Assume that the * maximum length of a PSK identity hint can be as * long as the maximum length of a PSK identity. */ if (i > PSK_MAX_IDENTITY_LEN) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH); goto f_err; } param_len += i; /* If received PSK identity hint contains NULL * characters, the hint is truncated from the first * NULL. p may not be ending with NULL, so create a * NULL-terminated string. */ memcpy(tmp_id_hint, p, i); memset(tmp_id_hint+i, 0, PSK_MAX_IDENTITY_LEN+1-i); if (s->ctx->psk_identity_hint != NULL) OPENSSL_free(s->ctx->psk_identity_hint); s->ctx->psk_identity_hint = BUF_strdup(tmp_id_hint); if (s->ctx->psk_identity_hint == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto f_err; } p+=i; n-=param_len; } else #endif /* !OPENSSL_NO_PSK */ #ifndef OPENSSL_NO_SRP if (alg_k & SSL_kSRP) { param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_N_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.N=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_G_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.g=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (1 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 1; i = (unsigned int)(p[0]); p++; if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_S_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.s=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_B_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.B=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; if (!srp_verify_server_param(s, &al)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS); goto f_err; } /* We must check if there is a certificate */ #ifndef OPENSSL_NO_RSA if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #else if (0) ; #endif #ifndef OPENSSL_NO_DSA else if (alg_a & SSL_aDSS) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509); #endif } else #endif /* !OPENSSL_NO_SRP */ #ifndef OPENSSL_NO_RSA if (alg_k & SSL_kRSA) { if ((rsa=RSA_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH); goto f_err; } param_len += i; if (!(rsa->n=BN_bin2bn(p,i,rsa->n))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH); goto f_err; } param_len += i; if (!(rsa->e=BN_bin2bn(p,i,rsa->e))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; /* this should be because we are using an export cipher */ if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); else { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } s->session->sess_cert->peer_rsa_tmp=rsa; rsa=NULL; } #else /* OPENSSL_NO_RSA */ if (0) ; #endif #ifndef OPENSSL_NO_DH else if (alg_k & SSL_kDHE) { if ((dh=DH_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB); goto err; } param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH); goto f_err; } param_len += i; if (!(dh->p=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH); goto f_err; } param_len += i; if (!(dh->g=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH); goto f_err; } param_len += i; if (!(dh->pub_key=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; if (!ssl_security(s, SSL_SECOP_TMP_DH, DH_security_bits(dh), 0, dh)) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_DH_KEY_TOO_SMALL); goto f_err; } #ifndef OPENSSL_NO_RSA if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #else if (0) ; #endif #ifndef OPENSSL_NO_DSA else if (alg_a & SSL_aDSS) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509); #endif /* else anonymous DH, so no certificate or pkey. */ s->session->sess_cert->peer_dh_tmp=dh; dh=NULL; } else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER); goto f_err; } #endif /* !OPENSSL_NO_DH */ #ifndef OPENSSL_NO_ECDH else if (alg_k & SSL_kECDHE) { EC_GROUP *ngroup; const EC_GROUP *group; if ((ecdh=EC_KEY_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } /* Extract elliptic curve parameters and the * server's ephemeral ECDH public key. * Keep accumulating lengths of various components in * param_len and make sure it never exceeds n. */ /* XXX: For now we only support named (not generic) curves * and the ECParameters in this case is just three bytes. We * also need one byte for the length of the encoded point */ param_len=4; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } /* Check curve is one of our preferences, if not server has * sent an invalid curve. ECParameters is 3 bytes. */ if (!tls1_check_curve(s, p, 3)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_CURVE); goto f_err; } if ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0) { al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS); goto f_err; } ngroup = EC_GROUP_new_by_curve_name(curve_nid); if (ngroup == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } if (EC_KEY_set_group(ecdh, ngroup) == 0) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } EC_GROUP_free(ngroup); group = EC_KEY_get0_group(ecdh); if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && (EC_GROUP_get_degree(group) > 163)) { al=SSL_AD_EXPORT_RESTRICTION; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER); goto f_err; } p+=3; /* Next, get the encoded ECPoint */ if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) || ((bn_ctx = BN_CTX_new()) == NULL)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } encoded_pt_len = *p; /* length of encoded point */ p+=1; if ((encoded_pt_len > n - param_len) || (EC_POINT_oct2point(group, srvr_ecpoint, p, encoded_pt_len, bn_ctx) == 0)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT); goto f_err; } param_len += encoded_pt_len; n-=param_len; p+=encoded_pt_len; /* The ECC/TLS specification does not mention * the use of DSA to sign ECParameters in the server * key exchange message. We do support RSA and ECDSA. */ if (0) ; #ifndef OPENSSL_NO_RSA else if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #endif #ifndef OPENSSL_NO_ECDSA else if (alg_a & SSL_aECDSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509); #endif /* else anonymous ECDH, so no certificate or pkey. */ EC_KEY_set_public_key(ecdh, srvr_ecpoint); s->session->sess_cert->peer_ecdh_tmp=ecdh; ecdh=NULL; BN_CTX_free(bn_ctx); bn_ctx = NULL; EC_POINT_free(srvr_ecpoint); srvr_ecpoint = NULL; } else if (alg_k) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE); goto f_err; } #endif /* !OPENSSL_NO_ECDH */ /* p points to the next byte, there are 'n' bytes left */ /* if it was signed, check the signature */ if (pkey != NULL) { if (SSL_USE_SIGALGS(s)) { int rv; if (2 > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } rv = tls12_check_peer_sigalg(&md, s, p, pkey); if (rv == -1) goto err; else if (rv == 0) { goto f_err; } #ifdef SSL_DEBUG fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md)); #endif p += 2; n -= 2; } else md = EVP_sha1(); if (2 > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); n-=2; j=EVP_PKEY_size(pkey); /* Check signature length. If n is 0 then signature is empty */ if ((i != n) || (n > j) || (n <= 0)) { /* wrong packet length */ SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH); goto f_err; } #ifndef OPENSSL_NO_RSA if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) { int num; unsigned int size; j=0; q=md_buf; for (num=2; num > 0; num--) { EVP_MD_CTX_set_flags(&md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); EVP_DigestInit_ex(&md_ctx,(num == 2) ?s->ctx->md5:s->ctx->sha1, NULL); EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,param,param_len); EVP_DigestFinal_ex(&md_ctx,q,&size); q+=size; j+=size; } i=RSA_verify(NID_md5_sha1, md_buf, j, p, n, pkey->pkey.rsa); if (i < 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT); goto f_err; } if (i == 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); goto f_err; } } else #endif { EVP_VerifyInit_ex(&md_ctx, md, NULL); EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_VerifyUpdate(&md_ctx,param,param_len); if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); goto f_err; } } } else { /* aNULL, aSRP or kPSK do not need public keys */ if (!(alg_a & (SSL_aNULL|SSL_aSRP)) && !(alg_k & SSL_kPSK)) { /* Might be wrong key type, check it */ if (ssl3_check_cert_and_algorithm(s)) /* Otherwise this shouldn't happen */ SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } /* still data left over */ if (n != 0) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE); goto f_err; } } EVP_PKEY_free(pkey); EVP_MD_CTX_cleanup(&md_ctx); return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: EVP_PKEY_free(pkey); #ifndef OPENSSL_NO_RSA if (rsa != NULL) RSA_free(rsa); #endif #ifndef OPENSSL_NO_DH if (dh != NULL) DH_free(dh); #endif #ifndef OPENSSL_NO_ECDH BN_CTX_free(bn_ctx); EC_POINT_free(srvr_ecpoint); if (ecdh != NULL) EC_KEY_free(ecdh); #endif EVP_MD_CTX_cleanup(&md_ctx); return(-1); } int ssl3_get_certificate_request(SSL *s) { int ok,ret=0; unsigned long n,nc,l; unsigned int llen, ctype_num,i; X509_NAME *xn=NULL; const unsigned char *p,*q; unsigned char *d; STACK_OF(X509_NAME) *ca_sk=NULL; n=s->method->ssl_get_message(s, SSL3_ST_CR_CERT_REQ_A, SSL3_ST_CR_CERT_REQ_B, -1, s->max_cert_list, &ok); if (!ok) return((int)n); s->s3->tmp.cert_req=0; if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE) { s->s3->tmp.reuse_message=1; /* If we get here we don't need any cached handshake records * as we wont be doing client auth. */ if (s->s3->handshake_buffer) { if (!ssl3_digest_cached_records(s)) goto err; } return(1); } if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_WRONG_MESSAGE_TYPE); goto err; } /* TLS does not like anon-DH with client cert */ if (s->version > SSL3_VERSION) { if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER); goto err; } } p=d=(unsigned char *)s->init_msg; if ((ca_sk=sk_X509_NAME_new(ca_dn_cmp)) == NULL) { SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE); goto err; } /* get the certificate types */ ctype_num= *(p++); if (s->cert->ctypes) { OPENSSL_free(s->cert->ctypes); s->cert->ctypes = NULL; } if (ctype_num > SSL3_CT_NUMBER) { /* If we exceed static buffer copy all to cert structure */ s->cert->ctypes = OPENSSL_malloc(ctype_num); if (s->cert->ctypes == NULL) { SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE); goto err; } memcpy(s->cert->ctypes, p, ctype_num); s->cert->ctype_num = (size_t)ctype_num; ctype_num=SSL3_CT_NUMBER; } for (i=0; i<ctype_num; i++) s->s3->tmp.ctype[i]= p[i]; p+=p[-1]; if (SSL_USE_SIGALGS(s)) { n2s(p, llen); /* Check we have enough room for signature algorithms and * following length value. */ if ((unsigned long)(p - d + llen + 2) > n) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_DATA_LENGTH_TOO_LONG); goto err; } /* Clear certificate digests and validity flags */ for (i = 0; i < SSL_PKEY_NUM; i++) { s->cert->pkeys[i].digest = NULL; s->cert->pkeys[i].valid_flags = 0; } if ((llen & 1) || !tls1_save_sigalgs(s, p, llen)) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_SIGNATURE_ALGORITHMS_ERROR); goto err; } if (!tls1_process_sigalgs(s)) { ssl3_send_alert(s,SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE); goto err; } p += llen; } /* get the CA RDNs */ n2s(p,llen); #if 0 { FILE *out; out=fopen("/tmp/vsign.der","w"); fwrite(p,1,llen,out); fclose(out); } #endif if ((unsigned long)(p - d + llen) != n) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_LENGTH_MISMATCH); goto err; } for (nc=0; nc<llen; ) { n2s(p,l); if ((l+nc+2) > llen) { if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG)) goto cont; /* netscape bugs */ ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_TOO_LONG); goto err; } q=p; if ((xn=d2i_X509_NAME(NULL,&q,l)) == NULL) { /* If netscape tolerance is on, ignore errors */ if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG) goto cont; else { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_ASN1_LIB); goto err; } } if (q != (p+l)) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_LENGTH_MISMATCH); goto err; } if (!sk_X509_NAME_push(ca_sk,xn)) { SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE); goto err; } p+=l; nc+=l+2; } if (0) { cont: ERR_clear_error(); } /* we should setup a certificate to return.... */ s->s3->tmp.cert_req=1; s->s3->tmp.ctype_num=ctype_num; if (s->s3->tmp.ca_names != NULL) sk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free); s->s3->tmp.ca_names=ca_sk; ca_sk=NULL; ret=1; err: if (ca_sk != NULL) sk_X509_NAME_pop_free(ca_sk,X509_NAME_free); return(ret); } static int ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b) { return(X509_NAME_cmp(*a,*b)); } #ifndef OPENSSL_NO_TLSEXT int ssl3_get_new_session_ticket(SSL *s) { int ok,al,ret=0, ticklen; long n; const unsigned char *p; unsigned char *d; n=s->method->ssl_get_message(s, SSL3_ST_CR_SESSION_TICKET_A, SSL3_ST_CR_SESSION_TICKET_B, SSL3_MT_NEWSESSION_TICKET, 16384, &ok); if (!ok) return((int)n); if (n < 6) { /* need at least ticket_lifetime_hint + ticket length */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH); goto f_err; } p=d=(unsigned char *)s->init_msg; n2l(p, s->session->tlsext_tick_lifetime_hint); n2s(p, ticklen); /* ticket_lifetime_hint + ticket_length + ticket */ if (ticklen + 6 != n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH); goto f_err; } if (s->session->tlsext_tick) { OPENSSL_free(s->session->tlsext_tick); s->session->tlsext_ticklen = 0; } s->session->tlsext_tick = OPENSSL_malloc(ticklen); if (!s->session->tlsext_tick) { SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,ERR_R_MALLOC_FAILURE); goto err; } memcpy(s->session->tlsext_tick, p, ticklen); s->session->tlsext_ticklen = ticklen; /* There are two ways to detect a resumed ticket session. * One is to set an appropriate session ID and then the server * must return a match in ServerHello. This allows the normal * client session ID matching to work and we know much * earlier that the ticket has been accepted. * * The other way is to set zero length session ID when the * ticket is presented and rely on the handshake to determine * session resumption. * * We choose the former approach because this fits in with * assumptions elsewhere in OpenSSL. The session ID is set * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the * ticket. */ EVP_Digest(p, ticklen, s->session->session_id, &s->session->session_id_length, #ifndef OPENSSL_NO_SHA256 EVP_sha256(), NULL); #else EVP_sha1(), NULL); #endif ret=1; return(ret); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(-1); } int ssl3_get_cert_status(SSL *s) { int ok, al; unsigned long resplen,n; const unsigned char *p; n=s->method->ssl_get_message(s, SSL3_ST_CR_CERT_STATUS_A, SSL3_ST_CR_CERT_STATUS_B, SSL3_MT_CERTIFICATE_STATUS, 16384, &ok); if (!ok) return((int)n); if (n < 4) { /* need at least status type + length */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH); goto f_err; } p = (unsigned char *)s->init_msg; if (*p++ != TLSEXT_STATUSTYPE_ocsp) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_UNSUPPORTED_STATUS_TYPE); goto f_err; } n2l3(p, resplen); if (resplen + 4 != n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH); goto f_err; } if (s->tlsext_ocsp_resp) OPENSSL_free(s->tlsext_ocsp_resp); s->tlsext_ocsp_resp = BUF_memdup(p, resplen); if (!s->tlsext_ocsp_resp) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE); goto f_err; } s->tlsext_ocsp_resplen = resplen; if (s->ctx->tlsext_status_cb) { int ret; ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg); if (ret == 0) { al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE; SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_INVALID_STATUS_RESPONSE); goto f_err; } if (ret < 0) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE); goto f_err; } } return 1; f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); return(-1); } #endif int ssl3_get_server_done(SSL *s) { int ok,ret=0; long n; n=s->method->ssl_get_message(s, SSL3_ST_CR_SRVR_DONE_A, SSL3_ST_CR_SRVR_DONE_B, SSL3_MT_SERVER_DONE, 30, /* should be very small, like 0 :-) */ &ok); if (!ok) return((int)n); if (n > 0) { /* should contain no data */ ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_SERVER_DONE,SSL_R_LENGTH_MISMATCH); return -1; } ret=1; return(ret); } int ssl3_send_client_key_exchange(SSL *s) { unsigned char *p; int n; unsigned long alg_k; #ifndef OPENSSL_NO_RSA unsigned char *q; EVP_PKEY *pkey=NULL; #endif #ifndef OPENSSL_NO_KRB5 KSSL_ERR kssl_err; #endif /* OPENSSL_NO_KRB5 */ #ifndef OPENSSL_NO_ECDH EC_KEY *clnt_ecdh = NULL; const EC_POINT *srvr_ecpoint = NULL; EVP_PKEY *srvr_pub_pkey = NULL; unsigned char *encodedPoint = NULL; int encoded_pt_len = 0; BN_CTX * bn_ctx = NULL; #endif if (s->state == SSL3_ST_CW_KEY_EXCH_A) { p = ssl_handshake_start(s); alg_k=s->s3->tmp.new_cipher->algorithm_mkey; /* Fool emacs indentation */ if (0) {} #ifndef OPENSSL_NO_RSA else if (alg_k & SSL_kRSA) { RSA *rsa; unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH]; if (s->session->sess_cert == NULL) { /* We should always have a server certificate with SSL_kRSA. */ SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } if (s->session->sess_cert->peer_rsa_tmp != NULL) rsa=s->session->sess_cert->peer_rsa_tmp; else { pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } rsa=pkey->pkey.rsa; EVP_PKEY_free(pkey); } tmp_buf[0]=s->client_version>>8; tmp_buf[1]=s->client_version&0xff; if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0) goto err; s->session->master_key_length=sizeof tmp_buf; q=p; /* Fix buf for TLS and beyond */ if (s->version > SSL3_VERSION) p+=2; n=RSA_public_encrypt(sizeof tmp_buf, tmp_buf,p,rsa,RSA_PKCS1_PADDING); #ifdef PKCS1_CHECK if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++; if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70; #endif if (n <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT); goto err; } /* Fix buf for TLS and beyond */ if (s->version > SSL3_VERSION) { s2n(n,q); n+=2; } s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key, tmp_buf,sizeof tmp_buf); OPENSSL_cleanse(tmp_buf,sizeof tmp_buf); } #endif #ifndef OPENSSL_NO_KRB5 else if (alg_k & SSL_kKRB5) { krb5_error_code krb5rc; KSSL_CTX *kssl_ctx = s->kssl_ctx; /* krb5_data krb5_ap_req; */ krb5_data *enc_ticket; krb5_data authenticator, *authp = NULL; EVP_CIPHER_CTX ciph_ctx; const EVP_CIPHER *enc = NULL; unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH]; unsigned char epms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_IV_LENGTH]; int padl, outl = sizeof(epms); EVP_CIPHER_CTX_init(&ciph_ctx); #ifdef KSSL_DEBUG fprintf(stderr,"ssl3_send_client_key_exchange(%lx & %lx)\n", alg_k, SSL_kKRB5); #endif /* KSSL_DEBUG */ authp = NULL; #ifdef KRB5SENDAUTH if (KRB5SENDAUTH) authp = &authenticator; #endif /* KRB5SENDAUTH */ krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp, &kssl_err); enc = kssl_map_enc(kssl_ctx->enctype); if (enc == NULL) goto err; #ifdef KSSL_DEBUG { fprintf(stderr,"kssl_cget_tkt rtn %d\n", krb5rc); if (krb5rc && kssl_err.text) fprintf(stderr,"kssl_cget_tkt kssl_err=%s\n", kssl_err.text); } #endif /* KSSL_DEBUG */ if (krb5rc) { ssl3_send_alert(s,SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, kssl_err.reason); goto err; } /*- * 20010406 VRS - Earlier versions used KRB5 AP_REQ * in place of RFC 2712 KerberosWrapper, as in: * * Send ticket (copy to *p, set n = length) * n = krb5_ap_req.length; * memcpy(p, krb5_ap_req.data, krb5_ap_req.length); * if (krb5_ap_req.data) * kssl_krb5_free_data_contents(NULL,&krb5_ap_req); * * Now using real RFC 2712 KerberosWrapper * (Thanks to Simon Wilkinson <sxw@sxw.org.uk>) * Note: 2712 "opaque" types are here replaced * with a 2-byte length followed by the value. * Example: * KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms * Where "xx xx" = length bytes. Shown here with * optional authenticator omitted. */ /* KerberosWrapper.Ticket */ s2n(enc_ticket->length,p); memcpy(p, enc_ticket->data, enc_ticket->length); p+= enc_ticket->length; n = enc_ticket->length + 2; /* KerberosWrapper.Authenticator */ if (authp && authp->length) { s2n(authp->length,p); memcpy(p, authp->data, authp->length); p+= authp->length; n+= authp->length + 2; free(authp->data); authp->data = NULL; authp->length = 0; } else { s2n(0,p);/* null authenticator length */ n+=2; } tmp_buf[0]=s->client_version>>8; tmp_buf[1]=s->client_version&0xff; if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0) goto err; /*- * 20010420 VRS. Tried it this way; failed. * EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL); * EVP_CIPHER_CTX_set_key_length(&ciph_ctx, * kssl_ctx->length); * EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv); */ memset(iv, 0, sizeof iv); /* per RFC 1510 */ EVP_EncryptInit_ex(&ciph_ctx,enc, NULL, kssl_ctx->key,iv); EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf, sizeof tmp_buf); EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl); outl += padl; if (outl > (int)sizeof epms) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } EVP_CIPHER_CTX_cleanup(&ciph_ctx); /* KerberosWrapper.EncryptedPreMasterSecret */ s2n(outl,p); memcpy(p, epms, outl); p+=outl; n+=outl + 2; s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key, tmp_buf, sizeof tmp_buf); OPENSSL_cleanse(tmp_buf, sizeof tmp_buf); OPENSSL_cleanse(epms, outl); } #endif #ifndef OPENSSL_NO_DH else if (alg_k & (SSL_kDHE|SSL_kDHr|SSL_kDHd)) { DH *dh_srvr,*dh_clnt; SESS_CERT *scert = s->session->sess_cert; if (scert == NULL) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE); goto err; } if (scert->peer_dh_tmp != NULL) dh_srvr=scert->peer_dh_tmp; else { /* we get them from the cert */ int idx = scert->peer_cert_type; EVP_PKEY *spkey = NULL; dh_srvr = NULL; if (idx >= 0) spkey = X509_get_pubkey( scert->peer_pkeys[idx].x509); if (spkey) { dh_srvr = EVP_PKEY_get1_DH(spkey); EVP_PKEY_free(spkey); } if (dh_srvr == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } } if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) { /* Use client certificate key */ EVP_PKEY *clkey = s->cert->key->privatekey; dh_clnt = NULL; if (clkey) dh_clnt = EVP_PKEY_get1_DH(clkey); if (dh_clnt == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } } else { /* generate a new random key */ if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); goto err; } if (!DH_generate_key(dh_clnt)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); DH_free(dh_clnt); goto err; } } /* use the 'p' output buffer for the DH key, but * make sure to clear it out afterwards */ n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt); if (scert->peer_dh_tmp == NULL) DH_free(dh_srvr); if (n <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); DH_free(dh_clnt); goto err; } /* generate master key from the result */ s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key,p,n); /* clean up */ memset(p,0,n); if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) n = 0; else { /* send off the data */ n=BN_num_bytes(dh_clnt->pub_key); s2n(n,p); BN_bn2bin(dh_clnt->pub_key,p); n+=2; } DH_free(dh_clnt); /* perhaps clean things up a bit EAY EAY EAY EAY*/ } #endif #ifndef OPENSSL_NO_ECDH else if (alg_k & (SSL_kECDHE|SSL_kECDHr|SSL_kECDHe)) { const EC_GROUP *srvr_group = NULL; EC_KEY *tkey; int ecdh_clnt_cert = 0; int field_size = 0; if (s->session->sess_cert == NULL) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE); goto err; } /* Did we send out the client's * ECDH share for use in premaster * computation as part of client certificate? * If so, set ecdh_clnt_cert to 1. */ if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL)) { /*- * XXX: For now, we do not support client * authentication using ECDH certificates. * To add such support, one needs to add * code that checks for appropriate * conditions and sets ecdh_clnt_cert to 1. * For example, the cert have an ECC * key on the same curve as the server's * and the key should be authorized for * key agreement. * * One also needs to add code in ssl3_connect * to skip sending the certificate verify * message. * * if ((s->cert->key->privatekey != NULL) && * (s->cert->key->privatekey->type == * EVP_PKEY_EC) && ...) * ecdh_clnt_cert = 1; */ } if (s->session->sess_cert->peer_ecdh_tmp != NULL) { tkey = s->session->sess_cert->peer_ecdh_tmp; } else { /* Get the Server Public Key from Cert */ srvr_pub_pkey = X509_get_pubkey(s->session-> \ sess_cert->peer_pkeys[SSL_PKEY_ECC].x509); if ((srvr_pub_pkey == NULL) || (srvr_pub_pkey->type != EVP_PKEY_EC) || (srvr_pub_pkey->pkey.ec == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } tkey = srvr_pub_pkey->pkey.ec; } srvr_group = EC_KEY_get0_group(tkey); srvr_ecpoint = EC_KEY_get0_public_key(tkey); if ((srvr_group == NULL) || (srvr_ecpoint == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } if ((clnt_ecdh=EC_KEY_new()) == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } if (!EC_KEY_set_group(clnt_ecdh, srvr_group)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } if (ecdh_clnt_cert) { /* Reuse key info from our certificate * We only need our private key to perform * the ECDH computation. */ const BIGNUM *priv_key; tkey = s->cert->key->privatekey->pkey.ec; priv_key = EC_KEY_get0_private_key(tkey); if (priv_key == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } if (!EC_KEY_set_private_key(clnt_ecdh, priv_key)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } } else { /* Generate a new ECDH key pair */ if (!(EC_KEY_generate_key(clnt_ecdh))) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } } /* use the 'p' output buffer for the ECDH key, but * make sure to clear it out afterwards */ field_size = EC_GROUP_get_degree(srvr_group); if (field_size <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL); if (n <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } /* generate master key from the result */ s->session->master_key_length = s->method->ssl3_enc \ -> generate_master_secret(s, s->session->master_key, p, n); memset(p, 0, n); /* clean up */ if (ecdh_clnt_cert) { /* Send empty client key exch message */ n = 0; } else { /* First check the size of encoding and * allocate memory accordingly. */ encoded_pt_len = EC_POINT_point2oct(srvr_group, EC_KEY_get0_public_key(clnt_ecdh), POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL); encodedPoint = (unsigned char *) OPENSSL_malloc(encoded_pt_len * sizeof(unsigned char)); bn_ctx = BN_CTX_new(); if ((encodedPoint == NULL) || (bn_ctx == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } /* Encode the public key */ n = EC_POINT_point2oct(srvr_group, EC_KEY_get0_public_key(clnt_ecdh), POINT_CONVERSION_UNCOMPRESSED, encodedPoint, encoded_pt_len, bn_ctx); *p = n; /* length of encoded point */ /* Encoded point will be copied here */ p += 1; /* copy the point */ memcpy((unsigned char *)p, encodedPoint, n); /* increment n to account for length field */ n += 1; } /* Free allocated memory */ BN_CTX_free(bn_ctx); if (encodedPoint != NULL) OPENSSL_free(encodedPoint); if (clnt_ecdh != NULL) EC_KEY_free(clnt_ecdh); EVP_PKEY_free(srvr_pub_pkey); } #endif /* !OPENSSL_NO_ECDH */ else if (alg_k & SSL_kGOST) { /* GOST key exchange message creation */ EVP_PKEY_CTX *pkey_ctx; X509 *peer_cert; size_t msglen; unsigned int md_len; int keytype; unsigned char premaster_secret[32],shared_ukm[32], tmp[256]; EVP_MD_CTX *ukm_hash; EVP_PKEY *pub_key; /* Get server sertificate PKEY and create ctx from it */ peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST01)].x509; if (!peer_cert) peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST94)].x509; if (!peer_cert) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER); goto err; } pkey_ctx=EVP_PKEY_CTX_new(pub_key=X509_get_pubkey(peer_cert),NULL); /* If we have send a certificate, and certificate key * parameters match those of server certificate, use * certificate key for key exchange */ /* Otherwise, generate ephemeral key pair */ EVP_PKEY_encrypt_init(pkey_ctx); /* Generate session key */ RAND_bytes(premaster_secret,32); /* If we have client certificate, use its secret as peer key */ if (s->s3->tmp.cert_req && s->cert->key->privatekey) { if (EVP_PKEY_derive_set_peer(pkey_ctx,s->cert->key->privatekey) <=0) { /* If there was an error - just ignore it. Ephemeral key * would be used */ ERR_clear_error(); } } /* Compute shared IV and store it in algorithm-specific * context data */ ukm_hash = EVP_MD_CTX_create(); EVP_DigestInit(ukm_hash,EVP_get_digestbynid(NID_id_GostR3411_94)); EVP_DigestUpdate(ukm_hash,s->s3->client_random,SSL3_RANDOM_SIZE); EVP_DigestUpdate(ukm_hash,s->s3->server_random,SSL3_RANDOM_SIZE); EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len); EVP_MD_CTX_destroy(ukm_hash); if (EVP_PKEY_CTX_ctrl(pkey_ctx,-1,EVP_PKEY_OP_ENCRYPT,EVP_PKEY_CTRL_SET_IV, 8,shared_ukm)<0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_LIBRARY_BUG); goto err; } /* Make GOST keytransport blob message */ /*Encapsulate it into sequence */ *(p++)=V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED; msglen=255; if (EVP_PKEY_encrypt(pkey_ctx,tmp,&msglen,premaster_secret,32)<0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_LIBRARY_BUG); goto err; } if (msglen >= 0x80) { *(p++)=0x81; *(p++)= msglen & 0xff; n=msglen+3; } else { *(p++)= msglen & 0xff; n=msglen+2; } memcpy(p, tmp, msglen); /* Check if pubkey from client certificate was used */ if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) { /* Set flag "skip certificate verify" */ s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY; } EVP_PKEY_CTX_free(pkey_ctx); s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key,premaster_secret,32); EVP_PKEY_free(pub_key); } #ifndef OPENSSL_NO_SRP else if (alg_k & SSL_kSRP) { if (s->srp_ctx.A != NULL) { /* send off the data */ n=BN_num_bytes(s->srp_ctx.A); s2n(n,p); BN_bn2bin(s->srp_ctx.A,p); n+=2; } else { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } if (s->session->srp_username != NULL) OPENSSL_free(s->session->srp_username); s->session->srp_username = BUF_strdup(s->srp_ctx.login); if (s->session->srp_username == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } if ((s->session->master_key_length = SRP_generate_client_master_secret(s,s->session->master_key))<0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } } #endif #ifndef OPENSSL_NO_PSK else if (alg_k & SSL_kPSK) { /* The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes * to return a \0-terminated identity. The last byte * is for us for simulating strnlen. */ char identity[PSK_MAX_IDENTITY_LEN + 2]; size_t identity_len; unsigned char *t = NULL; unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4]; unsigned int pre_ms_len = 0, psk_len = 0; int psk_err = 1; n = 0; if (s->psk_client_callback == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_PSK_NO_CLIENT_CB); goto err; } memset(identity, 0, sizeof(identity)); psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint, identity, sizeof(identity) - 1, psk_or_pre_ms, sizeof(psk_or_pre_ms)); if (psk_len > PSK_MAX_PSK_LEN) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto psk_err; } else if (psk_len == 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_PSK_IDENTITY_NOT_FOUND); goto psk_err; } identity[PSK_MAX_IDENTITY_LEN + 1] = '\0'; identity_len = strlen(identity); if (identity_len > PSK_MAX_IDENTITY_LEN) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto psk_err; } /* create PSK pre_master_secret */ pre_ms_len = 2+psk_len+2+psk_len; t = psk_or_pre_ms; memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len); s2n(psk_len, t); memset(t, 0, psk_len); t+=psk_len; s2n(psk_len, t); if (s->session->psk_identity_hint != NULL) OPENSSL_free(s->session->psk_identity_hint); s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint); if (s->ctx->psk_identity_hint != NULL && s->session->psk_identity_hint == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto psk_err; } if (s->session->psk_identity != NULL) OPENSSL_free(s->session->psk_identity); s->session->psk_identity = BUF_strdup(identity); if (s->session->psk_identity == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto psk_err; } s->session->master_key_length = s->method->ssl3_enc->generate_master_secret(s, s->session->master_key, psk_or_pre_ms, pre_ms_len); s2n(identity_len, p); memcpy(p, identity, identity_len); n = 2 + identity_len; psk_err = 0; psk_err: OPENSSL_cleanse(identity, sizeof(identity)); OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms)); if (psk_err != 0) { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); goto err; } } #endif else { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n); s->state=SSL3_ST_CW_KEY_EXCH_B; } /* SSL3_ST_CW_KEY_EXCH_B */ return ssl_do_write(s); err: #ifndef OPENSSL_NO_ECDH BN_CTX_free(bn_ctx); if (encodedPoint != NULL) OPENSSL_free(encodedPoint); if (clnt_ecdh != NULL) EC_KEY_free(clnt_ecdh); EVP_PKEY_free(srvr_pub_pkey); #endif return(-1); } int ssl3_send_client_verify(SSL *s) { unsigned char *p; unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH]; EVP_PKEY *pkey; EVP_PKEY_CTX *pctx=NULL; EVP_MD_CTX mctx; unsigned u=0; unsigned long n; int j; EVP_MD_CTX_init(&mctx); if (s->state == SSL3_ST_CW_CERT_VRFY_A) { p= ssl_handshake_start(s); pkey=s->cert->key->privatekey; /* Create context from key and test if sha1 is allowed as digest */ pctx = EVP_PKEY_CTX_new(pkey,NULL); EVP_PKEY_sign_init(pctx); if (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1())>0) { if (!SSL_USE_SIGALGS(s)) s->method->ssl3_enc->cert_verify_mac(s, NID_sha1, &(data[MD5_DIGEST_LENGTH])); } else { ERR_clear_error(); } /* For TLS v1.2 send signature algorithm and signature * using agreed digest and cached handshake records. */ if (SSL_USE_SIGALGS(s)) { long hdatalen = 0; void *hdata; const EVP_MD *md = s->cert->key->digest; hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata); if (hdatalen <= 0 || !tls12_get_sigandhash(p, pkey, md)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR); goto err; } p += 2; #ifdef SSL_DEBUG fprintf(stderr, "Using TLS 1.2 with client alg %s\n", EVP_MD_name(md)); #endif if (!EVP_SignInit_ex(&mctx, md, NULL) || !EVP_SignUpdate(&mctx, hdata, hdatalen) || !EVP_SignFinal(&mctx, p + 2, &u, pkey)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_EVP_LIB); goto err; } s2n(u,p); n = u + 4; if (!ssl3_digest_cached_records(s)) goto err; } else #ifndef OPENSSL_NO_RSA if (pkey->type == EVP_PKEY_RSA) { s->method->ssl3_enc->cert_verify_mac(s, NID_md5, &(data[0])); if (RSA_sign(NID_md5_sha1, data, MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, &(p[2]), &u, pkey->pkey.rsa) <= 0 ) { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB); goto err; } s2n(u,p); n=u+2; } else #endif #ifndef OPENSSL_NO_DSA if (pkey->type == EVP_PKEY_DSA) { if (!DSA_sign(pkey->save_type, &(data[MD5_DIGEST_LENGTH]), SHA_DIGEST_LENGTH,&(p[2]), (unsigned int *)&j,pkey->pkey.dsa)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB); goto err; } s2n(j,p); n=j+2; } else #endif #ifndef OPENSSL_NO_ECDSA if (pkey->type == EVP_PKEY_EC) { if (!ECDSA_sign(pkey->save_type, &(data[MD5_DIGEST_LENGTH]), SHA_DIGEST_LENGTH,&(p[2]), (unsigned int *)&j,pkey->pkey.ec)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_ECDSA_LIB); goto err; } s2n(j,p); n=j+2; } else #endif if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001) { unsigned char signbuf[64]; int i; size_t sigsize=64; s->method->ssl3_enc->cert_verify_mac(s, NID_id_GostR3411_94, data); if (EVP_PKEY_sign(pctx, signbuf, &sigsize, data, 32) <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR); goto err; } for (i=63,j=0; i>=0; j++, i--) { p[2+j]=signbuf[i]; } s2n(j,p); n=j+2; } else { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR); goto err; } ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_VERIFY, n); s->state=SSL3_ST_CW_CERT_VRFY_B; } EVP_MD_CTX_cleanup(&mctx); EVP_PKEY_CTX_free(pctx); return ssl_do_write(s); err: EVP_MD_CTX_cleanup(&mctx); EVP_PKEY_CTX_free(pctx); return(-1); } /* Check a certificate can be used for client authentication. Currently * check cert exists, if we have a suitable digest for TLS 1.2 if * static DH client certificates can be used and optionally checks * suitability for Suite B. */ static int ssl3_check_client_certificate(SSL *s) { unsigned long alg_k; if (!s->cert || !s->cert->key->x509 || !s->cert->key->privatekey) return 0; /* If no suitable signature algorithm can't use certificate */ if (SSL_USE_SIGALGS(s) && !s->cert->key->digest) return 0; /* If strict mode check suitability of chain before using it. * This also adjusts suite B digest if necessary. */ if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT && !tls1_check_chain(s, NULL, NULL, NULL, -2)) return 0; alg_k=s->s3->tmp.new_cipher->algorithm_mkey; /* See if we can use client certificate for fixed DH */ if (alg_k & (SSL_kDHr|SSL_kDHd)) { SESS_CERT *scert = s->session->sess_cert; int i = scert->peer_cert_type; EVP_PKEY *clkey = NULL, *spkey = NULL; clkey = s->cert->key->privatekey; /* If client key not DH assume it can be used */ if (EVP_PKEY_id(clkey) != EVP_PKEY_DH) return 1; if (i >= 0) spkey = X509_get_pubkey(scert->peer_pkeys[i].x509); if (spkey) { /* Compare server and client parameters */ i = EVP_PKEY_cmp_parameters(clkey, spkey); EVP_PKEY_free(spkey); if (i != 1) return 0; } s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY; } return 1; } int ssl3_send_client_certificate(SSL *s) { X509 *x509=NULL; EVP_PKEY *pkey=NULL; int i; if (s->state == SSL3_ST_CW_CERT_A) { /* Let cert callback update client certificates if required */ if (s->cert->cert_cb) { i = s->cert->cert_cb(s, s->cert->cert_cb_arg); if (i < 0) { s->rwstate=SSL_X509_LOOKUP; return -1; } if (i == 0) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR); return 0; } s->rwstate=SSL_NOTHING; } if (ssl3_check_client_certificate(s)) s->state=SSL3_ST_CW_CERT_C; else s->state=SSL3_ST_CW_CERT_B; } /* We need to get a client cert */ if (s->state == SSL3_ST_CW_CERT_B) { /* If we get an error, we need to * ssl->rwstate=SSL_X509_LOOKUP; return(-1); * We then get retied later */ i=0; i = ssl_do_client_cert_cb(s, &x509, &pkey); if (i < 0) { s->rwstate=SSL_X509_LOOKUP; return(-1); } s->rwstate=SSL_NOTHING; if ((i == 1) && (pkey != NULL) && (x509 != NULL)) { s->state=SSL3_ST_CW_CERT_B; if ( !SSL_use_certificate(s,x509) || !SSL_use_PrivateKey(s,pkey)) i=0; } else if (i == 1) { i=0; SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK); } if (x509 != NULL) X509_free(x509); if (pkey != NULL) EVP_PKEY_free(pkey); if (i && !ssl3_check_client_certificate(s)) i = 0; if (i == 0) { if (s->version == SSL3_VERSION) { s->s3->tmp.cert_req=0; ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE); return(1); } else { s->s3->tmp.cert_req=2; } } /* Ok, we have a cert */ s->state=SSL3_ST_CW_CERT_C; } if (s->state == SSL3_ST_CW_CERT_C) { s->state=SSL3_ST_CW_CERT_D; if (!ssl3_output_cert_chain(s, (s->s3->tmp.cert_req == 2)?NULL:s->cert->key)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR); ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR); return 0; } } /* SSL3_ST_CW_CERT_D */ return ssl_do_write(s); } #define has_bits(i,m) (((i)&(m)) == (m)) int ssl3_check_cert_and_algorithm(SSL *s) { int i,idx; long alg_k,alg_a; EVP_PKEY *pkey=NULL; SESS_CERT *sc; #ifndef OPENSSL_NO_RSA RSA *rsa; #endif #ifndef OPENSSL_NO_DH DH *dh; #endif alg_k=s->s3->tmp.new_cipher->algorithm_mkey; alg_a=s->s3->tmp.new_cipher->algorithm_auth; /* we don't have a certificate */ if ((alg_a & (SSL_aNULL|SSL_aKRB5)) || (alg_k & SSL_kPSK)) return(1); sc=s->session->sess_cert; if (sc == NULL) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,ERR_R_INTERNAL_ERROR); goto err; } #ifndef OPENSSL_NO_RSA rsa=s->session->sess_cert->peer_rsa_tmp; #endif #ifndef OPENSSL_NO_DH dh=s->session->sess_cert->peer_dh_tmp; #endif /* This is the passed certificate */ idx=sc->peer_cert_type; #ifndef OPENSSL_NO_ECDH if (idx == SSL_PKEY_ECC) { if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509, s) == 0) { /* check failed */ SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_BAD_ECC_CERT); goto f_err; } else { return 1; } } else if (alg_a & SSL_aECDSA) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_ECDSA_SIGNING_CERT); goto f_err; } else if (alg_k & (SSL_kECDHr|SSL_kECDHe)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_ECDH_CERT); goto f_err; } #endif pkey=X509_get_pubkey(sc->peer_pkeys[idx].x509); i=X509_certificate_type(sc->peer_pkeys[idx].x509,pkey); EVP_PKEY_free(pkey); /* Check that we have a certificate if we require one */ if ((alg_a & SSL_aRSA) && !has_bits(i,EVP_PK_RSA|EVP_PKT_SIGN)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_SIGNING_CERT); goto f_err; } #ifndef OPENSSL_NO_DSA else if ((alg_a & SSL_aDSS) && !has_bits(i,EVP_PK_DSA|EVP_PKT_SIGN)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DSA_SIGNING_CERT); goto f_err; } #endif #ifndef OPENSSL_NO_RSA if ((alg_k & SSL_kRSA) && !(has_bits(i,EVP_PK_RSA|EVP_PKT_ENC) || (rsa != NULL))) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_ENCRYPTING_CERT); goto f_err; } #endif #ifndef OPENSSL_NO_DH if ((alg_k & SSL_kDHE) && !(has_bits(i,EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL))) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_KEY); goto f_err; } else if ((alg_k & SSL_kDHr) && !SSL_USE_SIGALGS(s) && !has_bits(i,EVP_PK_DH|EVP_PKS_RSA)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_RSA_CERT); goto f_err; } #ifndef OPENSSL_NO_DSA else if ((alg_k & SSL_kDHd) && !SSL_USE_SIGALGS(s) && !has_bits(i,EVP_PK_DH|EVP_PKS_DSA)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_DSA_CERT); goto f_err; } #endif #endif if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && !has_bits(i,EVP_PKT_EXP)) { #ifndef OPENSSL_NO_RSA if (alg_k & SSL_kRSA) { if (rsa == NULL || RSA_size(rsa)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_RSA_KEY); goto f_err; } } else #endif #ifndef OPENSSL_NO_DH if (alg_k & (SSL_kDHE|SSL_kDHr|SSL_kDHd)) { if (dh == NULL || DH_size(dh)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_DH_KEY); goto f_err; } } else #endif { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE); goto f_err; } } return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); err: return(0); } /* Check to see if handshake is full or resumed. Usually this is just a * case of checking to see if a cache hit has occurred. In the case of * session tickets we have to check the next message to be sure. */ #ifndef OPENSSL_NO_TLSEXT # ifndef OPENSSL_NO_NEXTPROTONEG int ssl3_send_next_proto(SSL *s) { unsigned int len, padding_len; unsigned char *d; if (s->state == SSL3_ST_CW_NEXT_PROTO_A) { len = s->next_proto_negotiated_len; padding_len = 32 - ((len + 2) % 32); d = (unsigned char *)s->init_buf->data; d[4] = len; memcpy(d + 5, s->next_proto_negotiated, len); d[5 + len] = padding_len; memset(d + 6 + len, 0, padding_len); *(d++)=SSL3_MT_NEXT_PROTO; l2n3(2 + len + padding_len, d); s->state = SSL3_ST_CW_NEXT_PROTO_B; s->init_num = 4 + 2 + len + padding_len; s->init_off = 0; } return ssl3_do_write(s, SSL3_RT_HANDSHAKE); } # endif #endif int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey) { int i = 0; #ifndef OPENSSL_NO_ENGINE if (s->ctx->client_cert_engine) { i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s, SSL_get_client_CA_list(s), px509, ppkey, NULL, NULL, NULL); if (i != 0) return i; } #endif if (s->ctx->client_cert_cb) i = s->ctx->client_cert_cb(s,px509,ppkey); return i; }
./CrossVul/dataset_final_sorted/CWE-310/c/bad_1445_4
crossvul-cpp_data_bad_892_0
/* cipher-gcm.c - Generic Galois Counter Mode implementation * Copyright (C) 2013 Dmitry Eremin-Solenikov * Copyright (C) 2013, 2018-2019 Jussi Kivilinna <jussi.kivilinna@iki.fi> * * This file is part of Libgcrypt. * * Libgcrypt 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. * * Libgcrypt 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 program; if not, see <http://www.gnu.org/licenses/>. */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include "g10lib.h" #include "cipher.h" #include "bufhelp.h" #include "./cipher-internal.h" #ifdef GCM_USE_INTEL_PCLMUL extern void _gcry_ghash_setup_intel_pclmul (gcry_cipher_hd_t c); extern unsigned int _gcry_ghash_intel_pclmul (gcry_cipher_hd_t c, byte *result, const byte *buf, size_t nblocks); #endif #ifdef GCM_USE_ARM_PMULL extern void _gcry_ghash_setup_armv8_ce_pmull (void *gcm_key, void *gcm_table); extern unsigned int _gcry_ghash_armv8_ce_pmull (void *gcm_key, byte *result, const byte *buf, size_t nblocks, void *gcm_table); static void ghash_setup_armv8_ce_pmull (gcry_cipher_hd_t c) { _gcry_ghash_setup_armv8_ce_pmull(c->u_mode.gcm.u_ghash_key.key, c->u_mode.gcm.gcm_table); } static unsigned int ghash_armv8_ce_pmull (gcry_cipher_hd_t c, byte *result, const byte *buf, size_t nblocks) { return _gcry_ghash_armv8_ce_pmull(c->u_mode.gcm.u_ghash_key.key, result, buf, nblocks, c->u_mode.gcm.gcm_table); } #endif /* GCM_USE_ARM_PMULL */ #ifdef GCM_USE_ARM_NEON extern void _gcry_ghash_setup_armv7_neon (void *gcm_key); extern unsigned int _gcry_ghash_armv7_neon (void *gcm_key, byte *result, const byte *buf, size_t nblocks); static void ghash_setup_armv7_neon (gcry_cipher_hd_t c) { _gcry_ghash_setup_armv7_neon(c->u_mode.gcm.u_ghash_key.key); } static unsigned int ghash_armv7_neon (gcry_cipher_hd_t c, byte *result, const byte *buf, size_t nblocks) { return _gcry_ghash_armv7_neon(c->u_mode.gcm.u_ghash_key.key, result, buf, nblocks); } #endif /* GCM_USE_ARM_NEON */ #ifdef GCM_USE_TABLES static const u16 gcmR[256] = { 0x0000, 0x01c2, 0x0384, 0x0246, 0x0708, 0x06ca, 0x048c, 0x054e, 0x0e10, 0x0fd2, 0x0d94, 0x0c56, 0x0918, 0x08da, 0x0a9c, 0x0b5e, 0x1c20, 0x1de2, 0x1fa4, 0x1e66, 0x1b28, 0x1aea, 0x18ac, 0x196e, 0x1230, 0x13f2, 0x11b4, 0x1076, 0x1538, 0x14fa, 0x16bc, 0x177e, 0x3840, 0x3982, 0x3bc4, 0x3a06, 0x3f48, 0x3e8a, 0x3ccc, 0x3d0e, 0x3650, 0x3792, 0x35d4, 0x3416, 0x3158, 0x309a, 0x32dc, 0x331e, 0x2460, 0x25a2, 0x27e4, 0x2626, 0x2368, 0x22aa, 0x20ec, 0x212e, 0x2a70, 0x2bb2, 0x29f4, 0x2836, 0x2d78, 0x2cba, 0x2efc, 0x2f3e, 0x7080, 0x7142, 0x7304, 0x72c6, 0x7788, 0x764a, 0x740c, 0x75ce, 0x7e90, 0x7f52, 0x7d14, 0x7cd6, 0x7998, 0x785a, 0x7a1c, 0x7bde, 0x6ca0, 0x6d62, 0x6f24, 0x6ee6, 0x6ba8, 0x6a6a, 0x682c, 0x69ee, 0x62b0, 0x6372, 0x6134, 0x60f6, 0x65b8, 0x647a, 0x663c, 0x67fe, 0x48c0, 0x4902, 0x4b44, 0x4a86, 0x4fc8, 0x4e0a, 0x4c4c, 0x4d8e, 0x46d0, 0x4712, 0x4554, 0x4496, 0x41d8, 0x401a, 0x425c, 0x439e, 0x54e0, 0x5522, 0x5764, 0x56a6, 0x53e8, 0x522a, 0x506c, 0x51ae, 0x5af0, 0x5b32, 0x5974, 0x58b6, 0x5df8, 0x5c3a, 0x5e7c, 0x5fbe, 0xe100, 0xe0c2, 0xe284, 0xe346, 0xe608, 0xe7ca, 0xe58c, 0xe44e, 0xef10, 0xeed2, 0xec94, 0xed56, 0xe818, 0xe9da, 0xeb9c, 0xea5e, 0xfd20, 0xfce2, 0xfea4, 0xff66, 0xfa28, 0xfbea, 0xf9ac, 0xf86e, 0xf330, 0xf2f2, 0xf0b4, 0xf176, 0xf438, 0xf5fa, 0xf7bc, 0xf67e, 0xd940, 0xd882, 0xdac4, 0xdb06, 0xde48, 0xdf8a, 0xddcc, 0xdc0e, 0xd750, 0xd692, 0xd4d4, 0xd516, 0xd058, 0xd19a, 0xd3dc, 0xd21e, 0xc560, 0xc4a2, 0xc6e4, 0xc726, 0xc268, 0xc3aa, 0xc1ec, 0xc02e, 0xcb70, 0xcab2, 0xc8f4, 0xc936, 0xcc78, 0xcdba, 0xcffc, 0xce3e, 0x9180, 0x9042, 0x9204, 0x93c6, 0x9688, 0x974a, 0x950c, 0x94ce, 0x9f90, 0x9e52, 0x9c14, 0x9dd6, 0x9898, 0x995a, 0x9b1c, 0x9ade, 0x8da0, 0x8c62, 0x8e24, 0x8fe6, 0x8aa8, 0x8b6a, 0x892c, 0x88ee, 0x83b0, 0x8272, 0x8034, 0x81f6, 0x84b8, 0x857a, 0x873c, 0x86fe, 0xa9c0, 0xa802, 0xaa44, 0xab86, 0xaec8, 0xaf0a, 0xad4c, 0xac8e, 0xa7d0, 0xa612, 0xa454, 0xa596, 0xa0d8, 0xa11a, 0xa35c, 0xa29e, 0xb5e0, 0xb422, 0xb664, 0xb7a6, 0xb2e8, 0xb32a, 0xb16c, 0xb0ae, 0xbbf0, 0xba32, 0xb874, 0xb9b6, 0xbcf8, 0xbd3a, 0xbf7c, 0xbebe, }; static inline void prefetch_table(const void *tab, size_t len) { const volatile byte *vtab = tab; size_t i; for (i = 0; i < len; i += 8 * 32) { (void)vtab[i + 0 * 32]; (void)vtab[i + 1 * 32]; (void)vtab[i + 2 * 32]; (void)vtab[i + 3 * 32]; (void)vtab[i + 4 * 32]; (void)vtab[i + 5 * 32]; (void)vtab[i + 6 * 32]; (void)vtab[i + 7 * 32]; } (void)vtab[len - 1]; } static inline void do_prefetch_tables (const void *gcmM, size_t gcmM_size) { prefetch_table(gcmM, gcmM_size); prefetch_table(gcmR, sizeof(gcmR)); } #ifdef GCM_TABLES_USE_U64 static void bshift (u64 * b0, u64 * b1) { u64 t[2], mask; t[0] = *b0; t[1] = *b1; mask = -(t[1] & 1) & 0xe1; mask <<= 56; *b1 = (t[1] >> 1) ^ (t[0] << 63); *b0 = (t[0] >> 1) ^ mask; } static void do_fillM (unsigned char *h, u64 *M) { int i, j; M[0 + 0] = 0; M[0 + 16] = 0; M[8 + 0] = buf_get_be64 (h + 0); M[8 + 16] = buf_get_be64 (h + 8); for (i = 4; i > 0; i /= 2) { M[i + 0] = M[2 * i + 0]; M[i + 16] = M[2 * i + 16]; bshift (&M[i], &M[i + 16]); } for (i = 2; i < 16; i *= 2) for (j = 1; j < i; j++) { M[(i + j) + 0] = M[i + 0] ^ M[j + 0]; M[(i + j) + 16] = M[i + 16] ^ M[j + 16]; } for (i = 0; i < 16; i++) { M[i + 32] = (M[i + 0] >> 4) ^ ((u64) gcmR[(M[i + 16] & 0xf) << 4] << 48); M[i + 48] = (M[i + 16] >> 4) ^ (M[i + 0] << 60); } } static inline unsigned int do_ghash (unsigned char *result, const unsigned char *buf, const u64 *gcmM) { u64 V[2]; u64 tmp[2]; const u64 *M; u64 T; u32 A; int i; cipher_block_xor (V, result, buf, 16); V[0] = be_bswap64 (V[0]); V[1] = be_bswap64 (V[1]); /* First round can be manually tweaked based on fact that 'tmp' is zero. */ M = &gcmM[(V[1] & 0xf) + 32]; V[1] >>= 4; tmp[0] = M[0]; tmp[1] = M[16]; tmp[0] ^= gcmM[(V[1] & 0xf) + 0]; tmp[1] ^= gcmM[(V[1] & 0xf) + 16]; V[1] >>= 4; i = 6; while (1) { M = &gcmM[(V[1] & 0xf) + 32]; V[1] >>= 4; A = tmp[1] & 0xff; T = tmp[0]; tmp[0] = (T >> 8) ^ ((u64) gcmR[A] << 48) ^ gcmM[(V[1] & 0xf) + 0]; tmp[1] = (T << 56) ^ (tmp[1] >> 8) ^ gcmM[(V[1] & 0xf) + 16]; tmp[0] ^= M[0]; tmp[1] ^= M[16]; if (i == 0) break; V[1] >>= 4; --i; } i = 7; while (1) { M = &gcmM[(V[0] & 0xf) + 32]; V[0] >>= 4; A = tmp[1] & 0xff; T = tmp[0]; tmp[0] = (T >> 8) ^ ((u64) gcmR[A] << 48) ^ gcmM[(V[0] & 0xf) + 0]; tmp[1] = (T << 56) ^ (tmp[1] >> 8) ^ gcmM[(V[0] & 0xf) + 16]; tmp[0] ^= M[0]; tmp[1] ^= M[16]; if (i == 0) break; V[0] >>= 4; --i; } buf_put_be64 (result + 0, tmp[0]); buf_put_be64 (result + 8, tmp[1]); return (sizeof(V) + sizeof(T) + sizeof(tmp) + sizeof(int)*2 + sizeof(void*)*5); } #else /*!GCM_TABLES_USE_U64*/ static void bshift (u32 * M, int i) { u32 t[4], mask; t[0] = M[i * 4 + 0]; t[1] = M[i * 4 + 1]; t[2] = M[i * 4 + 2]; t[3] = M[i * 4 + 3]; mask = -(t[3] & 1) & 0xe1; M[i * 4 + 3] = (t[3] >> 1) ^ (t[2] << 31); M[i * 4 + 2] = (t[2] >> 1) ^ (t[1] << 31); M[i * 4 + 1] = (t[1] >> 1) ^ (t[0] << 31); M[i * 4 + 0] = (t[0] >> 1) ^ (mask << 24); } static void do_fillM (unsigned char *h, u32 *M) { int i, j; M[0 * 4 + 0] = 0; M[0 * 4 + 1] = 0; M[0 * 4 + 2] = 0; M[0 * 4 + 3] = 0; M[8 * 4 + 0] = buf_get_be32 (h + 0); M[8 * 4 + 1] = buf_get_be32 (h + 4); M[8 * 4 + 2] = buf_get_be32 (h + 8); M[8 * 4 + 3] = buf_get_be32 (h + 12); for (i = 4; i > 0; i /= 2) { M[i * 4 + 0] = M[2 * i * 4 + 0]; M[i * 4 + 1] = M[2 * i * 4 + 1]; M[i * 4 + 2] = M[2 * i * 4 + 2]; M[i * 4 + 3] = M[2 * i * 4 + 3]; bshift (M, i); } for (i = 2; i < 16; i *= 2) for (j = 1; j < i; j++) { M[(i + j) * 4 + 0] = M[i * 4 + 0] ^ M[j * 4 + 0]; M[(i + j) * 4 + 1] = M[i * 4 + 1] ^ M[j * 4 + 1]; M[(i + j) * 4 + 2] = M[i * 4 + 2] ^ M[j * 4 + 2]; M[(i + j) * 4 + 3] = M[i * 4 + 3] ^ M[j * 4 + 3]; } for (i = 0; i < 4 * 16; i += 4) { M[i + 0 + 64] = (M[i + 0] >> 4) ^ ((u64) gcmR[(M[i + 3] << 4) & 0xf0] << 16); M[i + 1 + 64] = (M[i + 1] >> 4) ^ (M[i + 0] << 28); M[i + 2 + 64] = (M[i + 2] >> 4) ^ (M[i + 1] << 28); M[i + 3 + 64] = (M[i + 3] >> 4) ^ (M[i + 2] << 28); } } static inline unsigned int do_ghash (unsigned char *result, const unsigned char *buf, const u32 *gcmM) { byte V[16]; u32 tmp[4]; u32 v; const u32 *M, *m; u32 T[3]; int i; cipher_block_xor (V, result, buf, 16); /* V is big-endian */ /* First round can be manually tweaked based on fact that 'tmp' is zero. */ i = 15; v = V[i]; M = &gcmM[(v & 0xf) * 4 + 64]; v = (v & 0xf0) >> 4; m = &gcmM[v * 4]; v = V[--i]; tmp[0] = M[0] ^ m[0]; tmp[1] = M[1] ^ m[1]; tmp[2] = M[2] ^ m[2]; tmp[3] = M[3] ^ m[3]; while (1) { M = &gcmM[(v & 0xf) * 4 + 64]; v = (v & 0xf0) >> 4; m = &gcmM[v * 4]; T[0] = tmp[0]; T[1] = tmp[1]; T[2] = tmp[2]; tmp[0] = (T[0] >> 8) ^ ((u32) gcmR[tmp[3] & 0xff] << 16) ^ m[0]; tmp[1] = (T[0] << 24) ^ (tmp[1] >> 8) ^ m[1]; tmp[2] = (T[1] << 24) ^ (tmp[2] >> 8) ^ m[2]; tmp[3] = (T[2] << 24) ^ (tmp[3] >> 8) ^ m[3]; tmp[0] ^= M[0]; tmp[1] ^= M[1]; tmp[2] ^= M[2]; tmp[3] ^= M[3]; if (i == 0) break; v = V[--i]; } buf_put_be32 (result + 0, tmp[0]); buf_put_be32 (result + 4, tmp[1]); buf_put_be32 (result + 8, tmp[2]); buf_put_be32 (result + 12, tmp[3]); return (sizeof(V) + sizeof(T) + sizeof(tmp) + sizeof(int)*2 + sizeof(void*)*6); } #endif /*!GCM_TABLES_USE_U64*/ #define fillM(c) \ do_fillM (c->u_mode.gcm.u_ghash_key.key, c->u_mode.gcm.gcm_table) #define GHASH(c, result, buf) do_ghash (result, buf, c->u_mode.gcm.gcm_table) #define prefetch_tables(c) \ do_prefetch_tables(c->u_mode.gcm.gcm_table, sizeof(c->u_mode.gcm.gcm_table)) #else static unsigned long bshift (unsigned long *b) { unsigned long c; int i; c = b[3] & 1; for (i = 3; i > 0; i--) { b[i] = (b[i] >> 1) | (b[i - 1] << 31); } b[i] >>= 1; return c; } static unsigned int do_ghash (unsigned char *hsub, unsigned char *result, const unsigned char *buf) { unsigned long V[4]; int i, j; byte *p; #ifdef WORDS_BIGENDIAN p = result; #else unsigned long T[4]; cipher_block_xor (V, result, buf, 16); for (i = 0; i < 4; i++) { V[i] = (V[i] & 0x00ff00ff) << 8 | (V[i] & 0xff00ff00) >> 8; V[i] = (V[i] & 0x0000ffff) << 16 | (V[i] & 0xffff0000) >> 16; } p = (byte *) T; #endif memset (p, 0, 16); for (i = 0; i < 16; i++) { for (j = 0x80; j; j >>= 1) { if (hsub[i] & j) cipher_block_xor (p, p, V, 16); if (bshift (V)) V[0] ^= 0xe1000000; } } #ifndef WORDS_BIGENDIAN for (i = 0, p = (byte *) T; i < 16; i += 4, p += 4) { result[i + 0] = p[3]; result[i + 1] = p[2]; result[i + 2] = p[1]; result[i + 3] = p[0]; } #endif return (sizeof(V) + sizeof(T) + sizeof(int)*2 + sizeof(void*)*5); } #define fillM(c) do { } while (0) #define GHASH(c, result, buf) do_ghash (c->u_mode.gcm.u_ghash_key.key, result, buf) #define prefetch_tables(c) do {} while (0) #endif /* !GCM_USE_TABLES */ static unsigned int ghash_internal (gcry_cipher_hd_t c, byte *result, const byte *buf, size_t nblocks) { const unsigned int blocksize = GCRY_GCM_BLOCK_LEN; unsigned int burn = 0; prefetch_tables (c); while (nblocks) { burn = GHASH (c, result, buf); buf += blocksize; nblocks--; } return burn + (burn ? 5*sizeof(void*) : 0); } static void setupM (gcry_cipher_hd_t c) { #if defined(GCM_USE_INTEL_PCLMUL) || defined(GCM_USE_ARM_PMULL) unsigned int features = _gcry_get_hw_features (); #endif if (0) ; #ifdef GCM_USE_INTEL_PCLMUL else if (features & HWF_INTEL_PCLMUL) { c->u_mode.gcm.ghash_fn = _gcry_ghash_intel_pclmul; _gcry_ghash_setup_intel_pclmul (c); } #endif #ifdef GCM_USE_ARM_PMULL else if (features & HWF_ARM_PMULL) { c->u_mode.gcm.ghash_fn = ghash_armv8_ce_pmull; ghash_setup_armv8_ce_pmull (c); } #endif #ifdef GCM_USE_ARM_NEON else if (features & HWF_ARM_NEON) { c->u_mode.gcm.ghash_fn = ghash_armv7_neon; ghash_setup_armv7_neon (c); } #endif else { c->u_mode.gcm.ghash_fn = ghash_internal; fillM (c); } } static inline void gcm_bytecounter_add (u32 ctr[2], size_t add) { if (sizeof(add) > sizeof(u32)) { u32 high_add = ((add >> 31) >> 1) & 0xffffffff; ctr[1] += high_add; } ctr[0] += add; if (ctr[0] >= add) return; ++ctr[1]; } static inline u32 gcm_add32_be128 (byte *ctr, unsigned int add) { /* 'ctr' must be aligned to four bytes. */ const unsigned int blocksize = GCRY_GCM_BLOCK_LEN; u32 *pval = (u32 *)(void *)(ctr + blocksize - sizeof(u32)); u32 val; val = be_bswap32(*pval) + add; *pval = be_bswap32(val); return val; /* return result as host-endian value */ } static inline int gcm_check_datalen (u32 ctr[2]) { /* len(plaintext) <= 2^39-256 bits == 2^36-32 bytes == 2^32-2 blocks */ if (ctr[1] > 0xfU) return 0; if (ctr[1] < 0xfU) return 1; if (ctr[0] <= 0xffffffe0U) return 1; return 0; } static inline int gcm_check_aadlen_or_ivlen (u32 ctr[2]) { /* len(aad/iv) <= 2^64-1 bits ~= 2^61-1 bytes */ if (ctr[1] > 0x1fffffffU) return 0; if (ctr[1] < 0x1fffffffU) return 1; if (ctr[0] <= 0xffffffffU) return 1; return 0; } static void do_ghash_buf(gcry_cipher_hd_t c, byte *hash, const byte *buf, size_t buflen, int do_padding) { unsigned int blocksize = GCRY_GCM_BLOCK_LEN; unsigned int unused = c->u_mode.gcm.mac_unused; ghash_fn_t ghash_fn = c->u_mode.gcm.ghash_fn; size_t nblocks, n; unsigned int burn = 0; if (buflen == 0 && (unused == 0 || !do_padding)) return; do { if (buflen > 0 && (buflen + unused < blocksize || unused > 0)) { n = blocksize - unused; n = n < buflen ? n : buflen; buf_cpy (&c->u_mode.gcm.macbuf[unused], buf, n); unused += n; buf += n; buflen -= n; } if (!buflen) { if (!do_padding) break; n = blocksize - unused; if (n > 0) { memset (&c->u_mode.gcm.macbuf[unused], 0, n); unused = blocksize; } } if (unused > 0) { gcry_assert (unused == blocksize); /* Process one block from macbuf. */ burn = ghash_fn (c, hash, c->u_mode.gcm.macbuf, 1); unused = 0; } nblocks = buflen / blocksize; if (nblocks) { burn = ghash_fn (c, hash, buf, nblocks); buf += blocksize * nblocks; buflen -= blocksize * nblocks; } } while (buflen > 0); c->u_mode.gcm.mac_unused = unused; if (burn) _gcry_burn_stack (burn); } static gcry_err_code_t gcm_ctr_encrypt (gcry_cipher_hd_t c, byte *outbuf, size_t outbuflen, const byte *inbuf, size_t inbuflen) { gcry_err_code_t err = 0; while (inbuflen) { u32 nblocks_to_overflow; u32 num_ctr_increments; u32 curr_ctr_low; size_t currlen = inbuflen; byte ctr_copy[GCRY_GCM_BLOCK_LEN]; int fix_ctr = 0; /* GCM CTR increments only least significant 32-bits, without carry * to upper 96-bits of counter. Using generic CTR implementation * directly would carry 32-bit overflow to upper 96-bit. Detect * if input length is long enough to cause overflow, and limit * input length so that CTR overflow happen but updated CTR value is * not used to encrypt further input. After overflow, upper 96 bits * of CTR are restored to cancel out modification done by generic CTR * encryption. */ if (inbuflen > c->unused) { curr_ctr_low = gcm_add32_be128 (c->u_ctr.ctr, 0); /* Number of CTR increments this inbuflen would cause. */ num_ctr_increments = (inbuflen - c->unused) / GCRY_GCM_BLOCK_LEN + !!((inbuflen - c->unused) % GCRY_GCM_BLOCK_LEN); if ((u32)(num_ctr_increments + curr_ctr_low) < curr_ctr_low) { nblocks_to_overflow = 0xffffffffU - curr_ctr_low + 1; currlen = nblocks_to_overflow * GCRY_GCM_BLOCK_LEN + c->unused; if (currlen > inbuflen) { currlen = inbuflen; } fix_ctr = 1; cipher_block_cpy(ctr_copy, c->u_ctr.ctr, GCRY_GCM_BLOCK_LEN); } } err = _gcry_cipher_ctr_encrypt(c, outbuf, outbuflen, inbuf, currlen); if (err != 0) return err; if (fix_ctr) { /* Lower 32-bits of CTR should now be zero. */ gcry_assert(gcm_add32_be128 (c->u_ctr.ctr, 0) == 0); /* Restore upper part of CTR. */ buf_cpy(c->u_ctr.ctr, ctr_copy, GCRY_GCM_BLOCK_LEN - sizeof(u32)); wipememory(ctr_copy, sizeof(ctr_copy)); } inbuflen -= currlen; inbuf += currlen; outbuflen -= currlen; outbuf += currlen; } return err; } gcry_err_code_t _gcry_cipher_gcm_encrypt (gcry_cipher_hd_t c, byte *outbuf, size_t outbuflen, const byte *inbuf, size_t inbuflen) { static const unsigned char zerobuf[MAX_BLOCKSIZE]; gcry_err_code_t err; if (c->spec->blocksize != GCRY_GCM_BLOCK_LEN) return GPG_ERR_CIPHER_ALGO; if (outbuflen < inbuflen) return GPG_ERR_BUFFER_TOO_SHORT; if (c->u_mode.gcm.datalen_over_limits) return GPG_ERR_INV_LENGTH; if (c->marks.tag || c->u_mode.gcm.ghash_data_finalized || !c->u_mode.gcm.ghash_fn) return GPG_ERR_INV_STATE; if (!c->marks.iv) _gcry_cipher_gcm_setiv (c, zerobuf, GCRY_GCM_BLOCK_LEN); if (c->u_mode.gcm.disallow_encryption_because_of_setiv_in_fips_mode) return GPG_ERR_INV_STATE; if (!c->u_mode.gcm.ghash_aad_finalized) { /* Start of encryption marks end of AAD stream. */ do_ghash_buf(c, c->u_mode.gcm.u_tag.tag, NULL, 0, 1); c->u_mode.gcm.ghash_aad_finalized = 1; } gcm_bytecounter_add(c->u_mode.gcm.datalen, inbuflen); if (!gcm_check_datalen(c->u_mode.gcm.datalen)) { c->u_mode.gcm.datalen_over_limits = 1; return GPG_ERR_INV_LENGTH; } while (inbuflen) { size_t currlen = inbuflen; /* Since checksumming is done after encryption, process input in 24KiB * chunks to keep data loaded in L1 cache for checksumming. */ if (currlen > 24 * 1024) currlen = 24 * 1024; err = gcm_ctr_encrypt(c, outbuf, outbuflen, inbuf, currlen); if (err != 0) return err; do_ghash_buf(c, c->u_mode.gcm.u_tag.tag, outbuf, currlen, 0); outbuf += currlen; inbuf += currlen; outbuflen -= currlen; inbuflen -= currlen; } return 0; } gcry_err_code_t _gcry_cipher_gcm_decrypt (gcry_cipher_hd_t c, byte *outbuf, size_t outbuflen, const byte *inbuf, size_t inbuflen) { static const unsigned char zerobuf[MAX_BLOCKSIZE]; gcry_err_code_t err; if (c->spec->blocksize != GCRY_GCM_BLOCK_LEN) return GPG_ERR_CIPHER_ALGO; if (outbuflen < inbuflen) return GPG_ERR_BUFFER_TOO_SHORT; if (c->u_mode.gcm.datalen_over_limits) return GPG_ERR_INV_LENGTH; if (c->marks.tag || c->u_mode.gcm.ghash_data_finalized || !c->u_mode.gcm.ghash_fn) return GPG_ERR_INV_STATE; if (!c->marks.iv) _gcry_cipher_gcm_setiv (c, zerobuf, GCRY_GCM_BLOCK_LEN); if (!c->u_mode.gcm.ghash_aad_finalized) { /* Start of decryption marks end of AAD stream. */ do_ghash_buf(c, c->u_mode.gcm.u_tag.tag, NULL, 0, 1); c->u_mode.gcm.ghash_aad_finalized = 1; } gcm_bytecounter_add(c->u_mode.gcm.datalen, inbuflen); if (!gcm_check_datalen(c->u_mode.gcm.datalen)) { c->u_mode.gcm.datalen_over_limits = 1; return GPG_ERR_INV_LENGTH; } while (inbuflen) { size_t currlen = inbuflen; /* Since checksumming is done before decryption, process input in * 24KiB chunks to keep data loaded in L1 cache for decryption. */ if (currlen > 24 * 1024) currlen = 24 * 1024; do_ghash_buf(c, c->u_mode.gcm.u_tag.tag, inbuf, currlen, 0); err = gcm_ctr_encrypt(c, outbuf, outbuflen, inbuf, currlen); if (err) return err; outbuf += currlen; inbuf += currlen; outbuflen -= currlen; inbuflen -= currlen; } return 0; } gcry_err_code_t _gcry_cipher_gcm_authenticate (gcry_cipher_hd_t c, const byte * aadbuf, size_t aadbuflen) { static const unsigned char zerobuf[MAX_BLOCKSIZE]; if (c->spec->blocksize != GCRY_GCM_BLOCK_LEN) return GPG_ERR_CIPHER_ALGO; if (c->u_mode.gcm.datalen_over_limits) return GPG_ERR_INV_LENGTH; if (c->marks.tag || c->u_mode.gcm.ghash_aad_finalized || c->u_mode.gcm.ghash_data_finalized || !c->u_mode.gcm.ghash_fn) return GPG_ERR_INV_STATE; if (!c->marks.iv) _gcry_cipher_gcm_setiv (c, zerobuf, GCRY_GCM_BLOCK_LEN); gcm_bytecounter_add(c->u_mode.gcm.aadlen, aadbuflen); if (!gcm_check_aadlen_or_ivlen(c->u_mode.gcm.aadlen)) { c->u_mode.gcm.datalen_over_limits = 1; return GPG_ERR_INV_LENGTH; } do_ghash_buf(c, c->u_mode.gcm.u_tag.tag, aadbuf, aadbuflen, 0); return 0; } void _gcry_cipher_gcm_setkey (gcry_cipher_hd_t c) { memset (c->u_mode.gcm.u_ghash_key.key, 0, GCRY_GCM_BLOCK_LEN); c->spec->encrypt (&c->context.c, c->u_mode.gcm.u_ghash_key.key, c->u_mode.gcm.u_ghash_key.key); setupM (c); } static gcry_err_code_t _gcry_cipher_gcm_initiv (gcry_cipher_hd_t c, const byte *iv, size_t ivlen) { memset (c->u_mode.gcm.aadlen, 0, sizeof(c->u_mode.gcm.aadlen)); memset (c->u_mode.gcm.datalen, 0, sizeof(c->u_mode.gcm.datalen)); memset (c->u_mode.gcm.u_tag.tag, 0, GCRY_GCM_BLOCK_LEN); c->u_mode.gcm.datalen_over_limits = 0; c->u_mode.gcm.ghash_data_finalized = 0; c->u_mode.gcm.ghash_aad_finalized = 0; if (ivlen == 0) return GPG_ERR_INV_LENGTH; if (ivlen != GCRY_GCM_BLOCK_LEN - 4) { u32 iv_bytes[2] = {0, 0}; u32 bitlengths[2][2]; if (!c->u_mode.gcm.ghash_fn) return GPG_ERR_INV_STATE; memset(c->u_ctr.ctr, 0, GCRY_GCM_BLOCK_LEN); gcm_bytecounter_add(iv_bytes, ivlen); if (!gcm_check_aadlen_or_ivlen(iv_bytes)) { c->u_mode.gcm.datalen_over_limits = 1; return GPG_ERR_INV_LENGTH; } do_ghash_buf(c, c->u_ctr.ctr, iv, ivlen, 1); /* iv length, 64-bit */ bitlengths[1][1] = be_bswap32(iv_bytes[0] << 3); bitlengths[1][0] = be_bswap32((iv_bytes[0] >> 29) | (iv_bytes[1] << 3)); /* zeros, 64-bit */ bitlengths[0][1] = 0; bitlengths[0][0] = 0; do_ghash_buf(c, c->u_ctr.ctr, (byte*)bitlengths, GCRY_GCM_BLOCK_LEN, 1); wipememory (iv_bytes, sizeof iv_bytes); wipememory (bitlengths, sizeof bitlengths); } else { /* 96-bit IV is handled differently. */ memcpy (c->u_ctr.ctr, iv, ivlen); c->u_ctr.ctr[12] = c->u_ctr.ctr[13] = c->u_ctr.ctr[14] = 0; c->u_ctr.ctr[15] = 1; } c->spec->encrypt (&c->context.c, c->u_mode.gcm.tagiv, c->u_ctr.ctr); gcm_add32_be128 (c->u_ctr.ctr, 1); c->unused = 0; c->marks.iv = 1; c->marks.tag = 0; return 0; } gcry_err_code_t _gcry_cipher_gcm_setiv (gcry_cipher_hd_t c, const byte *iv, size_t ivlen) { c->marks.iv = 0; c->marks.tag = 0; c->u_mode.gcm.disallow_encryption_because_of_setiv_in_fips_mode = 0; if (fips_mode ()) { /* Direct invocation of GCM setiv in FIPS mode disables encryption. */ c->u_mode.gcm.disallow_encryption_because_of_setiv_in_fips_mode = 1; } return _gcry_cipher_gcm_initiv (c, iv, ivlen); } #if 0 && TODO void _gcry_cipher_gcm_geniv (gcry_cipher_hd_t c, byte *ivout, size_t ivoutlen, const byte *nonce, size_t noncelen) { /* nonce: user provided part (might be null) */ /* noncelen: check if proper length (if nonce not null) */ /* ivout: iv used to initialize gcm, output to user */ /* ivoutlen: check correct size */ byte iv[IVLEN]; if (!ivout) return GPG_ERR_INV_ARG; if (ivoutlen != IVLEN) return GPG_ERR_INV_LENGTH; if (nonce != NULL && !is_nonce_ok_len(noncelen)) return GPG_ERR_INV_ARG; gcm_generate_iv(iv, nonce, noncelen); c->marks.iv = 0; c->marks.tag = 0; c->u_mode.gcm.disallow_encryption_because_of_setiv_in_fips_mode = 0; _gcry_cipher_gcm_initiv (c, iv, IVLEN); buf_cpy(ivout, iv, IVLEN); wipememory(iv, sizeof(iv)); } #endif static int is_tag_length_valid(size_t taglen) { switch (taglen) { /* Allowed tag lengths from NIST SP 800-38D. */ case 128 / 8: /* GCRY_GCM_BLOCK_LEN */ case 120 / 8: case 112 / 8: case 104 / 8: case 96 / 8: case 64 / 8: case 32 / 8: return 1; default: return 0; } } static gcry_err_code_t _gcry_cipher_gcm_tag (gcry_cipher_hd_t c, byte * outbuf, size_t outbuflen, int check) { if (!(is_tag_length_valid (outbuflen) || outbuflen >= GCRY_GCM_BLOCK_LEN)) return GPG_ERR_INV_LENGTH; if (c->u_mode.gcm.datalen_over_limits) return GPG_ERR_INV_LENGTH; if (!c->marks.tag) { u32 bitlengths[2][2]; if (!c->u_mode.gcm.ghash_fn) return GPG_ERR_INV_STATE; /* aad length */ bitlengths[0][1] = be_bswap32(c->u_mode.gcm.aadlen[0] << 3); bitlengths[0][0] = be_bswap32((c->u_mode.gcm.aadlen[0] >> 29) | (c->u_mode.gcm.aadlen[1] << 3)); /* data length */ bitlengths[1][1] = be_bswap32(c->u_mode.gcm.datalen[0] << 3); bitlengths[1][0] = be_bswap32((c->u_mode.gcm.datalen[0] >> 29) | (c->u_mode.gcm.datalen[1] << 3)); /* Finalize data-stream. */ do_ghash_buf(c, c->u_mode.gcm.u_tag.tag, NULL, 0, 1); c->u_mode.gcm.ghash_aad_finalized = 1; c->u_mode.gcm.ghash_data_finalized = 1; /* Add bitlengths to tag. */ do_ghash_buf(c, c->u_mode.gcm.u_tag.tag, (byte*)bitlengths, GCRY_GCM_BLOCK_LEN, 1); cipher_block_xor (c->u_mode.gcm.u_tag.tag, c->u_mode.gcm.tagiv, c->u_mode.gcm.u_tag.tag, GCRY_GCM_BLOCK_LEN); c->marks.tag = 1; wipememory (bitlengths, sizeof (bitlengths)); wipememory (c->u_mode.gcm.macbuf, GCRY_GCM_BLOCK_LEN); wipememory (c->u_mode.gcm.tagiv, GCRY_GCM_BLOCK_LEN); wipememory (c->u_mode.gcm.aadlen, sizeof (c->u_mode.gcm.aadlen)); wipememory (c->u_mode.gcm.datalen, sizeof (c->u_mode.gcm.datalen)); } if (!check) { if (outbuflen > GCRY_GCM_BLOCK_LEN) outbuflen = GCRY_GCM_BLOCK_LEN; /* NB: We already checked that OUTBUF is large enough to hold * the result or has valid truncated length. */ memcpy (outbuf, c->u_mode.gcm.u_tag.tag, outbuflen); } else { /* OUTBUFLEN gives the length of the user supplied tag in OUTBUF * and thus we need to compare its length first. */ if (!is_tag_length_valid (outbuflen) || !buf_eq_const (outbuf, c->u_mode.gcm.u_tag.tag, outbuflen)) return GPG_ERR_CHECKSUM; } return 0; } gcry_err_code_t _gcry_cipher_gcm_get_tag (gcry_cipher_hd_t c, unsigned char *outtag, size_t taglen) { /* Outputting authentication tag is part of encryption. */ if (c->u_mode.gcm.disallow_encryption_because_of_setiv_in_fips_mode) return GPG_ERR_INV_STATE; return _gcry_cipher_gcm_tag (c, outtag, taglen, 0); } gcry_err_code_t _gcry_cipher_gcm_check_tag (gcry_cipher_hd_t c, const unsigned char *intag, size_t taglen) { return _gcry_cipher_gcm_tag (c, (unsigned char *) intag, taglen, 1); }
./CrossVul/dataset_final_sorted/CWE-310/c/bad_892_0
crossvul-cpp_data_bad_3783_2
/* * Copyright (C) 2007 Oracle. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License v2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 021110-1307, USA. */ #include <linux/kernel.h> #include <linux/bio.h> #include <linux/buffer_head.h> #include <linux/file.h> #include <linux/fs.h> #include <linux/pagemap.h> #include <linux/highmem.h> #include <linux/time.h> #include <linux/init.h> #include <linux/string.h> #include <linux/backing-dev.h> #include <linux/mpage.h> #include <linux/swap.h> #include <linux/writeback.h> #include <linux/statfs.h> #include <linux/compat.h> #include <linux/bit_spinlock.h> #include <linux/xattr.h> #include <linux/posix_acl.h> #include <linux/falloc.h> #include <linux/slab.h> #include <linux/ratelimit.h> #include <linux/mount.h> #include "compat.h" #include "ctree.h" #include "disk-io.h" #include "transaction.h" #include "btrfs_inode.h" #include "ioctl.h" #include "print-tree.h" #include "ordered-data.h" #include "xattr.h" #include "tree-log.h" #include "volumes.h" #include "compression.h" #include "locking.h" #include "free-space-cache.h" #include "inode-map.h" struct btrfs_iget_args { u64 ino; struct btrfs_root *root; }; static const struct inode_operations btrfs_dir_inode_operations; static const struct inode_operations btrfs_symlink_inode_operations; static const struct inode_operations btrfs_dir_ro_inode_operations; static const struct inode_operations btrfs_special_inode_operations; static const struct inode_operations btrfs_file_inode_operations; static const struct address_space_operations btrfs_aops; static const struct address_space_operations btrfs_symlink_aops; static const struct file_operations btrfs_dir_file_operations; static struct extent_io_ops btrfs_extent_io_ops; static struct kmem_cache *btrfs_inode_cachep; static struct kmem_cache *btrfs_delalloc_work_cachep; struct kmem_cache *btrfs_trans_handle_cachep; struct kmem_cache *btrfs_transaction_cachep; struct kmem_cache *btrfs_path_cachep; struct kmem_cache *btrfs_free_space_cachep; #define S_SHIFT 12 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = { [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE, [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR, [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV, [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV, [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO, [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK, [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK, }; static int btrfs_setsize(struct inode *inode, loff_t newsize); static int btrfs_truncate(struct inode *inode); static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent); static noinline int cow_file_range(struct inode *inode, struct page *locked_page, u64 start, u64 end, int *page_started, unsigned long *nr_written, int unlock); static struct extent_map *create_pinned_em(struct inode *inode, u64 start, u64 len, u64 orig_start, u64 block_start, u64 block_len, u64 orig_block_len, int type); static int btrfs_init_inode_security(struct btrfs_trans_handle *trans, struct inode *inode, struct inode *dir, const struct qstr *qstr) { int err; err = btrfs_init_acl(trans, inode, dir); if (!err) err = btrfs_xattr_security_init(trans, inode, dir, qstr); return err; } /* * this does all the hard work for inserting an inline extent into * the btree. The caller should have done a btrfs_drop_extents so that * no overlapping inline items exist in the btree */ static noinline int insert_inline_extent(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *inode, u64 start, size_t size, size_t compressed_size, int compress_type, struct page **compressed_pages) { struct btrfs_key key; struct btrfs_path *path; struct extent_buffer *leaf; struct page *page = NULL; char *kaddr; unsigned long ptr; struct btrfs_file_extent_item *ei; int err = 0; int ret; size_t cur_size = size; size_t datasize; unsigned long offset; if (compressed_size && compressed_pages) cur_size = compressed_size; path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->leave_spinning = 1; key.objectid = btrfs_ino(inode); key.offset = start; btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY); datasize = btrfs_file_extent_calc_inline_size(cur_size); inode_add_bytes(inode, size); ret = btrfs_insert_empty_item(trans, root, path, &key, datasize); if (ret) { err = ret; goto fail; } leaf = path->nodes[0]; ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); btrfs_set_file_extent_generation(leaf, ei, trans->transid); btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE); btrfs_set_file_extent_encryption(leaf, ei, 0); btrfs_set_file_extent_other_encoding(leaf, ei, 0); btrfs_set_file_extent_ram_bytes(leaf, ei, size); ptr = btrfs_file_extent_inline_start(ei); if (compress_type != BTRFS_COMPRESS_NONE) { struct page *cpage; int i = 0; while (compressed_size > 0) { cpage = compressed_pages[i]; cur_size = min_t(unsigned long, compressed_size, PAGE_CACHE_SIZE); kaddr = kmap_atomic(cpage); write_extent_buffer(leaf, kaddr, ptr, cur_size); kunmap_atomic(kaddr); i++; ptr += cur_size; compressed_size -= cur_size; } btrfs_set_file_extent_compression(leaf, ei, compress_type); } else { page = find_get_page(inode->i_mapping, start >> PAGE_CACHE_SHIFT); btrfs_set_file_extent_compression(leaf, ei, 0); kaddr = kmap_atomic(page); offset = start & (PAGE_CACHE_SIZE - 1); write_extent_buffer(leaf, kaddr + offset, ptr, size); kunmap_atomic(kaddr); page_cache_release(page); } btrfs_mark_buffer_dirty(leaf); btrfs_free_path(path); /* * we're an inline extent, so nobody can * extend the file past i_size without locking * a page we already have locked. * * We must do any isize and inode updates * before we unlock the pages. Otherwise we * could end up racing with unlink. */ BTRFS_I(inode)->disk_i_size = inode->i_size; ret = btrfs_update_inode(trans, root, inode); return ret; fail: btrfs_free_path(path); return err; } /* * conditionally insert an inline extent into the file. This * does the checks required to make sure the data is small enough * to fit as an inline extent. */ static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *inode, u64 start, u64 end, size_t compressed_size, int compress_type, struct page **compressed_pages) { u64 isize = i_size_read(inode); u64 actual_end = min(end + 1, isize); u64 inline_len = actual_end - start; u64 aligned_end = (end + root->sectorsize - 1) & ~((u64)root->sectorsize - 1); u64 data_len = inline_len; int ret; if (compressed_size) data_len = compressed_size; if (start > 0 || actual_end >= PAGE_CACHE_SIZE || data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) || (!compressed_size && (actual_end & (root->sectorsize - 1)) == 0) || end + 1 < isize || data_len > root->fs_info->max_inline) { return 1; } ret = btrfs_drop_extents(trans, root, inode, start, aligned_end, 1); if (ret) return ret; if (isize > actual_end) inline_len = min_t(u64, isize, actual_end); ret = insert_inline_extent(trans, root, inode, start, inline_len, compressed_size, compress_type, compressed_pages); if (ret && ret != -ENOSPC) { btrfs_abort_transaction(trans, root, ret); return ret; } else if (ret == -ENOSPC) { return 1; } btrfs_delalloc_release_metadata(inode, end + 1 - start); btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0); return 0; } struct async_extent { u64 start; u64 ram_size; u64 compressed_size; struct page **pages; unsigned long nr_pages; int compress_type; struct list_head list; }; struct async_cow { struct inode *inode; struct btrfs_root *root; struct page *locked_page; u64 start; u64 end; struct list_head extents; struct btrfs_work work; }; static noinline int add_async_extent(struct async_cow *cow, u64 start, u64 ram_size, u64 compressed_size, struct page **pages, unsigned long nr_pages, int compress_type) { struct async_extent *async_extent; async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS); BUG_ON(!async_extent); /* -ENOMEM */ async_extent->start = start; async_extent->ram_size = ram_size; async_extent->compressed_size = compressed_size; async_extent->pages = pages; async_extent->nr_pages = nr_pages; async_extent->compress_type = compress_type; list_add_tail(&async_extent->list, &cow->extents); return 0; } /* * we create compressed extents in two phases. The first * phase compresses a range of pages that have already been * locked (both pages and state bits are locked). * * This is done inside an ordered work queue, and the compression * is spread across many cpus. The actual IO submission is step * two, and the ordered work queue takes care of making sure that * happens in the same order things were put onto the queue by * writepages and friends. * * If this code finds it can't get good compression, it puts an * entry onto the work queue to write the uncompressed bytes. This * makes sure that both compressed inodes and uncompressed inodes * are written in the same order that the flusher thread sent them * down. */ static noinline int compress_file_range(struct inode *inode, struct page *locked_page, u64 start, u64 end, struct async_cow *async_cow, int *num_added) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; u64 num_bytes; u64 blocksize = root->sectorsize; u64 actual_end; u64 isize = i_size_read(inode); int ret = 0; struct page **pages = NULL; unsigned long nr_pages; unsigned long nr_pages_ret = 0; unsigned long total_compressed = 0; unsigned long total_in = 0; unsigned long max_compressed = 128 * 1024; unsigned long max_uncompressed = 128 * 1024; int i; int will_compress; int compress_type = root->fs_info->compress_type; /* if this is a small write inside eof, kick off a defrag */ if ((end - start + 1) < 16 * 1024 && (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size)) btrfs_add_inode_defrag(NULL, inode); actual_end = min_t(u64, isize, end + 1); again: will_compress = 0; nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1; nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE); /* * we don't want to send crud past the end of i_size through * compression, that's just a waste of CPU time. So, if the * end of the file is before the start of our current * requested range of bytes, we bail out to the uncompressed * cleanup code that can deal with all of this. * * It isn't really the fastest way to fix things, but this is a * very uncommon corner. */ if (actual_end <= start) goto cleanup_and_bail_uncompressed; total_compressed = actual_end - start; /* we want to make sure that amount of ram required to uncompress * an extent is reasonable, so we limit the total size in ram * of a compressed extent to 128k. This is a crucial number * because it also controls how easily we can spread reads across * cpus for decompression. * * We also want to make sure the amount of IO required to do * a random read is reasonably small, so we limit the size of * a compressed extent to 128k. */ total_compressed = min(total_compressed, max_uncompressed); num_bytes = (end - start + blocksize) & ~(blocksize - 1); num_bytes = max(blocksize, num_bytes); total_in = 0; ret = 0; /* * we do compression for mount -o compress and when the * inode has not been flagged as nocompress. This flag can * change at any time if we discover bad compression ratios. */ if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) && (btrfs_test_opt(root, COMPRESS) || (BTRFS_I(inode)->force_compress) || (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) { WARN_ON(pages); pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS); if (!pages) { /* just bail out to the uncompressed code */ goto cont; } if (BTRFS_I(inode)->force_compress) compress_type = BTRFS_I(inode)->force_compress; ret = btrfs_compress_pages(compress_type, inode->i_mapping, start, total_compressed, pages, nr_pages, &nr_pages_ret, &total_in, &total_compressed, max_compressed); if (!ret) { unsigned long offset = total_compressed & (PAGE_CACHE_SIZE - 1); struct page *page = pages[nr_pages_ret - 1]; char *kaddr; /* zero the tail end of the last page, we might be * sending it down to disk */ if (offset) { kaddr = kmap_atomic(page); memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset); kunmap_atomic(kaddr); } will_compress = 1; } } cont: if (start == 0) { trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { ret = PTR_ERR(trans); trans = NULL; goto cleanup_and_out; } trans->block_rsv = &root->fs_info->delalloc_block_rsv; /* lets try to make an inline extent */ if (ret || total_in < (actual_end - start)) { /* we didn't compress the entire range, try * to make an uncompressed inline extent. */ ret = cow_file_range_inline(trans, root, inode, start, end, 0, 0, NULL); } else { /* try making a compressed inline extent */ ret = cow_file_range_inline(trans, root, inode, start, end, total_compressed, compress_type, pages); } if (ret <= 0) { /* * inline extent creation worked or returned error, * we don't need to create any more async work items. * Unlock and free up our temp pages. */ extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, start, end, NULL, EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY | EXTENT_CLEAR_DELALLOC | EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK); btrfs_end_transaction(trans, root); goto free_pages_out; } btrfs_end_transaction(trans, root); } if (will_compress) { /* * we aren't doing an inline extent round the compressed size * up to a block size boundary so the allocator does sane * things */ total_compressed = (total_compressed + blocksize - 1) & ~(blocksize - 1); /* * one last check to make sure the compression is really a * win, compare the page count read with the blocks on disk */ total_in = (total_in + PAGE_CACHE_SIZE - 1) & ~(PAGE_CACHE_SIZE - 1); if (total_compressed >= total_in) { will_compress = 0; } else { num_bytes = total_in; } } if (!will_compress && pages) { /* * the compression code ran but failed to make things smaller, * free any pages it allocated and our page pointer array */ for (i = 0; i < nr_pages_ret; i++) { WARN_ON(pages[i]->mapping); page_cache_release(pages[i]); } kfree(pages); pages = NULL; total_compressed = 0; nr_pages_ret = 0; /* flag the file so we don't compress in the future */ if (!btrfs_test_opt(root, FORCE_COMPRESS) && !(BTRFS_I(inode)->force_compress)) { BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS; } } if (will_compress) { *num_added += 1; /* the async work queues will take care of doing actual * allocation on disk for these compressed pages, * and will submit them to the elevator. */ add_async_extent(async_cow, start, num_bytes, total_compressed, pages, nr_pages_ret, compress_type); if (start + num_bytes < end) { start += num_bytes; pages = NULL; cond_resched(); goto again; } } else { cleanup_and_bail_uncompressed: /* * No compression, but we still need to write the pages in * the file we've been given so far. redirty the locked * page if it corresponds to our extent and set things up * for the async work queue to run cow_file_range to do * the normal delalloc dance */ if (page_offset(locked_page) >= start && page_offset(locked_page) <= end) { __set_page_dirty_nobuffers(locked_page); /* unlocked later on in the async handlers */ } add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0, BTRFS_COMPRESS_NONE); *num_added += 1; } out: return ret; free_pages_out: for (i = 0; i < nr_pages_ret; i++) { WARN_ON(pages[i]->mapping); page_cache_release(pages[i]); } kfree(pages); goto out; cleanup_and_out: extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, start, end, NULL, EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY | EXTENT_CLEAR_DELALLOC | EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK); if (!trans || IS_ERR(trans)) btrfs_error(root->fs_info, ret, "Failed to join transaction"); else btrfs_abort_transaction(trans, root, ret); goto free_pages_out; } /* * phase two of compressed writeback. This is the ordered portion * of the code, which only gets called in the order the work was * queued. We walk all the async extents created by compress_file_range * and send them down to the disk. */ static noinline int submit_compressed_extents(struct inode *inode, struct async_cow *async_cow) { struct async_extent *async_extent; u64 alloc_hint = 0; struct btrfs_trans_handle *trans; struct btrfs_key ins; struct extent_map *em; struct btrfs_root *root = BTRFS_I(inode)->root; struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; struct extent_io_tree *io_tree; int ret = 0; if (list_empty(&async_cow->extents)) return 0; while (!list_empty(&async_cow->extents)) { async_extent = list_entry(async_cow->extents.next, struct async_extent, list); list_del(&async_extent->list); io_tree = &BTRFS_I(inode)->io_tree; retry: /* did the compression code fall back to uncompressed IO? */ if (!async_extent->pages) { int page_started = 0; unsigned long nr_written = 0; lock_extent(io_tree, async_extent->start, async_extent->start + async_extent->ram_size - 1); /* allocate blocks */ ret = cow_file_range(inode, async_cow->locked_page, async_extent->start, async_extent->start + async_extent->ram_size - 1, &page_started, &nr_written, 0); /* JDM XXX */ /* * if page_started, cow_file_range inserted an * inline extent and took care of all the unlocking * and IO for us. Otherwise, we need to submit * all those pages down to the drive. */ if (!page_started && !ret) extent_write_locked_range(io_tree, inode, async_extent->start, async_extent->start + async_extent->ram_size - 1, btrfs_get_extent, WB_SYNC_ALL); kfree(async_extent); cond_resched(); continue; } lock_extent(io_tree, async_extent->start, async_extent->start + async_extent->ram_size - 1); trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { ret = PTR_ERR(trans); } else { trans->block_rsv = &root->fs_info->delalloc_block_rsv; ret = btrfs_reserve_extent(trans, root, async_extent->compressed_size, async_extent->compressed_size, 0, alloc_hint, &ins, 1); if (ret && ret != -ENOSPC) btrfs_abort_transaction(trans, root, ret); btrfs_end_transaction(trans, root); } if (ret) { int i; for (i = 0; i < async_extent->nr_pages; i++) { WARN_ON(async_extent->pages[i]->mapping); page_cache_release(async_extent->pages[i]); } kfree(async_extent->pages); async_extent->nr_pages = 0; async_extent->pages = NULL; unlock_extent(io_tree, async_extent->start, async_extent->start + async_extent->ram_size - 1); if (ret == -ENOSPC) goto retry; goto out_free; /* JDM: Requeue? */ } /* * here we're doing allocation and writeback of the * compressed pages */ btrfs_drop_extent_cache(inode, async_extent->start, async_extent->start + async_extent->ram_size - 1, 0); em = alloc_extent_map(); BUG_ON(!em); /* -ENOMEM */ em->start = async_extent->start; em->len = async_extent->ram_size; em->orig_start = em->start; em->block_start = ins.objectid; em->block_len = ins.offset; em->orig_block_len = ins.offset; em->bdev = root->fs_info->fs_devices->latest_bdev; em->compress_type = async_extent->compress_type; set_bit(EXTENT_FLAG_PINNED, &em->flags); set_bit(EXTENT_FLAG_COMPRESSED, &em->flags); em->generation = -1; while (1) { write_lock(&em_tree->lock); ret = add_extent_mapping(em_tree, em); if (!ret) list_move(&em->list, &em_tree->modified_extents); write_unlock(&em_tree->lock); if (ret != -EEXIST) { free_extent_map(em); break; } btrfs_drop_extent_cache(inode, async_extent->start, async_extent->start + async_extent->ram_size - 1, 0); } ret = btrfs_add_ordered_extent_compress(inode, async_extent->start, ins.objectid, async_extent->ram_size, ins.offset, BTRFS_ORDERED_COMPRESSED, async_extent->compress_type); BUG_ON(ret); /* -ENOMEM */ /* * clear dirty, set writeback and unlock the pages. */ extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, async_extent->start, async_extent->start + async_extent->ram_size - 1, NULL, EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC | EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK); ret = btrfs_submit_compressed_write(inode, async_extent->start, async_extent->ram_size, ins.objectid, ins.offset, async_extent->pages, async_extent->nr_pages); BUG_ON(ret); /* -ENOMEM */ alloc_hint = ins.objectid + ins.offset; kfree(async_extent); cond_resched(); } ret = 0; out: return ret; out_free: kfree(async_extent); goto out; } static u64 get_extent_allocation_hint(struct inode *inode, u64 start, u64 num_bytes) { struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; struct extent_map *em; u64 alloc_hint = 0; read_lock(&em_tree->lock); em = search_extent_mapping(em_tree, start, num_bytes); if (em) { /* * if block start isn't an actual block number then find the * first block in this inode and use that as a hint. If that * block is also bogus then just don't worry about it. */ if (em->block_start >= EXTENT_MAP_LAST_BYTE) { free_extent_map(em); em = search_extent_mapping(em_tree, 0, 0); if (em && em->block_start < EXTENT_MAP_LAST_BYTE) alloc_hint = em->block_start; if (em) free_extent_map(em); } else { alloc_hint = em->block_start; free_extent_map(em); } } read_unlock(&em_tree->lock); return alloc_hint; } /* * when extent_io.c finds a delayed allocation range in the file, * the call backs end up in this code. The basic idea is to * allocate extents on disk for the range, and create ordered data structs * in ram to track those extents. * * locked_page is the page that writepage had locked already. We use * it to make sure we don't do extra locks or unlocks. * * *page_started is set to one if we unlock locked_page and do everything * required to start IO on it. It may be clean and already done with * IO when we return. */ static noinline int __cow_file_range(struct btrfs_trans_handle *trans, struct inode *inode, struct btrfs_root *root, struct page *locked_page, u64 start, u64 end, int *page_started, unsigned long *nr_written, int unlock) { u64 alloc_hint = 0; u64 num_bytes; unsigned long ram_size; u64 disk_num_bytes; u64 cur_alloc_size; u64 blocksize = root->sectorsize; struct btrfs_key ins; struct extent_map *em; struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; int ret = 0; BUG_ON(btrfs_is_free_space_inode(inode)); num_bytes = (end - start + blocksize) & ~(blocksize - 1); num_bytes = max(blocksize, num_bytes); disk_num_bytes = num_bytes; /* if this is a small write inside eof, kick off defrag */ if (num_bytes < 64 * 1024 && (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size)) btrfs_add_inode_defrag(trans, inode); if (start == 0) { /* lets try to make an inline extent */ ret = cow_file_range_inline(trans, root, inode, start, end, 0, 0, NULL); if (ret == 0) { extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, start, end, NULL, EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC | EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK); *nr_written = *nr_written + (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE; *page_started = 1; goto out; } else if (ret < 0) { btrfs_abort_transaction(trans, root, ret); goto out_unlock; } } BUG_ON(disk_num_bytes > btrfs_super_total_bytes(root->fs_info->super_copy)); alloc_hint = get_extent_allocation_hint(inode, start, num_bytes); btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0); while (disk_num_bytes > 0) { unsigned long op; cur_alloc_size = disk_num_bytes; ret = btrfs_reserve_extent(trans, root, cur_alloc_size, root->sectorsize, 0, alloc_hint, &ins, 1); if (ret < 0) { btrfs_abort_transaction(trans, root, ret); goto out_unlock; } em = alloc_extent_map(); BUG_ON(!em); /* -ENOMEM */ em->start = start; em->orig_start = em->start; ram_size = ins.offset; em->len = ins.offset; em->block_start = ins.objectid; em->block_len = ins.offset; em->orig_block_len = ins.offset; em->bdev = root->fs_info->fs_devices->latest_bdev; set_bit(EXTENT_FLAG_PINNED, &em->flags); em->generation = -1; while (1) { write_lock(&em_tree->lock); ret = add_extent_mapping(em_tree, em); if (!ret) list_move(&em->list, &em_tree->modified_extents); write_unlock(&em_tree->lock); if (ret != -EEXIST) { free_extent_map(em); break; } btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0); } cur_alloc_size = ins.offset; ret = btrfs_add_ordered_extent(inode, start, ins.objectid, ram_size, cur_alloc_size, 0); BUG_ON(ret); /* -ENOMEM */ if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID) { ret = btrfs_reloc_clone_csums(inode, start, cur_alloc_size); if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_unlock; } } if (disk_num_bytes < cur_alloc_size) break; /* we're not doing compressed IO, don't unlock the first * page (which the caller expects to stay locked), don't * clear any dirty bits and don't set any writeback bits * * Do set the Private2 bit so we know this page was properly * setup for writepage */ op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0; op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC | EXTENT_SET_PRIVATE2; extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, start, start + ram_size - 1, locked_page, op); disk_num_bytes -= cur_alloc_size; num_bytes -= cur_alloc_size; alloc_hint = ins.objectid + ins.offset; start += cur_alloc_size; } out: return ret; out_unlock: extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, start, end, locked_page, EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC | EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK); goto out; } static noinline int cow_file_range(struct inode *inode, struct page *locked_page, u64 start, u64 end, int *page_started, unsigned long *nr_written, int unlock) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(inode)->root; int ret; trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, start, end, locked_page, EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC | EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK); return PTR_ERR(trans); } trans->block_rsv = &root->fs_info->delalloc_block_rsv; ret = __cow_file_range(trans, inode, root, locked_page, start, end, page_started, nr_written, unlock); btrfs_end_transaction(trans, root); return ret; } /* * work queue call back to started compression on a file and pages */ static noinline void async_cow_start(struct btrfs_work *work) { struct async_cow *async_cow; int num_added = 0; async_cow = container_of(work, struct async_cow, work); compress_file_range(async_cow->inode, async_cow->locked_page, async_cow->start, async_cow->end, async_cow, &num_added); if (num_added == 0) { btrfs_add_delayed_iput(async_cow->inode); async_cow->inode = NULL; } } /* * work queue call back to submit previously compressed pages */ static noinline void async_cow_submit(struct btrfs_work *work) { struct async_cow *async_cow; struct btrfs_root *root; unsigned long nr_pages; async_cow = container_of(work, struct async_cow, work); root = async_cow->root; nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >> PAGE_CACHE_SHIFT; if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) < 5 * 1024 * 1024 && waitqueue_active(&root->fs_info->async_submit_wait)) wake_up(&root->fs_info->async_submit_wait); if (async_cow->inode) submit_compressed_extents(async_cow->inode, async_cow); } static noinline void async_cow_free(struct btrfs_work *work) { struct async_cow *async_cow; async_cow = container_of(work, struct async_cow, work); if (async_cow->inode) btrfs_add_delayed_iput(async_cow->inode); kfree(async_cow); } static int cow_file_range_async(struct inode *inode, struct page *locked_page, u64 start, u64 end, int *page_started, unsigned long *nr_written) { struct async_cow *async_cow; struct btrfs_root *root = BTRFS_I(inode)->root; unsigned long nr_pages; u64 cur_end; int limit = 10 * 1024 * 1024; clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED, 1, 0, NULL, GFP_NOFS); while (start < end) { async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS); BUG_ON(!async_cow); /* -ENOMEM */ async_cow->inode = igrab(inode); async_cow->root = root; async_cow->locked_page = locked_page; async_cow->start = start; if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) cur_end = end; else cur_end = min(end, start + 512 * 1024 - 1); async_cow->end = cur_end; INIT_LIST_HEAD(&async_cow->extents); async_cow->work.func = async_cow_start; async_cow->work.ordered_func = async_cow_submit; async_cow->work.ordered_free = async_cow_free; async_cow->work.flags = 0; nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >> PAGE_CACHE_SHIFT; atomic_add(nr_pages, &root->fs_info->async_delalloc_pages); btrfs_queue_worker(&root->fs_info->delalloc_workers, &async_cow->work); if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) { wait_event(root->fs_info->async_submit_wait, (atomic_read(&root->fs_info->async_delalloc_pages) < limit)); } while (atomic_read(&root->fs_info->async_submit_draining) && atomic_read(&root->fs_info->async_delalloc_pages)) { wait_event(root->fs_info->async_submit_wait, (atomic_read(&root->fs_info->async_delalloc_pages) == 0)); } *nr_written += nr_pages; start = cur_end + 1; } *page_started = 1; return 0; } static noinline int csum_exist_in_range(struct btrfs_root *root, u64 bytenr, u64 num_bytes) { int ret; struct btrfs_ordered_sum *sums; LIST_HEAD(list); ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr, bytenr + num_bytes - 1, &list, 0); if (ret == 0 && list_empty(&list)) return 0; while (!list_empty(&list)) { sums = list_entry(list.next, struct btrfs_ordered_sum, list); list_del(&sums->list); kfree(sums); } return 1; } /* * when nowcow writeback call back. This checks for snapshots or COW copies * of the extents that exist in the file, and COWs the file as required. * * If no cow copies or snapshots exist, we write directly to the existing * blocks on disk */ static noinline int run_delalloc_nocow(struct inode *inode, struct page *locked_page, u64 start, u64 end, int *page_started, int force, unsigned long *nr_written) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; struct extent_buffer *leaf; struct btrfs_path *path; struct btrfs_file_extent_item *fi; struct btrfs_key found_key; u64 cow_start; u64 cur_offset; u64 extent_end; u64 extent_offset; u64 disk_bytenr; u64 num_bytes; u64 disk_num_bytes; int extent_type; int ret, err; int type; int nocow; int check_prev = 1; bool nolock; u64 ino = btrfs_ino(inode); path = btrfs_alloc_path(); if (!path) { extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, start, end, locked_page, EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC | EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK); return -ENOMEM; } nolock = btrfs_is_free_space_inode(inode); if (nolock) trans = btrfs_join_transaction_nolock(root); else trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, start, end, locked_page, EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC | EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK); btrfs_free_path(path); return PTR_ERR(trans); } trans->block_rsv = &root->fs_info->delalloc_block_rsv; cow_start = (u64)-1; cur_offset = start; while (1) { ret = btrfs_lookup_file_extent(trans, root, path, ino, cur_offset, 0); if (ret < 0) { btrfs_abort_transaction(trans, root, ret); goto error; } if (ret > 0 && path->slots[0] > 0 && check_prev) { leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0] - 1); if (found_key.objectid == ino && found_key.type == BTRFS_EXTENT_DATA_KEY) path->slots[0]--; } check_prev = 0; next_slot: leaf = path->nodes[0]; if (path->slots[0] >= btrfs_header_nritems(leaf)) { ret = btrfs_next_leaf(root, path); if (ret < 0) { btrfs_abort_transaction(trans, root, ret); goto error; } if (ret > 0) break; leaf = path->nodes[0]; } nocow = 0; disk_bytenr = 0; num_bytes = 0; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); if (found_key.objectid > ino || found_key.type > BTRFS_EXTENT_DATA_KEY || found_key.offset > end) break; if (found_key.offset > cur_offset) { extent_end = found_key.offset; extent_type = 0; goto out_check; } fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); extent_type = btrfs_file_extent_type(leaf, fi); if (extent_type == BTRFS_FILE_EXTENT_REG || extent_type == BTRFS_FILE_EXTENT_PREALLOC) { disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi); extent_offset = btrfs_file_extent_offset(leaf, fi); extent_end = found_key.offset + btrfs_file_extent_num_bytes(leaf, fi); disk_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi); if (extent_end <= start) { path->slots[0]++; goto next_slot; } if (disk_bytenr == 0) goto out_check; if (btrfs_file_extent_compression(leaf, fi) || btrfs_file_extent_encryption(leaf, fi) || btrfs_file_extent_other_encoding(leaf, fi)) goto out_check; if (extent_type == BTRFS_FILE_EXTENT_REG && !force) goto out_check; if (btrfs_extent_readonly(root, disk_bytenr)) goto out_check; if (btrfs_cross_ref_exist(trans, root, ino, found_key.offset - extent_offset, disk_bytenr)) goto out_check; disk_bytenr += extent_offset; disk_bytenr += cur_offset - found_key.offset; num_bytes = min(end + 1, extent_end) - cur_offset; /* * force cow if csum exists in the range. * this ensure that csum for a given extent are * either valid or do not exist. */ if (csum_exist_in_range(root, disk_bytenr, num_bytes)) goto out_check; nocow = 1; } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { extent_end = found_key.offset + btrfs_file_extent_inline_len(leaf, fi); extent_end = ALIGN(extent_end, root->sectorsize); } else { BUG_ON(1); } out_check: if (extent_end <= start) { path->slots[0]++; goto next_slot; } if (!nocow) { if (cow_start == (u64)-1) cow_start = cur_offset; cur_offset = extent_end; if (cur_offset > end) break; path->slots[0]++; goto next_slot; } btrfs_release_path(path); if (cow_start != (u64)-1) { ret = __cow_file_range(trans, inode, root, locked_page, cow_start, found_key.offset - 1, page_started, nr_written, 1); if (ret) { btrfs_abort_transaction(trans, root, ret); goto error; } cow_start = (u64)-1; } if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) { struct extent_map *em; struct extent_map_tree *em_tree; em_tree = &BTRFS_I(inode)->extent_tree; em = alloc_extent_map(); BUG_ON(!em); /* -ENOMEM */ em->start = cur_offset; em->orig_start = found_key.offset - extent_offset; em->len = num_bytes; em->block_len = num_bytes; em->block_start = disk_bytenr; em->orig_block_len = disk_num_bytes; em->bdev = root->fs_info->fs_devices->latest_bdev; set_bit(EXTENT_FLAG_PINNED, &em->flags); set_bit(EXTENT_FLAG_FILLING, &em->flags); em->generation = -1; while (1) { write_lock(&em_tree->lock); ret = add_extent_mapping(em_tree, em); if (!ret) list_move(&em->list, &em_tree->modified_extents); write_unlock(&em_tree->lock); if (ret != -EEXIST) { free_extent_map(em); break; } btrfs_drop_extent_cache(inode, em->start, em->start + em->len - 1, 0); } type = BTRFS_ORDERED_PREALLOC; } else { type = BTRFS_ORDERED_NOCOW; } ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr, num_bytes, num_bytes, type); BUG_ON(ret); /* -ENOMEM */ if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID) { ret = btrfs_reloc_clone_csums(inode, cur_offset, num_bytes); if (ret) { btrfs_abort_transaction(trans, root, ret); goto error; } } extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, cur_offset, cur_offset + num_bytes - 1, locked_page, EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC | EXTENT_SET_PRIVATE2); cur_offset = extent_end; if (cur_offset > end) break; } btrfs_release_path(path); if (cur_offset <= end && cow_start == (u64)-1) { cow_start = cur_offset; cur_offset = end; } if (cow_start != (u64)-1) { ret = __cow_file_range(trans, inode, root, locked_page, cow_start, end, page_started, nr_written, 1); if (ret) { btrfs_abort_transaction(trans, root, ret); goto error; } } error: err = btrfs_end_transaction(trans, root); if (!ret) ret = err; if (ret && cur_offset < end) extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, cur_offset, end, locked_page, EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC | EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK); btrfs_free_path(path); return ret; } /* * extent_io.c call back to do delayed allocation processing */ static int run_delalloc_range(struct inode *inode, struct page *locked_page, u64 start, u64 end, int *page_started, unsigned long *nr_written) { int ret; struct btrfs_root *root = BTRFS_I(inode)->root; if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) { ret = run_delalloc_nocow(inode, locked_page, start, end, page_started, 1, nr_written); } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) { ret = run_delalloc_nocow(inode, locked_page, start, end, page_started, 0, nr_written); } else if (!btrfs_test_opt(root, COMPRESS) && !(BTRFS_I(inode)->force_compress) && !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) { ret = cow_file_range(inode, locked_page, start, end, page_started, nr_written, 1); } else { set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &BTRFS_I(inode)->runtime_flags); ret = cow_file_range_async(inode, locked_page, start, end, page_started, nr_written); } return ret; } static void btrfs_split_extent_hook(struct inode *inode, struct extent_state *orig, u64 split) { /* not delalloc, ignore it */ if (!(orig->state & EXTENT_DELALLOC)) return; spin_lock(&BTRFS_I(inode)->lock); BTRFS_I(inode)->outstanding_extents++; spin_unlock(&BTRFS_I(inode)->lock); } /* * extent_io.c merge_extent_hook, used to track merged delayed allocation * extents so we can keep track of new extents that are just merged onto old * extents, such as when we are doing sequential writes, so we can properly * account for the metadata space we'll need. */ static void btrfs_merge_extent_hook(struct inode *inode, struct extent_state *new, struct extent_state *other) { /* not delalloc, ignore it */ if (!(other->state & EXTENT_DELALLOC)) return; spin_lock(&BTRFS_I(inode)->lock); BTRFS_I(inode)->outstanding_extents--; spin_unlock(&BTRFS_I(inode)->lock); } /* * extent_io.c set_bit_hook, used to track delayed allocation * bytes in this file, and to maintain the list of inodes that * have pending delalloc work to be done. */ static void btrfs_set_bit_hook(struct inode *inode, struct extent_state *state, int *bits) { /* * set_bit and clear bit hooks normally require _irqsave/restore * but in this case, we are only testing for the DELALLOC * bit, which is only set or cleared with irqs on */ if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) { struct btrfs_root *root = BTRFS_I(inode)->root; u64 len = state->end + 1 - state->start; bool do_list = !btrfs_is_free_space_inode(inode); if (*bits & EXTENT_FIRST_DELALLOC) { *bits &= ~EXTENT_FIRST_DELALLOC; } else { spin_lock(&BTRFS_I(inode)->lock); BTRFS_I(inode)->outstanding_extents++; spin_unlock(&BTRFS_I(inode)->lock); } spin_lock(&root->fs_info->delalloc_lock); BTRFS_I(inode)->delalloc_bytes += len; root->fs_info->delalloc_bytes += len; if (do_list && list_empty(&BTRFS_I(inode)->delalloc_inodes)) { list_add_tail(&BTRFS_I(inode)->delalloc_inodes, &root->fs_info->delalloc_inodes); } spin_unlock(&root->fs_info->delalloc_lock); } } /* * extent_io.c clear_bit_hook, see set_bit_hook for why */ static void btrfs_clear_bit_hook(struct inode *inode, struct extent_state *state, int *bits) { /* * set_bit and clear bit hooks normally require _irqsave/restore * but in this case, we are only testing for the DELALLOC * bit, which is only set or cleared with irqs on */ if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) { struct btrfs_root *root = BTRFS_I(inode)->root; u64 len = state->end + 1 - state->start; bool do_list = !btrfs_is_free_space_inode(inode); if (*bits & EXTENT_FIRST_DELALLOC) { *bits &= ~EXTENT_FIRST_DELALLOC; } else if (!(*bits & EXTENT_DO_ACCOUNTING)) { spin_lock(&BTRFS_I(inode)->lock); BTRFS_I(inode)->outstanding_extents--; spin_unlock(&BTRFS_I(inode)->lock); } if (*bits & EXTENT_DO_ACCOUNTING) btrfs_delalloc_release_metadata(inode, len); if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID && do_list) btrfs_free_reserved_data_space(inode, len); spin_lock(&root->fs_info->delalloc_lock); root->fs_info->delalloc_bytes -= len; BTRFS_I(inode)->delalloc_bytes -= len; if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 && !list_empty(&BTRFS_I(inode)->delalloc_inodes)) { list_del_init(&BTRFS_I(inode)->delalloc_inodes); } spin_unlock(&root->fs_info->delalloc_lock); } } /* * extent_io.c merge_bio_hook, this must check the chunk tree to make sure * we don't create bios that span stripes or chunks */ int btrfs_merge_bio_hook(struct page *page, unsigned long offset, size_t size, struct bio *bio, unsigned long bio_flags) { struct btrfs_root *root = BTRFS_I(page->mapping->host)->root; u64 logical = (u64)bio->bi_sector << 9; u64 length = 0; u64 map_length; int ret; if (bio_flags & EXTENT_BIO_COMPRESSED) return 0; length = bio->bi_size; map_length = length; ret = btrfs_map_block(root->fs_info, READ, logical, &map_length, NULL, 0); /* Will always return 0 with map_multi == NULL */ BUG_ON(ret < 0); if (map_length < length + size) return 1; return 0; } /* * in order to insert checksums into the metadata in large chunks, * we wait until bio submission time. All the pages in the bio are * checksummed and sums are attached onto the ordered extent record. * * At IO completion time the cums attached on the ordered extent record * are inserted into the btree */ static int __btrfs_submit_bio_start(struct inode *inode, int rw, struct bio *bio, int mirror_num, unsigned long bio_flags, u64 bio_offset) { struct btrfs_root *root = BTRFS_I(inode)->root; int ret = 0; ret = btrfs_csum_one_bio(root, inode, bio, 0, 0); BUG_ON(ret); /* -ENOMEM */ return 0; } /* * in order to insert checksums into the metadata in large chunks, * we wait until bio submission time. All the pages in the bio are * checksummed and sums are attached onto the ordered extent record. * * At IO completion time the cums attached on the ordered extent record * are inserted into the btree */ static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio, int mirror_num, unsigned long bio_flags, u64 bio_offset) { struct btrfs_root *root = BTRFS_I(inode)->root; int ret; ret = btrfs_map_bio(root, rw, bio, mirror_num, 1); if (ret) bio_endio(bio, ret); return ret; } /* * extent_io.c submission hook. This does the right thing for csum calculation * on write, or reading the csums from the tree before a read */ static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio, int mirror_num, unsigned long bio_flags, u64 bio_offset) { struct btrfs_root *root = BTRFS_I(inode)->root; int ret = 0; int skip_sum; int metadata = 0; int async = !atomic_read(&BTRFS_I(inode)->sync_writers); skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM; if (btrfs_is_free_space_inode(inode)) metadata = 2; if (!(rw & REQ_WRITE)) { ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata); if (ret) goto out; if (bio_flags & EXTENT_BIO_COMPRESSED) { ret = btrfs_submit_compressed_read(inode, bio, mirror_num, bio_flags); goto out; } else if (!skip_sum) { ret = btrfs_lookup_bio_sums(root, inode, bio, NULL); if (ret) goto out; } goto mapit; } else if (async && !skip_sum) { /* csum items have already been cloned */ if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID) goto mapit; /* we're doing a write, do the async checksumming */ ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info, inode, rw, bio, mirror_num, bio_flags, bio_offset, __btrfs_submit_bio_start, __btrfs_submit_bio_done); goto out; } else if (!skip_sum) { ret = btrfs_csum_one_bio(root, inode, bio, 0, 0); if (ret) goto out; } mapit: ret = btrfs_map_bio(root, rw, bio, mirror_num, 0); out: if (ret < 0) bio_endio(bio, ret); return ret; } /* * given a list of ordered sums record them in the inode. This happens * at IO completion time based on sums calculated at bio submission time. */ static noinline int add_pending_csums(struct btrfs_trans_handle *trans, struct inode *inode, u64 file_offset, struct list_head *list) { struct btrfs_ordered_sum *sum; list_for_each_entry(sum, list, list) { btrfs_csum_file_blocks(trans, BTRFS_I(inode)->root->fs_info->csum_root, sum); } return 0; } int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end, struct extent_state **cached_state) { WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0); return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end, cached_state, GFP_NOFS); } /* see btrfs_writepage_start_hook for details on why this is required */ struct btrfs_writepage_fixup { struct page *page; struct btrfs_work work; }; static void btrfs_writepage_fixup_worker(struct btrfs_work *work) { struct btrfs_writepage_fixup *fixup; struct btrfs_ordered_extent *ordered; struct extent_state *cached_state = NULL; struct page *page; struct inode *inode; u64 page_start; u64 page_end; int ret; fixup = container_of(work, struct btrfs_writepage_fixup, work); page = fixup->page; again: lock_page(page); if (!page->mapping || !PageDirty(page) || !PageChecked(page)) { ClearPageChecked(page); goto out_page; } inode = page->mapping->host; page_start = page_offset(page); page_end = page_offset(page) + PAGE_CACHE_SIZE - 1; lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0, &cached_state); /* already ordered? We're done */ if (PagePrivate2(page)) goto out; ordered = btrfs_lookup_ordered_extent(inode, page_start); if (ordered) { unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end, &cached_state, GFP_NOFS); unlock_page(page); btrfs_start_ordered_extent(inode, ordered, 1); btrfs_put_ordered_extent(ordered); goto again; } ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE); if (ret) { mapping_set_error(page->mapping, ret); end_extent_writepage(page, ret, page_start, page_end); ClearPageChecked(page); goto out; } btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state); ClearPageChecked(page); set_page_dirty(page); out: unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end, &cached_state, GFP_NOFS); out_page: unlock_page(page); page_cache_release(page); kfree(fixup); } /* * There are a few paths in the higher layers of the kernel that directly * set the page dirty bit without asking the filesystem if it is a * good idea. This causes problems because we want to make sure COW * properly happens and the data=ordered rules are followed. * * In our case any range that doesn't have the ORDERED bit set * hasn't been properly setup for IO. We kick off an async process * to fix it up. The async helper will wait for ordered extents, set * the delalloc bit and make it safe to write the page. */ static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end) { struct inode *inode = page->mapping->host; struct btrfs_writepage_fixup *fixup; struct btrfs_root *root = BTRFS_I(inode)->root; /* this page is properly in the ordered list */ if (TestClearPagePrivate2(page)) return 0; if (PageChecked(page)) return -EAGAIN; fixup = kzalloc(sizeof(*fixup), GFP_NOFS); if (!fixup) return -EAGAIN; SetPageChecked(page); page_cache_get(page); fixup->work.func = btrfs_writepage_fixup_worker; fixup->page = page; btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work); return -EBUSY; } static int insert_reserved_file_extent(struct btrfs_trans_handle *trans, struct inode *inode, u64 file_pos, u64 disk_bytenr, u64 disk_num_bytes, u64 num_bytes, u64 ram_bytes, u8 compression, u8 encryption, u16 other_encoding, int extent_type) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_file_extent_item *fi; struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_key ins; int ret; path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->leave_spinning = 1; /* * we may be replacing one extent in the tree with another. * The new extent is pinned in the extent map, and we don't want * to drop it from the cache until it is completely in the btree. * * So, tell btrfs_drop_extents to leave this extent in the cache. * the caller is expected to unpin it and allow it to be merged * with the others. */ ret = btrfs_drop_extents(trans, root, inode, file_pos, file_pos + num_bytes, 0); if (ret) goto out; ins.objectid = btrfs_ino(inode); ins.offset = file_pos; ins.type = BTRFS_EXTENT_DATA_KEY; ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi)); if (ret) goto out; leaf = path->nodes[0]; fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); btrfs_set_file_extent_generation(leaf, fi, trans->transid); btrfs_set_file_extent_type(leaf, fi, extent_type); btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr); btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes); btrfs_set_file_extent_offset(leaf, fi, 0); btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes); btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes); btrfs_set_file_extent_compression(leaf, fi, compression); btrfs_set_file_extent_encryption(leaf, fi, encryption); btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding); btrfs_mark_buffer_dirty(leaf); btrfs_release_path(path); inode_add_bytes(inode, num_bytes); ins.objectid = disk_bytenr; ins.offset = disk_num_bytes; ins.type = BTRFS_EXTENT_ITEM_KEY; ret = btrfs_alloc_reserved_file_extent(trans, root, root->root_key.objectid, btrfs_ino(inode), file_pos, &ins); out: btrfs_free_path(path); return ret; } /* * helper function for btrfs_finish_ordered_io, this * just reads in some of the csum leaves to prime them into ram * before we start the transaction. It limits the amount of btree * reads required while inside the transaction. */ /* as ordered data IO finishes, this gets called so we can finish * an ordered extent if the range of bytes in the file it covers are * fully written. */ static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent) { struct inode *inode = ordered_extent->inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans = NULL; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct extent_state *cached_state = NULL; int compress_type = 0; int ret; bool nolock; nolock = btrfs_is_free_space_inode(inode); if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) { ret = -EIO; goto out; } if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) { BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */ btrfs_ordered_update_i_size(inode, 0, ordered_extent); if (nolock) trans = btrfs_join_transaction_nolock(root); else trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { ret = PTR_ERR(trans); trans = NULL; goto out; } trans->block_rsv = &root->fs_info->delalloc_block_rsv; ret = btrfs_update_inode_fallback(trans, root, inode); if (ret) /* -ENOMEM or corruption */ btrfs_abort_transaction(trans, root, ret); goto out; } lock_extent_bits(io_tree, ordered_extent->file_offset, ordered_extent->file_offset + ordered_extent->len - 1, 0, &cached_state); if (nolock) trans = btrfs_join_transaction_nolock(root); else trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { ret = PTR_ERR(trans); trans = NULL; goto out_unlock; } trans->block_rsv = &root->fs_info->delalloc_block_rsv; if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags)) compress_type = ordered_extent->compress_type; if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) { BUG_ON(compress_type); ret = btrfs_mark_extent_written(trans, inode, ordered_extent->file_offset, ordered_extent->file_offset + ordered_extent->len); } else { BUG_ON(root == root->fs_info->tree_root); ret = insert_reserved_file_extent(trans, inode, ordered_extent->file_offset, ordered_extent->start, ordered_extent->disk_len, ordered_extent->len, ordered_extent->len, compress_type, 0, 0, BTRFS_FILE_EXTENT_REG); } unpin_extent_cache(&BTRFS_I(inode)->extent_tree, ordered_extent->file_offset, ordered_extent->len, trans->transid); if (ret < 0) { btrfs_abort_transaction(trans, root, ret); goto out_unlock; } add_pending_csums(trans, inode, ordered_extent->file_offset, &ordered_extent->list); btrfs_ordered_update_i_size(inode, 0, ordered_extent); ret = btrfs_update_inode_fallback(trans, root, inode); if (ret) { /* -ENOMEM or corruption */ btrfs_abort_transaction(trans, root, ret); goto out_unlock; } ret = 0; out_unlock: unlock_extent_cached(io_tree, ordered_extent->file_offset, ordered_extent->file_offset + ordered_extent->len - 1, &cached_state, GFP_NOFS); out: if (root != root->fs_info->tree_root) btrfs_delalloc_release_metadata(inode, ordered_extent->len); if (trans) btrfs_end_transaction(trans, root); if (ret) clear_extent_uptodate(io_tree, ordered_extent->file_offset, ordered_extent->file_offset + ordered_extent->len - 1, NULL, GFP_NOFS); /* * This needs to be done to make sure anybody waiting knows we are done * updating everything for this ordered extent. */ btrfs_remove_ordered_extent(inode, ordered_extent); /* once for us */ btrfs_put_ordered_extent(ordered_extent); /* once for the tree */ btrfs_put_ordered_extent(ordered_extent); return ret; } static void finish_ordered_fn(struct btrfs_work *work) { struct btrfs_ordered_extent *ordered_extent; ordered_extent = container_of(work, struct btrfs_ordered_extent, work); btrfs_finish_ordered_io(ordered_extent); } static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end, struct extent_state *state, int uptodate) { struct inode *inode = page->mapping->host; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_ordered_extent *ordered_extent = NULL; struct btrfs_workers *workers; trace_btrfs_writepage_end_io_hook(page, start, end, uptodate); ClearPagePrivate2(page); if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start, end - start + 1, uptodate)) return 0; ordered_extent->work.func = finish_ordered_fn; ordered_extent->work.flags = 0; if (btrfs_is_free_space_inode(inode)) workers = &root->fs_info->endio_freespace_worker; else workers = &root->fs_info->endio_write_workers; btrfs_queue_worker(workers, &ordered_extent->work); return 0; } /* * when reads are done, we need to check csums to verify the data is correct * if there's a match, we allow the bio to finish. If not, the code in * extent_io.c will try to find good copies for us. */ static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end, struct extent_state *state, int mirror) { size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT); struct inode *inode = page->mapping->host; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; char *kaddr; u64 private = ~(u32)0; int ret; struct btrfs_root *root = BTRFS_I(inode)->root; u32 csum = ~(u32)0; if (PageChecked(page)) { ClearPageChecked(page); goto good; } if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM) goto good; if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID && test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) { clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM, GFP_NOFS); return 0; } if (state && state->start == start) { private = state->private; ret = 0; } else { ret = get_state_private(io_tree, start, &private); } kaddr = kmap_atomic(page); if (ret) goto zeroit; csum = btrfs_csum_data(root, kaddr + offset, csum, end - start + 1); btrfs_csum_final(csum, (char *)&csum); if (csum != private) goto zeroit; kunmap_atomic(kaddr); good: return 0; zeroit: printk_ratelimited(KERN_INFO "btrfs csum failed ino %llu off %llu csum %u " "private %llu\n", (unsigned long long)btrfs_ino(page->mapping->host), (unsigned long long)start, csum, (unsigned long long)private); memset(kaddr + offset, 1, end - start + 1); flush_dcache_page(page); kunmap_atomic(kaddr); if (private == 0) return 0; return -EIO; } struct delayed_iput { struct list_head list; struct inode *inode; }; /* JDM: If this is fs-wide, why can't we add a pointer to * btrfs_inode instead and avoid the allocation? */ void btrfs_add_delayed_iput(struct inode *inode) { struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info; struct delayed_iput *delayed; if (atomic_add_unless(&inode->i_count, -1, 1)) return; delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL); delayed->inode = inode; spin_lock(&fs_info->delayed_iput_lock); list_add_tail(&delayed->list, &fs_info->delayed_iputs); spin_unlock(&fs_info->delayed_iput_lock); } void btrfs_run_delayed_iputs(struct btrfs_root *root) { LIST_HEAD(list); struct btrfs_fs_info *fs_info = root->fs_info; struct delayed_iput *delayed; int empty; spin_lock(&fs_info->delayed_iput_lock); empty = list_empty(&fs_info->delayed_iputs); spin_unlock(&fs_info->delayed_iput_lock); if (empty) return; spin_lock(&fs_info->delayed_iput_lock); list_splice_init(&fs_info->delayed_iputs, &list); spin_unlock(&fs_info->delayed_iput_lock); while (!list_empty(&list)) { delayed = list_entry(list.next, struct delayed_iput, list); list_del(&delayed->list); iput(delayed->inode); kfree(delayed); } } enum btrfs_orphan_cleanup_state { ORPHAN_CLEANUP_STARTED = 1, ORPHAN_CLEANUP_DONE = 2, }; /* * This is called in transaction commit time. If there are no orphan * files in the subvolume, it removes orphan item and frees block_rsv * structure. */ void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans, struct btrfs_root *root) { struct btrfs_block_rsv *block_rsv; int ret; if (atomic_read(&root->orphan_inodes) || root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) return; spin_lock(&root->orphan_lock); if (atomic_read(&root->orphan_inodes)) { spin_unlock(&root->orphan_lock); return; } if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) { spin_unlock(&root->orphan_lock); return; } block_rsv = root->orphan_block_rsv; root->orphan_block_rsv = NULL; spin_unlock(&root->orphan_lock); if (root->orphan_item_inserted && btrfs_root_refs(&root->root_item) > 0) { ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root, root->root_key.objectid); BUG_ON(ret); root->orphan_item_inserted = 0; } if (block_rsv) { WARN_ON(block_rsv->size > 0); btrfs_free_block_rsv(root, block_rsv); } } /* * This creates an orphan entry for the given inode in case something goes * wrong in the middle of an unlink/truncate. * * NOTE: caller of this function should reserve 5 units of metadata for * this function. */ int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_block_rsv *block_rsv = NULL; int reserve = 0; int insert = 0; int ret; if (!root->orphan_block_rsv) { block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP); if (!block_rsv) return -ENOMEM; } spin_lock(&root->orphan_lock); if (!root->orphan_block_rsv) { root->orphan_block_rsv = block_rsv; } else if (block_rsv) { btrfs_free_block_rsv(root, block_rsv); block_rsv = NULL; } if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM, &BTRFS_I(inode)->runtime_flags)) { #if 0 /* * For proper ENOSPC handling, we should do orphan * cleanup when mounting. But this introduces backward * compatibility issue. */ if (!xchg(&root->orphan_item_inserted, 1)) insert = 2; else insert = 1; #endif insert = 1; atomic_inc(&root->orphan_inodes); } if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED, &BTRFS_I(inode)->runtime_flags)) reserve = 1; spin_unlock(&root->orphan_lock); /* grab metadata reservation from transaction handle */ if (reserve) { ret = btrfs_orphan_reserve_metadata(trans, inode); BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */ } /* insert an orphan item to track this unlinked/truncated file */ if (insert >= 1) { ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode)); if (ret && ret != -EEXIST) { clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM, &BTRFS_I(inode)->runtime_flags); btrfs_abort_transaction(trans, root, ret); return ret; } ret = 0; } /* insert an orphan item to track subvolume contains orphan files */ if (insert >= 2) { ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root, root->root_key.objectid); if (ret && ret != -EEXIST) { btrfs_abort_transaction(trans, root, ret); return ret; } } return 0; } /* * We have done the truncate/delete so we can go ahead and remove the orphan * item for this particular inode. */ int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; int delete_item = 0; int release_rsv = 0; int ret = 0; spin_lock(&root->orphan_lock); if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM, &BTRFS_I(inode)->runtime_flags)) delete_item = 1; if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED, &BTRFS_I(inode)->runtime_flags)) release_rsv = 1; spin_unlock(&root->orphan_lock); if (trans && delete_item) { ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode)); BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */ } if (release_rsv) { btrfs_orphan_release_metadata(inode); atomic_dec(&root->orphan_inodes); } return 0; } /* * this cleans up any orphans that may be left on the list from the last use * of this root. */ int btrfs_orphan_cleanup(struct btrfs_root *root) { struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_key key, found_key; struct btrfs_trans_handle *trans; struct inode *inode; u64 last_objectid = 0; int ret = 0, nr_unlink = 0, nr_truncate = 0; if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED)) return 0; path = btrfs_alloc_path(); if (!path) { ret = -ENOMEM; goto out; } path->reada = -1; key.objectid = BTRFS_ORPHAN_OBJECTID; btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY); key.offset = (u64)-1; while (1) { ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) goto out; /* * if ret == 0 means we found what we were searching for, which * is weird, but possible, so only screw with path if we didn't * find the key and see if we have stuff that matches */ if (ret > 0) { ret = 0; if (path->slots[0] == 0) break; path->slots[0]--; } /* pull out the item */ leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); /* make sure the item matches what we want */ if (found_key.objectid != BTRFS_ORPHAN_OBJECTID) break; if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY) break; /* release the path since we're done with it */ btrfs_release_path(path); /* * this is where we are basically btrfs_lookup, without the * crossing root thing. we store the inode number in the * offset of the orphan item. */ if (found_key.offset == last_objectid) { printk(KERN_ERR "btrfs: Error removing orphan entry, " "stopping orphan cleanup\n"); ret = -EINVAL; goto out; } last_objectid = found_key.offset; found_key.objectid = found_key.offset; found_key.type = BTRFS_INODE_ITEM_KEY; found_key.offset = 0; inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL); ret = PTR_RET(inode); if (ret && ret != -ESTALE) goto out; if (ret == -ESTALE && root == root->fs_info->tree_root) { struct btrfs_root *dead_root; struct btrfs_fs_info *fs_info = root->fs_info; int is_dead_root = 0; /* * this is an orphan in the tree root. Currently these * could come from 2 sources: * a) a snapshot deletion in progress * b) a free space cache inode * We need to distinguish those two, as the snapshot * orphan must not get deleted. * find_dead_roots already ran before us, so if this * is a snapshot deletion, we should find the root * in the dead_roots list */ spin_lock(&fs_info->trans_lock); list_for_each_entry(dead_root, &fs_info->dead_roots, root_list) { if (dead_root->root_key.objectid == found_key.objectid) { is_dead_root = 1; break; } } spin_unlock(&fs_info->trans_lock); if (is_dead_root) { /* prevent this orphan from being found again */ key.offset = found_key.objectid - 1; continue; } } /* * Inode is already gone but the orphan item is still there, * kill the orphan item. */ if (ret == -ESTALE) { trans = btrfs_start_transaction(root, 1); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out; } printk(KERN_ERR "auto deleting %Lu\n", found_key.objectid); ret = btrfs_del_orphan_item(trans, root, found_key.objectid); BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */ btrfs_end_transaction(trans, root); continue; } /* * add this inode to the orphan list so btrfs_orphan_del does * the proper thing when we hit it */ set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM, &BTRFS_I(inode)->runtime_flags); /* if we have links, this was a truncate, lets do that */ if (inode->i_nlink) { if (!S_ISREG(inode->i_mode)) { WARN_ON(1); iput(inode); continue; } nr_truncate++; ret = btrfs_truncate(inode); } else { nr_unlink++; } /* this will do delete_inode and everything for us */ iput(inode); if (ret) goto out; } /* release the path since we're done with it */ btrfs_release_path(path); root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE; if (root->orphan_block_rsv) btrfs_block_rsv_release(root, root->orphan_block_rsv, (u64)-1); if (root->orphan_block_rsv || root->orphan_item_inserted) { trans = btrfs_join_transaction(root); if (!IS_ERR(trans)) btrfs_end_transaction(trans, root); } if (nr_unlink) printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink); if (nr_truncate) printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate); out: if (ret) printk(KERN_CRIT "btrfs: could not do orphan cleanup %d\n", ret); btrfs_free_path(path); return ret; } /* * very simple check to peek ahead in the leaf looking for xattrs. If we * don't find any xattrs, we know there can't be any acls. * * slot is the slot the inode is in, objectid is the objectid of the inode */ static noinline int acls_after_inode_item(struct extent_buffer *leaf, int slot, u64 objectid) { u32 nritems = btrfs_header_nritems(leaf); struct btrfs_key found_key; int scanned = 0; slot++; while (slot < nritems) { btrfs_item_key_to_cpu(leaf, &found_key, slot); /* we found a different objectid, there must not be acls */ if (found_key.objectid != objectid) return 0; /* we found an xattr, assume we've got an acl */ if (found_key.type == BTRFS_XATTR_ITEM_KEY) return 1; /* * we found a key greater than an xattr key, there can't * be any acls later on */ if (found_key.type > BTRFS_XATTR_ITEM_KEY) return 0; slot++; scanned++; /* * it goes inode, inode backrefs, xattrs, extents, * so if there are a ton of hard links to an inode there can * be a lot of backrefs. Don't waste time searching too hard, * this is just an optimization */ if (scanned >= 8) break; } /* we hit the end of the leaf before we found an xattr or * something larger than an xattr. We have to assume the inode * has acls */ return 1; } /* * read an inode from the btree into the in-memory inode */ static void btrfs_read_locked_inode(struct inode *inode) { struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_inode_item *inode_item; struct btrfs_timespec *tspec; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_key location; int maybe_acls; u32 rdev; int ret; bool filled = false; ret = btrfs_fill_inode(inode, &rdev); if (!ret) filled = true; path = btrfs_alloc_path(); if (!path) goto make_bad; path->leave_spinning = 1; memcpy(&location, &BTRFS_I(inode)->location, sizeof(location)); ret = btrfs_lookup_inode(NULL, root, path, &location, 0); if (ret) goto make_bad; leaf = path->nodes[0]; if (filled) goto cache_acl; inode_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_inode_item); inode->i_mode = btrfs_inode_mode(leaf, inode_item); set_nlink(inode, btrfs_inode_nlink(leaf, inode_item)); i_uid_write(inode, btrfs_inode_uid(leaf, inode_item)); i_gid_write(inode, btrfs_inode_gid(leaf, inode_item)); btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item)); tspec = btrfs_inode_atime(inode_item); inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec); inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec); tspec = btrfs_inode_mtime(inode_item); inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec); inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec); tspec = btrfs_inode_ctime(inode_item); inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec); inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec); inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item)); BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item); BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item); /* * If we were modified in the current generation and evicted from memory * and then re-read we need to do a full sync since we don't have any * idea about which extents were modified before we were evicted from * cache. */ if (BTRFS_I(inode)->last_trans == root->fs_info->generation) set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags); inode->i_version = btrfs_inode_sequence(leaf, inode_item); inode->i_generation = BTRFS_I(inode)->generation; inode->i_rdev = 0; rdev = btrfs_inode_rdev(leaf, inode_item); BTRFS_I(inode)->index_cnt = (u64)-1; BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item); cache_acl: /* * try to precache a NULL acl entry for files that don't have * any xattrs or acls */ maybe_acls = acls_after_inode_item(leaf, path->slots[0], btrfs_ino(inode)); if (!maybe_acls) cache_no_acl(inode); btrfs_free_path(path); switch (inode->i_mode & S_IFMT) { case S_IFREG: inode->i_mapping->a_ops = &btrfs_aops; inode->i_mapping->backing_dev_info = &root->fs_info->bdi; BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops; inode->i_fop = &btrfs_file_operations; inode->i_op = &btrfs_file_inode_operations; break; case S_IFDIR: inode->i_fop = &btrfs_dir_file_operations; if (root == root->fs_info->tree_root) inode->i_op = &btrfs_dir_ro_inode_operations; else inode->i_op = &btrfs_dir_inode_operations; break; case S_IFLNK: inode->i_op = &btrfs_symlink_inode_operations; inode->i_mapping->a_ops = &btrfs_symlink_aops; inode->i_mapping->backing_dev_info = &root->fs_info->bdi; break; default: inode->i_op = &btrfs_special_inode_operations; init_special_inode(inode, inode->i_mode, rdev); break; } btrfs_update_iflags(inode); return; make_bad: btrfs_free_path(path); make_bad_inode(inode); } /* * given a leaf and an inode, copy the inode fields into the leaf */ static void fill_inode_item(struct btrfs_trans_handle *trans, struct extent_buffer *leaf, struct btrfs_inode_item *item, struct inode *inode) { btrfs_set_inode_uid(leaf, item, i_uid_read(inode)); btrfs_set_inode_gid(leaf, item, i_gid_read(inode)); btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size); btrfs_set_inode_mode(leaf, item, inode->i_mode); btrfs_set_inode_nlink(leaf, item, inode->i_nlink); btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item), inode->i_atime.tv_sec); btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item), inode->i_atime.tv_nsec); btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item), inode->i_mtime.tv_sec); btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item), inode->i_mtime.tv_nsec); btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item), inode->i_ctime.tv_sec); btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item), inode->i_ctime.tv_nsec); btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode)); btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation); btrfs_set_inode_sequence(leaf, item, inode->i_version); btrfs_set_inode_transid(leaf, item, trans->transid); btrfs_set_inode_rdev(leaf, item, inode->i_rdev); btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags); btrfs_set_inode_block_group(leaf, item, 0); } /* * copy everything in the in-memory inode into the btree. */ static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *inode) { struct btrfs_inode_item *inode_item; struct btrfs_path *path; struct extent_buffer *leaf; int ret; path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->leave_spinning = 1; ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location, 1); if (ret) { if (ret > 0) ret = -ENOENT; goto failed; } btrfs_unlock_up_safe(path, 1); leaf = path->nodes[0]; inode_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_inode_item); fill_inode_item(trans, leaf, inode_item, inode); btrfs_mark_buffer_dirty(leaf); btrfs_set_inode_last_trans(trans, inode); ret = 0; failed: btrfs_free_path(path); return ret; } /* * copy everything in the in-memory inode into the btree. */ noinline int btrfs_update_inode(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *inode) { int ret; /* * If the inode is a free space inode, we can deadlock during commit * if we put it into the delayed code. * * The data relocation inode should also be directly updated * without delay */ if (!btrfs_is_free_space_inode(inode) && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) { btrfs_update_root_times(trans, root); ret = btrfs_delayed_update_inode(trans, root, inode); if (!ret) btrfs_set_inode_last_trans(trans, inode); return ret; } return btrfs_update_inode_item(trans, root, inode); } noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *inode) { int ret; ret = btrfs_update_inode(trans, root, inode); if (ret == -ENOSPC) return btrfs_update_inode_item(trans, root, inode); return ret; } /* * unlink helper that gets used here in inode.c and in the tree logging * recovery code. It remove a link in a directory with a given name, and * also drops the back refs in the inode to the directory */ static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *dir, struct inode *inode, const char *name, int name_len) { struct btrfs_path *path; int ret = 0; struct extent_buffer *leaf; struct btrfs_dir_item *di; struct btrfs_key key; u64 index; u64 ino = btrfs_ino(inode); u64 dir_ino = btrfs_ino(dir); path = btrfs_alloc_path(); if (!path) { ret = -ENOMEM; goto out; } path->leave_spinning = 1; di = btrfs_lookup_dir_item(trans, root, path, dir_ino, name, name_len, -1); if (IS_ERR(di)) { ret = PTR_ERR(di); goto err; } if (!di) { ret = -ENOENT; goto err; } leaf = path->nodes[0]; btrfs_dir_item_key_to_cpu(leaf, di, &key); ret = btrfs_delete_one_dir_name(trans, root, path, di); if (ret) goto err; btrfs_release_path(path); ret = btrfs_del_inode_ref(trans, root, name, name_len, ino, dir_ino, &index); if (ret) { printk(KERN_INFO "btrfs failed to delete reference to %.*s, " "inode %llu parent %llu\n", name_len, name, (unsigned long long)ino, (unsigned long long)dir_ino); btrfs_abort_transaction(trans, root, ret); goto err; } ret = btrfs_delete_delayed_dir_index(trans, root, dir, index); if (ret) { btrfs_abort_transaction(trans, root, ret); goto err; } ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode, dir_ino); if (ret != 0 && ret != -ENOENT) { btrfs_abort_transaction(trans, root, ret); goto err; } ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir, index); if (ret == -ENOENT) ret = 0; err: btrfs_free_path(path); if (ret) goto out; btrfs_i_size_write(dir, dir->i_size - name_len * 2); inode_inc_iversion(inode); inode_inc_iversion(dir); inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME; ret = btrfs_update_inode(trans, root, dir); out: return ret; } int btrfs_unlink_inode(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *dir, struct inode *inode, const char *name, int name_len) { int ret; ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len); if (!ret) { btrfs_drop_nlink(inode); ret = btrfs_update_inode(trans, root, inode); } return ret; } /* helper to check if there is any shared block in the path */ static int check_path_shared(struct btrfs_root *root, struct btrfs_path *path) { struct extent_buffer *eb; int level; u64 refs = 1; for (level = 0; level < BTRFS_MAX_LEVEL; level++) { int ret; if (!path->nodes[level]) break; eb = path->nodes[level]; if (!btrfs_block_can_be_shared(root, eb)) continue; ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len, &refs, NULL); if (refs > 1) return 1; } return 0; } /* * helper to start transaction for unlink and rmdir. * * unlink and rmdir are special in btrfs, they do not always free space. * so in enospc case, we should make sure they will free space before * allowing them to use the global metadata reservation. */ static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir, struct dentry *dentry) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(dir)->root; struct btrfs_path *path; struct btrfs_dir_item *di; struct inode *inode = dentry->d_inode; u64 index; int check_link = 1; int err = -ENOSPC; int ret; u64 ino = btrfs_ino(inode); u64 dir_ino = btrfs_ino(dir); /* * 1 for the possible orphan item * 1 for the dir item * 1 for the dir index * 1 for the inode ref * 1 for the inode ref in the tree log * 2 for the dir entries in the log * 1 for the inode */ trans = btrfs_start_transaction(root, 8); if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC) return trans; if (ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) return ERR_PTR(-ENOSPC); /* check if there is someone else holds reference */ if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1) return ERR_PTR(-ENOSPC); if (atomic_read(&inode->i_count) > 2) return ERR_PTR(-ENOSPC); if (xchg(&root->fs_info->enospc_unlink, 1)) return ERR_PTR(-ENOSPC); path = btrfs_alloc_path(); if (!path) { root->fs_info->enospc_unlink = 0; return ERR_PTR(-ENOMEM); } /* 1 for the orphan item */ trans = btrfs_start_transaction(root, 1); if (IS_ERR(trans)) { btrfs_free_path(path); root->fs_info->enospc_unlink = 0; return trans; } path->skip_locking = 1; path->search_commit_root = 1; ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(dir)->location, 0); if (ret < 0) { err = ret; goto out; } if (ret == 0) { if (check_path_shared(root, path)) goto out; } else { check_link = 0; } btrfs_release_path(path); ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location, 0); if (ret < 0) { err = ret; goto out; } if (ret == 0) { if (check_path_shared(root, path)) goto out; } else { check_link = 0; } btrfs_release_path(path); if (ret == 0 && S_ISREG(inode->i_mode)) { ret = btrfs_lookup_file_extent(trans, root, path, ino, (u64)-1, 0); if (ret < 0) { err = ret; goto out; } BUG_ON(ret == 0); /* Corruption */ if (check_path_shared(root, path)) goto out; btrfs_release_path(path); } if (!check_link) { err = 0; goto out; } di = btrfs_lookup_dir_item(trans, root, path, dir_ino, dentry->d_name.name, dentry->d_name.len, 0); if (IS_ERR(di)) { err = PTR_ERR(di); goto out; } if (di) { if (check_path_shared(root, path)) goto out; } else { err = 0; goto out; } btrfs_release_path(path); ret = btrfs_get_inode_ref_index(trans, root, path, dentry->d_name.name, dentry->d_name.len, ino, dir_ino, 0, &index); if (ret) { err = ret; goto out; } if (check_path_shared(root, path)) goto out; btrfs_release_path(path); /* * This is a commit root search, if we can lookup inode item and other * relative items in the commit root, it means the transaction of * dir/file creation has been committed, and the dir index item that we * delay to insert has also been inserted into the commit root. So * we needn't worry about the delayed insertion of the dir index item * here. */ di = btrfs_lookup_dir_index_item(trans, root, path, dir_ino, index, dentry->d_name.name, dentry->d_name.len, 0); if (IS_ERR(di)) { err = PTR_ERR(di); goto out; } BUG_ON(ret == -ENOENT); if (check_path_shared(root, path)) goto out; err = 0; out: btrfs_free_path(path); /* Migrate the orphan reservation over */ if (!err) err = btrfs_block_rsv_migrate(trans->block_rsv, &root->fs_info->global_block_rsv, trans->bytes_reserved); if (err) { btrfs_end_transaction(trans, root); root->fs_info->enospc_unlink = 0; return ERR_PTR(err); } trans->block_rsv = &root->fs_info->global_block_rsv; return trans; } static void __unlink_end_trans(struct btrfs_trans_handle *trans, struct btrfs_root *root) { if (trans->block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL) { btrfs_block_rsv_release(root, trans->block_rsv, trans->bytes_reserved); trans->block_rsv = &root->fs_info->trans_block_rsv; BUG_ON(!root->fs_info->enospc_unlink); root->fs_info->enospc_unlink = 0; } btrfs_end_transaction(trans, root); } static int btrfs_unlink(struct inode *dir, struct dentry *dentry) { struct btrfs_root *root = BTRFS_I(dir)->root; struct btrfs_trans_handle *trans; struct inode *inode = dentry->d_inode; int ret; trans = __unlink_start_trans(dir, dentry); if (IS_ERR(trans)) return PTR_ERR(trans); btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0); ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode, dentry->d_name.name, dentry->d_name.len); if (ret) goto out; if (inode->i_nlink == 0) { ret = btrfs_orphan_add(trans, inode); if (ret) goto out; } out: __unlink_end_trans(trans, root); btrfs_btree_balance_dirty(root); return ret; } int btrfs_unlink_subvol(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *dir, u64 objectid, const char *name, int name_len) { struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_dir_item *di; struct btrfs_key key; u64 index; int ret; u64 dir_ino = btrfs_ino(dir); path = btrfs_alloc_path(); if (!path) return -ENOMEM; di = btrfs_lookup_dir_item(trans, root, path, dir_ino, name, name_len, -1); if (IS_ERR_OR_NULL(di)) { if (!di) ret = -ENOENT; else ret = PTR_ERR(di); goto out; } leaf = path->nodes[0]; btrfs_dir_item_key_to_cpu(leaf, di, &key); WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid); ret = btrfs_delete_one_dir_name(trans, root, path, di); if (ret) { btrfs_abort_transaction(trans, root, ret); goto out; } btrfs_release_path(path); ret = btrfs_del_root_ref(trans, root->fs_info->tree_root, objectid, root->root_key.objectid, dir_ino, &index, name, name_len); if (ret < 0) { if (ret != -ENOENT) { btrfs_abort_transaction(trans, root, ret); goto out; } di = btrfs_search_dir_index_item(root, path, dir_ino, name, name_len); if (IS_ERR_OR_NULL(di)) { if (!di) ret = -ENOENT; else ret = PTR_ERR(di); btrfs_abort_transaction(trans, root, ret); goto out; } leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); btrfs_release_path(path); index = key.offset; } btrfs_release_path(path); ret = btrfs_delete_delayed_dir_index(trans, root, dir, index); if (ret) { btrfs_abort_transaction(trans, root, ret); goto out; } btrfs_i_size_write(dir, dir->i_size - name_len * 2); inode_inc_iversion(dir); dir->i_mtime = dir->i_ctime = CURRENT_TIME; ret = btrfs_update_inode_fallback(trans, root, dir); if (ret) btrfs_abort_transaction(trans, root, ret); out: btrfs_free_path(path); return ret; } static int btrfs_rmdir(struct inode *dir, struct dentry *dentry) { struct inode *inode = dentry->d_inode; int err = 0; struct btrfs_root *root = BTRFS_I(dir)->root; struct btrfs_trans_handle *trans; if (inode->i_size > BTRFS_EMPTY_DIR_SIZE) return -ENOTEMPTY; if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) return -EPERM; trans = __unlink_start_trans(dir, dentry); if (IS_ERR(trans)) return PTR_ERR(trans); if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) { err = btrfs_unlink_subvol(trans, root, dir, BTRFS_I(inode)->location.objectid, dentry->d_name.name, dentry->d_name.len); goto out; } err = btrfs_orphan_add(trans, inode); if (err) goto out; /* now the directory is empty */ err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode, dentry->d_name.name, dentry->d_name.len); if (!err) btrfs_i_size_write(inode, 0); out: __unlink_end_trans(trans, root); btrfs_btree_balance_dirty(root); return err; } /* * this can truncate away extent items, csum items and directory items. * It starts at a high offset and removes keys until it can't find * any higher than new_size * * csum items that cross the new i_size are truncated to the new size * as well. * * min_type is the minimum key type to truncate down to. If set to 0, this * will kill all the items on this inode, including the INODE_ITEM_KEY. */ int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *inode, u64 new_size, u32 min_type) { struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_file_extent_item *fi; struct btrfs_key key; struct btrfs_key found_key; u64 extent_start = 0; u64 extent_num_bytes = 0; u64 extent_offset = 0; u64 item_end = 0; u64 mask = root->sectorsize - 1; u32 found_type = (u8)-1; int found_extent; int del_item; int pending_del_nr = 0; int pending_del_slot = 0; int extent_type = -1; int ret; int err = 0; u64 ino = btrfs_ino(inode); BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY); path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->reada = -1; /* * We want to drop from the next block forward in case this new size is * not block aligned since we will be keeping the last block of the * extent just the way it is. */ if (root->ref_cows || root == root->fs_info->tree_root) btrfs_drop_extent_cache(inode, (new_size + mask) & (~mask), (u64)-1, 0); /* * This function is also used to drop the items in the log tree before * we relog the inode, so if root != BTRFS_I(inode)->root, it means * it is used to drop the loged items. So we shouldn't kill the delayed * items. */ if (min_type == 0 && root == BTRFS_I(inode)->root) btrfs_kill_delayed_inode_items(inode); key.objectid = ino; key.offset = (u64)-1; key.type = (u8)-1; search_again: path->leave_spinning = 1; ret = btrfs_search_slot(trans, root, &key, path, -1, 1); if (ret < 0) { err = ret; goto out; } if (ret > 0) { /* there are no items in the tree for us to truncate, we're * done */ if (path->slots[0] == 0) goto out; path->slots[0]--; } while (1) { fi = NULL; leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); found_type = btrfs_key_type(&found_key); if (found_key.objectid != ino) break; if (found_type < min_type) break; item_end = found_key.offset; if (found_type == BTRFS_EXTENT_DATA_KEY) { fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); extent_type = btrfs_file_extent_type(leaf, fi); if (extent_type != BTRFS_FILE_EXTENT_INLINE) { item_end += btrfs_file_extent_num_bytes(leaf, fi); } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { item_end += btrfs_file_extent_inline_len(leaf, fi); } item_end--; } if (found_type > min_type) { del_item = 1; } else { if (item_end < new_size) break; if (found_key.offset >= new_size) del_item = 1; else del_item = 0; } found_extent = 0; /* FIXME, shrink the extent if the ref count is only 1 */ if (found_type != BTRFS_EXTENT_DATA_KEY) goto delete; if (extent_type != BTRFS_FILE_EXTENT_INLINE) { u64 num_dec; extent_start = btrfs_file_extent_disk_bytenr(leaf, fi); if (!del_item) { u64 orig_num_bytes = btrfs_file_extent_num_bytes(leaf, fi); extent_num_bytes = new_size - found_key.offset + root->sectorsize - 1; extent_num_bytes = extent_num_bytes & ~((u64)root->sectorsize - 1); btrfs_set_file_extent_num_bytes(leaf, fi, extent_num_bytes); num_dec = (orig_num_bytes - extent_num_bytes); if (root->ref_cows && extent_start != 0) inode_sub_bytes(inode, num_dec); btrfs_mark_buffer_dirty(leaf); } else { extent_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi); extent_offset = found_key.offset - btrfs_file_extent_offset(leaf, fi); /* FIXME blocksize != 4096 */ num_dec = btrfs_file_extent_num_bytes(leaf, fi); if (extent_start != 0) { found_extent = 1; if (root->ref_cows) inode_sub_bytes(inode, num_dec); } } } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { /* * we can't truncate inline items that have had * special encodings */ if (!del_item && btrfs_file_extent_compression(leaf, fi) == 0 && btrfs_file_extent_encryption(leaf, fi) == 0 && btrfs_file_extent_other_encoding(leaf, fi) == 0) { u32 size = new_size - found_key.offset; if (root->ref_cows) { inode_sub_bytes(inode, item_end + 1 - new_size); } size = btrfs_file_extent_calc_inline_size(size); btrfs_truncate_item(trans, root, path, size, 1); } else if (root->ref_cows) { inode_sub_bytes(inode, item_end + 1 - found_key.offset); } } delete: if (del_item) { if (!pending_del_nr) { /* no pending yet, add ourselves */ pending_del_slot = path->slots[0]; pending_del_nr = 1; } else if (pending_del_nr && path->slots[0] + 1 == pending_del_slot) { /* hop on the pending chunk */ pending_del_nr++; pending_del_slot = path->slots[0]; } else { BUG(); } } else { break; } if (found_extent && (root->ref_cows || root == root->fs_info->tree_root)) { btrfs_set_path_blocking(path); ret = btrfs_free_extent(trans, root, extent_start, extent_num_bytes, 0, btrfs_header_owner(leaf), ino, extent_offset, 0); BUG_ON(ret); } if (found_type == BTRFS_INODE_ITEM_KEY) break; if (path->slots[0] == 0 || path->slots[0] != pending_del_slot) { if (pending_del_nr) { ret = btrfs_del_items(trans, root, path, pending_del_slot, pending_del_nr); if (ret) { btrfs_abort_transaction(trans, root, ret); goto error; } pending_del_nr = 0; } btrfs_release_path(path); goto search_again; } else { path->slots[0]--; } } out: if (pending_del_nr) { ret = btrfs_del_items(trans, root, path, pending_del_slot, pending_del_nr); if (ret) btrfs_abort_transaction(trans, root, ret); } error: btrfs_free_path(path); return err; } /* * btrfs_truncate_page - read, zero a chunk and write a page * @inode - inode that we're zeroing * @from - the offset to start zeroing * @len - the length to zero, 0 to zero the entire range respective to the * offset * @front - zero up to the offset instead of from the offset on * * This will find the page for the "from" offset and cow the page and zero the * part we want to zero. This is used with truncate and hole punching. */ int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len, int front) { struct address_space *mapping = inode->i_mapping; struct btrfs_root *root = BTRFS_I(inode)->root; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct btrfs_ordered_extent *ordered; struct extent_state *cached_state = NULL; char *kaddr; u32 blocksize = root->sectorsize; pgoff_t index = from >> PAGE_CACHE_SHIFT; unsigned offset = from & (PAGE_CACHE_SIZE-1); struct page *page; gfp_t mask = btrfs_alloc_write_mask(mapping); int ret = 0; u64 page_start; u64 page_end; if ((offset & (blocksize - 1)) == 0 && (!len || ((len & (blocksize - 1)) == 0))) goto out; ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE); if (ret) goto out; again: page = find_or_create_page(mapping, index, mask); if (!page) { btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE); ret = -ENOMEM; goto out; } page_start = page_offset(page); page_end = page_start + PAGE_CACHE_SIZE - 1; if (!PageUptodate(page)) { ret = btrfs_readpage(NULL, page); lock_page(page); if (page->mapping != mapping) { unlock_page(page); page_cache_release(page); goto again; } if (!PageUptodate(page)) { ret = -EIO; goto out_unlock; } } wait_on_page_writeback(page); lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state); set_page_extent_mapped(page); ordered = btrfs_lookup_ordered_extent(inode, page_start); if (ordered) { unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS); unlock_page(page); page_cache_release(page); btrfs_start_ordered_extent(inode, ordered, 1); btrfs_put_ordered_extent(ordered); goto again; } clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end, EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS); ret = btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state); if (ret) { unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS); goto out_unlock; } if (offset != PAGE_CACHE_SIZE) { if (!len) len = PAGE_CACHE_SIZE - offset; kaddr = kmap(page); if (front) memset(kaddr, 0, offset); else memset(kaddr + offset, 0, len); flush_dcache_page(page); kunmap(page); } ClearPageChecked(page); set_page_dirty(page); unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS); out_unlock: if (ret) btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE); unlock_page(page); page_cache_release(page); out: return ret; } /* * This function puts in dummy file extents for the area we're creating a hole * for. So if we are truncating this file to a larger size we need to insert * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for * the range between oldsize and size */ int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(inode)->root; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct extent_map *em = NULL; struct extent_state *cached_state = NULL; struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; u64 mask = root->sectorsize - 1; u64 hole_start = (oldsize + mask) & ~mask; u64 block_end = (size + mask) & ~mask; u64 last_byte; u64 cur_offset; u64 hole_size; int err = 0; if (size <= hole_start) return 0; while (1) { struct btrfs_ordered_extent *ordered; btrfs_wait_ordered_range(inode, hole_start, block_end - hole_start); lock_extent_bits(io_tree, hole_start, block_end - 1, 0, &cached_state); ordered = btrfs_lookup_ordered_extent(inode, hole_start); if (!ordered) break; unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state, GFP_NOFS); btrfs_put_ordered_extent(ordered); } cur_offset = hole_start; while (1) { em = btrfs_get_extent(inode, NULL, 0, cur_offset, block_end - cur_offset, 0); if (IS_ERR(em)) { err = PTR_ERR(em); break; } last_byte = min(extent_map_end(em), block_end); last_byte = (last_byte + mask) & ~mask; if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) { struct extent_map *hole_em; hole_size = last_byte - cur_offset; trans = btrfs_start_transaction(root, 3); if (IS_ERR(trans)) { err = PTR_ERR(trans); break; } err = btrfs_drop_extents(trans, root, inode, cur_offset, cur_offset + hole_size, 1); if (err) { btrfs_abort_transaction(trans, root, err); btrfs_end_transaction(trans, root); break; } err = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), cur_offset, 0, 0, hole_size, 0, hole_size, 0, 0, 0); if (err) { btrfs_abort_transaction(trans, root, err); btrfs_end_transaction(trans, root); break; } btrfs_drop_extent_cache(inode, cur_offset, cur_offset + hole_size - 1, 0); hole_em = alloc_extent_map(); if (!hole_em) { set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags); goto next; } hole_em->start = cur_offset; hole_em->len = hole_size; hole_em->orig_start = cur_offset; hole_em->block_start = EXTENT_MAP_HOLE; hole_em->block_len = 0; hole_em->orig_block_len = 0; hole_em->bdev = root->fs_info->fs_devices->latest_bdev; hole_em->compress_type = BTRFS_COMPRESS_NONE; hole_em->generation = trans->transid; while (1) { write_lock(&em_tree->lock); err = add_extent_mapping(em_tree, hole_em); if (!err) list_move(&hole_em->list, &em_tree->modified_extents); write_unlock(&em_tree->lock); if (err != -EEXIST) break; btrfs_drop_extent_cache(inode, cur_offset, cur_offset + hole_size - 1, 0); } free_extent_map(hole_em); next: btrfs_update_inode(trans, root, inode); btrfs_end_transaction(trans, root); } free_extent_map(em); em = NULL; cur_offset = last_byte; if (cur_offset >= block_end) break; } free_extent_map(em); unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state, GFP_NOFS); return err; } static int btrfs_setsize(struct inode *inode, loff_t newsize) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; loff_t oldsize = i_size_read(inode); int ret; if (newsize == oldsize) return 0; if (newsize > oldsize) { truncate_pagecache(inode, oldsize, newsize); ret = btrfs_cont_expand(inode, oldsize, newsize); if (ret) return ret; trans = btrfs_start_transaction(root, 1); if (IS_ERR(trans)) return PTR_ERR(trans); i_size_write(inode, newsize); btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL); ret = btrfs_update_inode(trans, root, inode); btrfs_end_transaction(trans, root); } else { /* * We're truncating a file that used to have good data down to * zero. Make sure it gets into the ordered flush list so that * any new writes get down to disk quickly. */ if (newsize == 0) set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE, &BTRFS_I(inode)->runtime_flags); /* we don't support swapfiles, so vmtruncate shouldn't fail */ truncate_setsize(inode, newsize); ret = btrfs_truncate(inode); } return ret; } static int btrfs_setattr(struct dentry *dentry, struct iattr *attr) { struct inode *inode = dentry->d_inode; struct btrfs_root *root = BTRFS_I(inode)->root; int err; if (btrfs_root_readonly(root)) return -EROFS; err = inode_change_ok(inode, attr); if (err) return err; if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) { err = btrfs_setsize(inode, attr->ia_size); if (err) return err; } if (attr->ia_valid) { setattr_copy(inode, attr); inode_inc_iversion(inode); err = btrfs_dirty_inode(inode); if (!err && attr->ia_valid & ATTR_MODE) err = btrfs_acl_chmod(inode); } return err; } void btrfs_evict_inode(struct inode *inode) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_block_rsv *rsv, *global_rsv; u64 min_size = btrfs_calc_trunc_metadata_size(root, 1); int ret; trace_btrfs_inode_evict(inode); truncate_inode_pages(&inode->i_data, 0); if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 || btrfs_is_free_space_inode(inode))) goto no_delete; if (is_bad_inode(inode)) { btrfs_orphan_del(NULL, inode); goto no_delete; } /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */ btrfs_wait_ordered_range(inode, 0, (u64)-1); if (root->fs_info->log_root_recovering) { BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM, &BTRFS_I(inode)->runtime_flags)); goto no_delete; } if (inode->i_nlink > 0) { BUG_ON(btrfs_root_refs(&root->root_item) != 0); goto no_delete; } rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP); if (!rsv) { btrfs_orphan_del(NULL, inode); goto no_delete; } rsv->size = min_size; rsv->failfast = 1; global_rsv = &root->fs_info->global_block_rsv; btrfs_i_size_write(inode, 0); /* * This is a bit simpler than btrfs_truncate since we've already * reserved our space for our orphan item in the unlink, so we just * need to reserve some slack space in case we add bytes and update * inode item when doing the truncate. */ while (1) { ret = btrfs_block_rsv_refill(root, rsv, min_size, BTRFS_RESERVE_FLUSH_LIMIT); /* * Try and steal from the global reserve since we will * likely not use this space anyway, we want to try as * hard as possible to get this to work. */ if (ret) ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size); if (ret) { printk(KERN_WARNING "Could not get space for a " "delete, will truncate on mount %d\n", ret); btrfs_orphan_del(NULL, inode); btrfs_free_block_rsv(root, rsv); goto no_delete; } trans = btrfs_start_transaction_lflush(root, 1); if (IS_ERR(trans)) { btrfs_orphan_del(NULL, inode); btrfs_free_block_rsv(root, rsv); goto no_delete; } trans->block_rsv = rsv; ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0); if (ret != -ENOSPC) break; trans->block_rsv = &root->fs_info->trans_block_rsv; ret = btrfs_update_inode(trans, root, inode); BUG_ON(ret); btrfs_end_transaction(trans, root); trans = NULL; btrfs_btree_balance_dirty(root); } btrfs_free_block_rsv(root, rsv); if (ret == 0) { trans->block_rsv = root->orphan_block_rsv; ret = btrfs_orphan_del(trans, inode); BUG_ON(ret); } trans->block_rsv = &root->fs_info->trans_block_rsv; if (!(root == root->fs_info->tree_root || root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)) btrfs_return_ino(root, btrfs_ino(inode)); btrfs_end_transaction(trans, root); btrfs_btree_balance_dirty(root); no_delete: clear_inode(inode); return; } /* * this returns the key found in the dir entry in the location pointer. * If no dir entries were found, location->objectid is 0. */ static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry, struct btrfs_key *location) { const char *name = dentry->d_name.name; int namelen = dentry->d_name.len; struct btrfs_dir_item *di; struct btrfs_path *path; struct btrfs_root *root = BTRFS_I(dir)->root; int ret = 0; path = btrfs_alloc_path(); if (!path) return -ENOMEM; di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name, namelen, 0); if (IS_ERR(di)) ret = PTR_ERR(di); if (IS_ERR_OR_NULL(di)) goto out_err; btrfs_dir_item_key_to_cpu(path->nodes[0], di, location); out: btrfs_free_path(path); return ret; out_err: location->objectid = 0; goto out; } /* * when we hit a tree root in a directory, the btrfs part of the inode * needs to be changed to reflect the root directory of the tree root. This * is kind of like crossing a mount point. */ static int fixup_tree_root_location(struct btrfs_root *root, struct inode *dir, struct dentry *dentry, struct btrfs_key *location, struct btrfs_root **sub_root) { struct btrfs_path *path; struct btrfs_root *new_root; struct btrfs_root_ref *ref; struct extent_buffer *leaf; int ret; int err = 0; path = btrfs_alloc_path(); if (!path) { err = -ENOMEM; goto out; } err = -ENOENT; ret = btrfs_find_root_ref(root->fs_info->tree_root, path, BTRFS_I(dir)->root->root_key.objectid, location->objectid); if (ret) { if (ret < 0) err = ret; goto out; } leaf = path->nodes[0]; ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref); if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) || btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len) goto out; ret = memcmp_extent_buffer(leaf, dentry->d_name.name, (unsigned long)(ref + 1), dentry->d_name.len); if (ret) goto out; btrfs_release_path(path); new_root = btrfs_read_fs_root_no_name(root->fs_info, location); if (IS_ERR(new_root)) { err = PTR_ERR(new_root); goto out; } if (btrfs_root_refs(&new_root->root_item) == 0) { err = -ENOENT; goto out; } *sub_root = new_root; location->objectid = btrfs_root_dirid(&new_root->root_item); location->type = BTRFS_INODE_ITEM_KEY; location->offset = 0; err = 0; out: btrfs_free_path(path); return err; } static void inode_tree_add(struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_inode *entry; struct rb_node **p; struct rb_node *parent; u64 ino = btrfs_ino(inode); again: p = &root->inode_tree.rb_node; parent = NULL; if (inode_unhashed(inode)) return; spin_lock(&root->inode_lock); while (*p) { parent = *p; entry = rb_entry(parent, struct btrfs_inode, rb_node); if (ino < btrfs_ino(&entry->vfs_inode)) p = &parent->rb_left; else if (ino > btrfs_ino(&entry->vfs_inode)) p = &parent->rb_right; else { WARN_ON(!(entry->vfs_inode.i_state & (I_WILL_FREE | I_FREEING))); rb_erase(parent, &root->inode_tree); RB_CLEAR_NODE(parent); spin_unlock(&root->inode_lock); goto again; } } rb_link_node(&BTRFS_I(inode)->rb_node, parent, p); rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree); spin_unlock(&root->inode_lock); } static void inode_tree_del(struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; int empty = 0; spin_lock(&root->inode_lock); if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) { rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree); RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node); empty = RB_EMPTY_ROOT(&root->inode_tree); } spin_unlock(&root->inode_lock); /* * Free space cache has inodes in the tree root, but the tree root has a * root_refs of 0, so this could end up dropping the tree root as a * snapshot, so we need the extra !root->fs_info->tree_root check to * make sure we don't drop it. */ if (empty && btrfs_root_refs(&root->root_item) == 0 && root != root->fs_info->tree_root) { synchronize_srcu(&root->fs_info->subvol_srcu); spin_lock(&root->inode_lock); empty = RB_EMPTY_ROOT(&root->inode_tree); spin_unlock(&root->inode_lock); if (empty) btrfs_add_dead_root(root); } } void btrfs_invalidate_inodes(struct btrfs_root *root) { struct rb_node *node; struct rb_node *prev; struct btrfs_inode *entry; struct inode *inode; u64 objectid = 0; WARN_ON(btrfs_root_refs(&root->root_item) != 0); spin_lock(&root->inode_lock); again: node = root->inode_tree.rb_node; prev = NULL; while (node) { prev = node; entry = rb_entry(node, struct btrfs_inode, rb_node); if (objectid < btrfs_ino(&entry->vfs_inode)) node = node->rb_left; else if (objectid > btrfs_ino(&entry->vfs_inode)) node = node->rb_right; else break; } if (!node) { while (prev) { entry = rb_entry(prev, struct btrfs_inode, rb_node); if (objectid <= btrfs_ino(&entry->vfs_inode)) { node = prev; break; } prev = rb_next(prev); } } while (node) { entry = rb_entry(node, struct btrfs_inode, rb_node); objectid = btrfs_ino(&entry->vfs_inode) + 1; inode = igrab(&entry->vfs_inode); if (inode) { spin_unlock(&root->inode_lock); if (atomic_read(&inode->i_count) > 1) d_prune_aliases(inode); /* * btrfs_drop_inode will have it removed from * the inode cache when its usage count * hits zero. */ iput(inode); cond_resched(); spin_lock(&root->inode_lock); goto again; } if (cond_resched_lock(&root->inode_lock)) goto again; node = rb_next(node); } spin_unlock(&root->inode_lock); } static int btrfs_init_locked_inode(struct inode *inode, void *p) { struct btrfs_iget_args *args = p; inode->i_ino = args->ino; BTRFS_I(inode)->root = args->root; return 0; } static int btrfs_find_actor(struct inode *inode, void *opaque) { struct btrfs_iget_args *args = opaque; return args->ino == btrfs_ino(inode) && args->root == BTRFS_I(inode)->root; } static struct inode *btrfs_iget_locked(struct super_block *s, u64 objectid, struct btrfs_root *root) { struct inode *inode; struct btrfs_iget_args args; args.ino = objectid; args.root = root; inode = iget5_locked(s, objectid, btrfs_find_actor, btrfs_init_locked_inode, (void *)&args); return inode; } /* Get an inode object given its location and corresponding root. * Returns in *is_new if the inode was read from disk */ struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location, struct btrfs_root *root, int *new) { struct inode *inode; inode = btrfs_iget_locked(s, location->objectid, root); if (!inode) return ERR_PTR(-ENOMEM); if (inode->i_state & I_NEW) { BTRFS_I(inode)->root = root; memcpy(&BTRFS_I(inode)->location, location, sizeof(*location)); btrfs_read_locked_inode(inode); if (!is_bad_inode(inode)) { inode_tree_add(inode); unlock_new_inode(inode); if (new) *new = 1; } else { unlock_new_inode(inode); iput(inode); inode = ERR_PTR(-ESTALE); } } return inode; } static struct inode *new_simple_dir(struct super_block *s, struct btrfs_key *key, struct btrfs_root *root) { struct inode *inode = new_inode(s); if (!inode) return ERR_PTR(-ENOMEM); BTRFS_I(inode)->root = root; memcpy(&BTRFS_I(inode)->location, key, sizeof(*key)); set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags); inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID; inode->i_op = &btrfs_dir_ro_inode_operations; inode->i_fop = &simple_dir_operations; inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO; inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME; return inode; } struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry) { struct inode *inode; struct btrfs_root *root = BTRFS_I(dir)->root; struct btrfs_root *sub_root = root; struct btrfs_key location; int index; int ret = 0; if (dentry->d_name.len > BTRFS_NAME_LEN) return ERR_PTR(-ENAMETOOLONG); if (unlikely(d_need_lookup(dentry))) { memcpy(&location, dentry->d_fsdata, sizeof(struct btrfs_key)); kfree(dentry->d_fsdata); dentry->d_fsdata = NULL; /* This thing is hashed, drop it for now */ d_drop(dentry); } else { ret = btrfs_inode_by_name(dir, dentry, &location); } if (ret < 0) return ERR_PTR(ret); if (location.objectid == 0) return NULL; if (location.type == BTRFS_INODE_ITEM_KEY) { inode = btrfs_iget(dir->i_sb, &location, root, NULL); return inode; } BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY); index = srcu_read_lock(&root->fs_info->subvol_srcu); ret = fixup_tree_root_location(root, dir, dentry, &location, &sub_root); if (ret < 0) { if (ret != -ENOENT) inode = ERR_PTR(ret); else inode = new_simple_dir(dir->i_sb, &location, sub_root); } else { inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL); } srcu_read_unlock(&root->fs_info->subvol_srcu, index); if (!IS_ERR(inode) && root != sub_root) { down_read(&root->fs_info->cleanup_work_sem); if (!(inode->i_sb->s_flags & MS_RDONLY)) ret = btrfs_orphan_cleanup(sub_root); up_read(&root->fs_info->cleanup_work_sem); if (ret) inode = ERR_PTR(ret); } return inode; } static int btrfs_dentry_delete(const struct dentry *dentry) { struct btrfs_root *root; struct inode *inode = dentry->d_inode; if (!inode && !IS_ROOT(dentry)) inode = dentry->d_parent->d_inode; if (inode) { root = BTRFS_I(inode)->root; if (btrfs_root_refs(&root->root_item) == 0) return 1; if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) return 1; } return 0; } static void btrfs_dentry_release(struct dentry *dentry) { if (dentry->d_fsdata) kfree(dentry->d_fsdata); } static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags) { struct dentry *ret; ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry); if (unlikely(d_need_lookup(dentry))) { spin_lock(&dentry->d_lock); dentry->d_flags &= ~DCACHE_NEED_LOOKUP; spin_unlock(&dentry->d_lock); } return ret; } unsigned char btrfs_filetype_table[] = { DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK }; static int btrfs_real_readdir(struct file *filp, void *dirent, filldir_t filldir) { struct inode *inode = filp->f_dentry->d_inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_item *item; struct btrfs_dir_item *di; struct btrfs_key key; struct btrfs_key found_key; struct btrfs_path *path; struct list_head ins_list; struct list_head del_list; int ret; struct extent_buffer *leaf; int slot; unsigned char d_type; int over = 0; u32 di_cur; u32 di_total; u32 di_len; int key_type = BTRFS_DIR_INDEX_KEY; char tmp_name[32]; char *name_ptr; int name_len; int is_curr = 0; /* filp->f_pos points to the current index? */ /* FIXME, use a real flag for deciding about the key type */ if (root->fs_info->tree_root == root) key_type = BTRFS_DIR_ITEM_KEY; /* special case for "." */ if (filp->f_pos == 0) { over = filldir(dirent, ".", 1, filp->f_pos, btrfs_ino(inode), DT_DIR); if (over) return 0; filp->f_pos = 1; } /* special case for .., just use the back ref */ if (filp->f_pos == 1) { u64 pino = parent_ino(filp->f_path.dentry); over = filldir(dirent, "..", 2, filp->f_pos, pino, DT_DIR); if (over) return 0; filp->f_pos = 2; } path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->reada = 1; if (key_type == BTRFS_DIR_INDEX_KEY) { INIT_LIST_HEAD(&ins_list); INIT_LIST_HEAD(&del_list); btrfs_get_delayed_items(inode, &ins_list, &del_list); } btrfs_set_key_type(&key, key_type); key.offset = filp->f_pos; key.objectid = btrfs_ino(inode); ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) goto err; while (1) { leaf = path->nodes[0]; slot = path->slots[0]; if (slot >= btrfs_header_nritems(leaf)) { ret = btrfs_next_leaf(root, path); if (ret < 0) goto err; else if (ret > 0) break; continue; } item = btrfs_item_nr(leaf, slot); btrfs_item_key_to_cpu(leaf, &found_key, slot); if (found_key.objectid != key.objectid) break; if (btrfs_key_type(&found_key) != key_type) break; if (found_key.offset < filp->f_pos) goto next; if (key_type == BTRFS_DIR_INDEX_KEY && btrfs_should_delete_dir_index(&del_list, found_key.offset)) goto next; filp->f_pos = found_key.offset; is_curr = 1; di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item); di_cur = 0; di_total = btrfs_item_size(leaf, item); while (di_cur < di_total) { struct btrfs_key location; if (verify_dir_item(root, leaf, di)) break; name_len = btrfs_dir_name_len(leaf, di); if (name_len <= sizeof(tmp_name)) { name_ptr = tmp_name; } else { name_ptr = kmalloc(name_len, GFP_NOFS); if (!name_ptr) { ret = -ENOMEM; goto err; } } read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1), name_len); d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)]; btrfs_dir_item_key_to_cpu(leaf, di, &location); /* is this a reference to our own snapshot? If so * skip it. * * In contrast to old kernels, we insert the snapshot's * dir item and dir index after it has been created, so * we won't find a reference to our own snapshot. We * still keep the following code for backward * compatibility. */ if (location.type == BTRFS_ROOT_ITEM_KEY && location.objectid == root->root_key.objectid) { over = 0; goto skip; } over = filldir(dirent, name_ptr, name_len, found_key.offset, location.objectid, d_type); skip: if (name_ptr != tmp_name) kfree(name_ptr); if (over) goto nopos; di_len = btrfs_dir_name_len(leaf, di) + btrfs_dir_data_len(leaf, di) + sizeof(*di); di_cur += di_len; di = (struct btrfs_dir_item *)((char *)di + di_len); } next: path->slots[0]++; } if (key_type == BTRFS_DIR_INDEX_KEY) { if (is_curr) filp->f_pos++; ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir, &ins_list); if (ret) goto nopos; } /* Reached end of directory/root. Bump pos past the last item. */ if (key_type == BTRFS_DIR_INDEX_KEY) /* * 32-bit glibc will use getdents64, but then strtol - * so the last number we can serve is this. */ filp->f_pos = 0x7fffffff; else filp->f_pos++; nopos: ret = 0; err: if (key_type == BTRFS_DIR_INDEX_KEY) btrfs_put_delayed_items(&ins_list, &del_list); btrfs_free_path(path); return ret; } int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; int ret = 0; bool nolock = false; if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags)) return 0; if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode)) nolock = true; if (wbc->sync_mode == WB_SYNC_ALL) { if (nolock) trans = btrfs_join_transaction_nolock(root); else trans = btrfs_join_transaction(root); if (IS_ERR(trans)) return PTR_ERR(trans); ret = btrfs_commit_transaction(trans, root); } return ret; } /* * This is somewhat expensive, updating the tree every time the * inode changes. But, it is most likely to find the inode in cache. * FIXME, needs more benchmarking...there are no reasons other than performance * to keep or drop this code. */ int btrfs_dirty_inode(struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; int ret; if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags)) return 0; trans = btrfs_join_transaction(root); if (IS_ERR(trans)) return PTR_ERR(trans); ret = btrfs_update_inode(trans, root, inode); if (ret && ret == -ENOSPC) { /* whoops, lets try again with the full transaction */ btrfs_end_transaction(trans, root); trans = btrfs_start_transaction(root, 1); if (IS_ERR(trans)) return PTR_ERR(trans); ret = btrfs_update_inode(trans, root, inode); } btrfs_end_transaction(trans, root); if (BTRFS_I(inode)->delayed_node) btrfs_balance_delayed_items(root); return ret; } /* * This is a copy of file_update_time. We need this so we can return error on * ENOSPC for updating the inode in the case of file write and mmap writes. */ static int btrfs_update_time(struct inode *inode, struct timespec *now, int flags) { struct btrfs_root *root = BTRFS_I(inode)->root; if (btrfs_root_readonly(root)) return -EROFS; if (flags & S_VERSION) inode_inc_iversion(inode); if (flags & S_CTIME) inode->i_ctime = *now; if (flags & S_MTIME) inode->i_mtime = *now; if (flags & S_ATIME) inode->i_atime = *now; return btrfs_dirty_inode(inode); } /* * find the highest existing sequence number in a directory * and then set the in-memory index_cnt variable to reflect * free sequence numbers */ static int btrfs_set_inode_index_count(struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_key key, found_key; struct btrfs_path *path; struct extent_buffer *leaf; int ret; key.objectid = btrfs_ino(inode); btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY); key.offset = (u64)-1; path = btrfs_alloc_path(); if (!path) return -ENOMEM; ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) goto out; /* FIXME: we should be able to handle this */ if (ret == 0) goto out; ret = 0; /* * MAGIC NUMBER EXPLANATION: * since we search a directory based on f_pos we have to start at 2 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody * else has to start at 2 */ if (path->slots[0] == 0) { BTRFS_I(inode)->index_cnt = 2; goto out; } path->slots[0]--; leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); if (found_key.objectid != btrfs_ino(inode) || btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) { BTRFS_I(inode)->index_cnt = 2; goto out; } BTRFS_I(inode)->index_cnt = found_key.offset + 1; out: btrfs_free_path(path); return ret; } /* * helper to find a free sequence number in a given directory. This current * code is very simple, later versions will do smarter things in the btree */ int btrfs_set_inode_index(struct inode *dir, u64 *index) { int ret = 0; if (BTRFS_I(dir)->index_cnt == (u64)-1) { ret = btrfs_inode_delayed_dir_index_count(dir); if (ret) { ret = btrfs_set_inode_index_count(dir); if (ret) return ret; } } *index = BTRFS_I(dir)->index_cnt; BTRFS_I(dir)->index_cnt++; return ret; } static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *dir, const char *name, int name_len, u64 ref_objectid, u64 objectid, umode_t mode, u64 *index) { struct inode *inode; struct btrfs_inode_item *inode_item; struct btrfs_key *location; struct btrfs_path *path; struct btrfs_inode_ref *ref; struct btrfs_key key[2]; u32 sizes[2]; unsigned long ptr; int ret; int owner; path = btrfs_alloc_path(); if (!path) return ERR_PTR(-ENOMEM); inode = new_inode(root->fs_info->sb); if (!inode) { btrfs_free_path(path); return ERR_PTR(-ENOMEM); } /* * we have to initialize this early, so we can reclaim the inode * number if we fail afterwards in this function. */ inode->i_ino = objectid; if (dir) { trace_btrfs_inode_request(dir); ret = btrfs_set_inode_index(dir, index); if (ret) { btrfs_free_path(path); iput(inode); return ERR_PTR(ret); } } /* * index_cnt is ignored for everything but a dir, * btrfs_get_inode_index_count has an explanation for the magic * number */ BTRFS_I(inode)->index_cnt = 2; BTRFS_I(inode)->root = root; BTRFS_I(inode)->generation = trans->transid; inode->i_generation = BTRFS_I(inode)->generation; /* * We could have gotten an inode number from somebody who was fsynced * and then removed in this same transaction, so let's just set full * sync since it will be a full sync anyway and this will blow away the * old info in the log. */ set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags); if (S_ISDIR(mode)) owner = 0; else owner = 1; key[0].objectid = objectid; btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY); key[0].offset = 0; /* * Start new inodes with an inode_ref. This is slightly more * efficient for small numbers of hard links since they will * be packed into one item. Extended refs will kick in if we * add more hard links than can fit in the ref item. */ key[1].objectid = objectid; btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY); key[1].offset = ref_objectid; sizes[0] = sizeof(struct btrfs_inode_item); sizes[1] = name_len + sizeof(*ref); path->leave_spinning = 1; ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2); if (ret != 0) goto fail; inode_init_owner(inode, dir, mode); inode_set_bytes(inode, 0); inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME; inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0], struct btrfs_inode_item); memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item, sizeof(*inode_item)); fill_inode_item(trans, path->nodes[0], inode_item, inode); ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1, struct btrfs_inode_ref); btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len); btrfs_set_inode_ref_index(path->nodes[0], ref, *index); ptr = (unsigned long)(ref + 1); write_extent_buffer(path->nodes[0], name, ptr, name_len); btrfs_mark_buffer_dirty(path->nodes[0]); btrfs_free_path(path); location = &BTRFS_I(inode)->location; location->objectid = objectid; location->offset = 0; btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY); btrfs_inherit_iflags(inode, dir); if (S_ISREG(mode)) { if (btrfs_test_opt(root, NODATASUM)) BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM; if (btrfs_test_opt(root, NODATACOW) || (BTRFS_I(dir)->flags & BTRFS_INODE_NODATACOW)) BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW; } insert_inode_hash(inode); inode_tree_add(inode); trace_btrfs_inode_new(inode); btrfs_set_inode_last_trans(trans, inode); btrfs_update_root_times(trans, root); return inode; fail: if (dir) BTRFS_I(dir)->index_cnt--; btrfs_free_path(path); iput(inode); return ERR_PTR(ret); } static inline u8 btrfs_inode_type(struct inode *inode) { return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT]; } /* * utility function to add 'inode' into 'parent_inode' with * a give name and a given sequence number. * if 'add_backref' is true, also insert a backref from the * inode to the parent directory. */ int btrfs_add_link(struct btrfs_trans_handle *trans, struct inode *parent_inode, struct inode *inode, const char *name, int name_len, int add_backref, u64 index) { int ret = 0; struct btrfs_key key; struct btrfs_root *root = BTRFS_I(parent_inode)->root; u64 ino = btrfs_ino(inode); u64 parent_ino = btrfs_ino(parent_inode); if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key)); } else { key.objectid = ino; btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY); key.offset = 0; } if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { ret = btrfs_add_root_ref(trans, root->fs_info->tree_root, key.objectid, root->root_key.objectid, parent_ino, index, name, name_len); } else if (add_backref) { ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino, parent_ino, index); } /* Nothing to clean up yet */ if (ret) return ret; ret = btrfs_insert_dir_item(trans, root, name, name_len, parent_inode, &key, btrfs_inode_type(inode), index); if (ret == -EEXIST) goto fail_dir_item; else if (ret) { btrfs_abort_transaction(trans, root, ret); return ret; } btrfs_i_size_write(parent_inode, parent_inode->i_size + name_len * 2); inode_inc_iversion(parent_inode); parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME; ret = btrfs_update_inode(trans, root, parent_inode); if (ret) btrfs_abort_transaction(trans, root, ret); return ret; fail_dir_item: if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { u64 local_index; int err; err = btrfs_del_root_ref(trans, root->fs_info->tree_root, key.objectid, root->root_key.objectid, parent_ino, &local_index, name, name_len); } else if (add_backref) { u64 local_index; int err; err = btrfs_del_inode_ref(trans, root, name, name_len, ino, parent_ino, &local_index); } return ret; } static int btrfs_add_nondir(struct btrfs_trans_handle *trans, struct inode *dir, struct dentry *dentry, struct inode *inode, int backref, u64 index) { int err = btrfs_add_link(trans, dir, inode, dentry->d_name.name, dentry->d_name.len, backref, index); if (err > 0) err = -EEXIST; return err; } static int btrfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t rdev) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(dir)->root; struct inode *inode = NULL; int err; int drop_inode = 0; u64 objectid; u64 index = 0; if (!new_valid_dev(rdev)) return -EINVAL; /* * 2 for inode item and ref * 2 for dir items * 1 for xattr if selinux is on */ trans = btrfs_start_transaction(root, 5); if (IS_ERR(trans)) return PTR_ERR(trans); err = btrfs_find_free_ino(root, &objectid); if (err) goto out_unlock; inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name, dentry->d_name.len, btrfs_ino(dir), objectid, mode, &index); if (IS_ERR(inode)) { err = PTR_ERR(inode); goto out_unlock; } err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name); if (err) { drop_inode = 1; goto out_unlock; } err = btrfs_update_inode(trans, root, inode); if (err) { drop_inode = 1; goto out_unlock; } /* * If the active LSM wants to access the inode during * d_instantiate it needs these. Smack checks to see * if the filesystem supports xattrs by looking at the * ops vector. */ inode->i_op = &btrfs_special_inode_operations; err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index); if (err) drop_inode = 1; else { init_special_inode(inode, inode->i_mode, rdev); btrfs_update_inode(trans, root, inode); d_instantiate(dentry, inode); } out_unlock: btrfs_end_transaction(trans, root); btrfs_btree_balance_dirty(root); if (drop_inode) { inode_dec_link_count(inode); iput(inode); } return err; } static int btrfs_create(struct inode *dir, struct dentry *dentry, umode_t mode, bool excl) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(dir)->root; struct inode *inode = NULL; int drop_inode_on_err = 0; int err; u64 objectid; u64 index = 0; /* * 2 for inode item and ref * 2 for dir items * 1 for xattr if selinux is on */ trans = btrfs_start_transaction(root, 5); if (IS_ERR(trans)) return PTR_ERR(trans); err = btrfs_find_free_ino(root, &objectid); if (err) goto out_unlock; inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name, dentry->d_name.len, btrfs_ino(dir), objectid, mode, &index); if (IS_ERR(inode)) { err = PTR_ERR(inode); goto out_unlock; } drop_inode_on_err = 1; err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name); if (err) goto out_unlock; err = btrfs_update_inode(trans, root, inode); if (err) goto out_unlock; /* * If the active LSM wants to access the inode during * d_instantiate it needs these. Smack checks to see * if the filesystem supports xattrs by looking at the * ops vector. */ inode->i_fop = &btrfs_file_operations; inode->i_op = &btrfs_file_inode_operations; err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index); if (err) goto out_unlock; inode->i_mapping->a_ops = &btrfs_aops; inode->i_mapping->backing_dev_info = &root->fs_info->bdi; BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops; d_instantiate(dentry, inode); out_unlock: btrfs_end_transaction(trans, root); if (err && drop_inode_on_err) { inode_dec_link_count(inode); iput(inode); } btrfs_btree_balance_dirty(root); return err; } static int btrfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(dir)->root; struct inode *inode = old_dentry->d_inode; u64 index; int err; int drop_inode = 0; /* do not allow sys_link's with other subvols of the same device */ if (root->objectid != BTRFS_I(inode)->root->objectid) return -EXDEV; if (inode->i_nlink >= BTRFS_LINK_MAX) return -EMLINK; err = btrfs_set_inode_index(dir, &index); if (err) goto fail; /* * 2 items for inode and inode ref * 2 items for dir items * 1 item for parent inode */ trans = btrfs_start_transaction(root, 5); if (IS_ERR(trans)) { err = PTR_ERR(trans); goto fail; } btrfs_inc_nlink(inode); inode_inc_iversion(inode); inode->i_ctime = CURRENT_TIME; ihold(inode); set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags); err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index); if (err) { drop_inode = 1; } else { struct dentry *parent = dentry->d_parent; err = btrfs_update_inode(trans, root, inode); if (err) goto fail; d_instantiate(dentry, inode); btrfs_log_new_name(trans, inode, NULL, parent); } btrfs_end_transaction(trans, root); fail: if (drop_inode) { inode_dec_link_count(inode); iput(inode); } btrfs_btree_balance_dirty(root); return err; } static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode) { struct inode *inode = NULL; struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(dir)->root; int err = 0; int drop_on_err = 0; u64 objectid = 0; u64 index = 0; /* * 2 items for inode and ref * 2 items for dir items * 1 for xattr if selinux is on */ trans = btrfs_start_transaction(root, 5); if (IS_ERR(trans)) return PTR_ERR(trans); err = btrfs_find_free_ino(root, &objectid); if (err) goto out_fail; inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name, dentry->d_name.len, btrfs_ino(dir), objectid, S_IFDIR | mode, &index); if (IS_ERR(inode)) { err = PTR_ERR(inode); goto out_fail; } drop_on_err = 1; err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name); if (err) goto out_fail; inode->i_op = &btrfs_dir_inode_operations; inode->i_fop = &btrfs_dir_file_operations; btrfs_i_size_write(inode, 0); err = btrfs_update_inode(trans, root, inode); if (err) goto out_fail; err = btrfs_add_link(trans, dir, inode, dentry->d_name.name, dentry->d_name.len, 0, index); if (err) goto out_fail; d_instantiate(dentry, inode); drop_on_err = 0; out_fail: btrfs_end_transaction(trans, root); if (drop_on_err) iput(inode); btrfs_btree_balance_dirty(root); return err; } /* helper for btfs_get_extent. Given an existing extent in the tree, * and an extent that you want to insert, deal with overlap and insert * the new extent into the tree. */ static int merge_extent_mapping(struct extent_map_tree *em_tree, struct extent_map *existing, struct extent_map *em, u64 map_start, u64 map_len) { u64 start_diff; BUG_ON(map_start < em->start || map_start >= extent_map_end(em)); start_diff = map_start - em->start; em->start = map_start; em->len = map_len; if (em->block_start < EXTENT_MAP_LAST_BYTE && !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) { em->block_start += start_diff; em->block_len -= start_diff; } return add_extent_mapping(em_tree, em); } static noinline int uncompress_inline(struct btrfs_path *path, struct inode *inode, struct page *page, size_t pg_offset, u64 extent_offset, struct btrfs_file_extent_item *item) { int ret; struct extent_buffer *leaf = path->nodes[0]; char *tmp; size_t max_size; unsigned long inline_size; unsigned long ptr; int compress_type; WARN_ON(pg_offset != 0); compress_type = btrfs_file_extent_compression(leaf, item); max_size = btrfs_file_extent_ram_bytes(leaf, item); inline_size = btrfs_file_extent_inline_item_len(leaf, btrfs_item_nr(leaf, path->slots[0])); tmp = kmalloc(inline_size, GFP_NOFS); if (!tmp) return -ENOMEM; ptr = btrfs_file_extent_inline_start(item); read_extent_buffer(leaf, tmp, ptr, inline_size); max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size); ret = btrfs_decompress(compress_type, tmp, page, extent_offset, inline_size, max_size); if (ret) { char *kaddr = kmap_atomic(page); unsigned long copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset, max_size - extent_offset); memset(kaddr + pg_offset, 0, copy_size); kunmap_atomic(kaddr); } kfree(tmp); return 0; } /* * a bit scary, this does extent mapping from logical file offset to the disk. * the ugly parts come from merging extents from the disk with the in-ram * representation. This gets more complex because of the data=ordered code, * where the in-ram extents might be locked pending data=ordered completion. * * This also copies inline extents directly into the page. */ struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page, size_t pg_offset, u64 start, u64 len, int create) { int ret; int err = 0; u64 bytenr; u64 extent_start = 0; u64 extent_end = 0; u64 objectid = btrfs_ino(inode); u32 found_type; struct btrfs_path *path = NULL; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_file_extent_item *item; struct extent_buffer *leaf; struct btrfs_key found_key; struct extent_map *em = NULL; struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct btrfs_trans_handle *trans = NULL; int compress_type; again: read_lock(&em_tree->lock); em = lookup_extent_mapping(em_tree, start, len); if (em) em->bdev = root->fs_info->fs_devices->latest_bdev; read_unlock(&em_tree->lock); if (em) { if (em->start > start || em->start + em->len <= start) free_extent_map(em); else if (em->block_start == EXTENT_MAP_INLINE && page) free_extent_map(em); else goto out; } em = alloc_extent_map(); if (!em) { err = -ENOMEM; goto out; } em->bdev = root->fs_info->fs_devices->latest_bdev; em->start = EXTENT_MAP_HOLE; em->orig_start = EXTENT_MAP_HOLE; em->len = (u64)-1; em->block_len = (u64)-1; if (!path) { path = btrfs_alloc_path(); if (!path) { err = -ENOMEM; goto out; } /* * Chances are we'll be called again, so go ahead and do * readahead */ path->reada = 1; } ret = btrfs_lookup_file_extent(trans, root, path, objectid, start, trans != NULL); if (ret < 0) { err = ret; goto out; } if (ret != 0) { if (path->slots[0] == 0) goto not_found; path->slots[0]--; } leaf = path->nodes[0]; item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); /* are we inside the extent that was found? */ btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); found_type = btrfs_key_type(&found_key); if (found_key.objectid != objectid || found_type != BTRFS_EXTENT_DATA_KEY) { goto not_found; } found_type = btrfs_file_extent_type(leaf, item); extent_start = found_key.offset; compress_type = btrfs_file_extent_compression(leaf, item); if (found_type == BTRFS_FILE_EXTENT_REG || found_type == BTRFS_FILE_EXTENT_PREALLOC) { extent_end = extent_start + btrfs_file_extent_num_bytes(leaf, item); } else if (found_type == BTRFS_FILE_EXTENT_INLINE) { size_t size; size = btrfs_file_extent_inline_len(leaf, item); extent_end = (extent_start + size + root->sectorsize - 1) & ~((u64)root->sectorsize - 1); } if (start >= extent_end) { path->slots[0]++; if (path->slots[0] >= btrfs_header_nritems(leaf)) { ret = btrfs_next_leaf(root, path); if (ret < 0) { err = ret; goto out; } if (ret > 0) goto not_found; leaf = path->nodes[0]; } btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); if (found_key.objectid != objectid || found_key.type != BTRFS_EXTENT_DATA_KEY) goto not_found; if (start + len <= found_key.offset) goto not_found; em->start = start; em->orig_start = start; em->len = found_key.offset - start; goto not_found_em; } if (found_type == BTRFS_FILE_EXTENT_REG || found_type == BTRFS_FILE_EXTENT_PREALLOC) { em->start = extent_start; em->len = extent_end - extent_start; em->orig_start = extent_start - btrfs_file_extent_offset(leaf, item); em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, item); bytenr = btrfs_file_extent_disk_bytenr(leaf, item); if (bytenr == 0) { em->block_start = EXTENT_MAP_HOLE; goto insert; } if (compress_type != BTRFS_COMPRESS_NONE) { set_bit(EXTENT_FLAG_COMPRESSED, &em->flags); em->compress_type = compress_type; em->block_start = bytenr; em->block_len = em->orig_block_len; } else { bytenr += btrfs_file_extent_offset(leaf, item); em->block_start = bytenr; em->block_len = em->len; if (found_type == BTRFS_FILE_EXTENT_PREALLOC) set_bit(EXTENT_FLAG_PREALLOC, &em->flags); } goto insert; } else if (found_type == BTRFS_FILE_EXTENT_INLINE) { unsigned long ptr; char *map; size_t size; size_t extent_offset; size_t copy_size; em->block_start = EXTENT_MAP_INLINE; if (!page || create) { em->start = extent_start; em->len = extent_end - extent_start; goto out; } size = btrfs_file_extent_inline_len(leaf, item); extent_offset = page_offset(page) + pg_offset - extent_start; copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset, size - extent_offset); em->start = extent_start + extent_offset; em->len = (copy_size + root->sectorsize - 1) & ~((u64)root->sectorsize - 1); em->orig_block_len = em->len; em->orig_start = em->start; if (compress_type) { set_bit(EXTENT_FLAG_COMPRESSED, &em->flags); em->compress_type = compress_type; } ptr = btrfs_file_extent_inline_start(item) + extent_offset; if (create == 0 && !PageUptodate(page)) { if (btrfs_file_extent_compression(leaf, item) != BTRFS_COMPRESS_NONE) { ret = uncompress_inline(path, inode, page, pg_offset, extent_offset, item); BUG_ON(ret); /* -ENOMEM */ } else { map = kmap(page); read_extent_buffer(leaf, map + pg_offset, ptr, copy_size); if (pg_offset + copy_size < PAGE_CACHE_SIZE) { memset(map + pg_offset + copy_size, 0, PAGE_CACHE_SIZE - pg_offset - copy_size); } kunmap(page); } flush_dcache_page(page); } else if (create && PageUptodate(page)) { BUG(); if (!trans) { kunmap(page); free_extent_map(em); em = NULL; btrfs_release_path(path); trans = btrfs_join_transaction(root); if (IS_ERR(trans)) return ERR_CAST(trans); goto again; } map = kmap(page); write_extent_buffer(leaf, map + pg_offset, ptr, copy_size); kunmap(page); btrfs_mark_buffer_dirty(leaf); } set_extent_uptodate(io_tree, em->start, extent_map_end(em) - 1, NULL, GFP_NOFS); goto insert; } else { WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type); } not_found: em->start = start; em->orig_start = start; em->len = len; not_found_em: em->block_start = EXTENT_MAP_HOLE; set_bit(EXTENT_FLAG_VACANCY, &em->flags); insert: btrfs_release_path(path); if (em->start > start || extent_map_end(em) <= start) { printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed " "[%llu %llu]\n", (unsigned long long)em->start, (unsigned long long)em->len, (unsigned long long)start, (unsigned long long)len); err = -EIO; goto out; } err = 0; write_lock(&em_tree->lock); ret = add_extent_mapping(em_tree, em); /* it is possible that someone inserted the extent into the tree * while we had the lock dropped. It is also possible that * an overlapping map exists in the tree */ if (ret == -EEXIST) { struct extent_map *existing; ret = 0; existing = lookup_extent_mapping(em_tree, start, len); if (existing && (existing->start > start || existing->start + existing->len <= start)) { free_extent_map(existing); existing = NULL; } if (!existing) { existing = lookup_extent_mapping(em_tree, em->start, em->len); if (existing) { err = merge_extent_mapping(em_tree, existing, em, start, root->sectorsize); free_extent_map(existing); if (err) { free_extent_map(em); em = NULL; } } else { err = -EIO; free_extent_map(em); em = NULL; } } else { free_extent_map(em); em = existing; err = 0; } } write_unlock(&em_tree->lock); out: if (em) trace_btrfs_get_extent(root, em); if (path) btrfs_free_path(path); if (trans) { ret = btrfs_end_transaction(trans, root); if (!err) err = ret; } if (err) { free_extent_map(em); return ERR_PTR(err); } BUG_ON(!em); /* Error is always set */ return em; } struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page, size_t pg_offset, u64 start, u64 len, int create) { struct extent_map *em; struct extent_map *hole_em = NULL; u64 range_start = start; u64 end; u64 found; u64 found_end; int err = 0; em = btrfs_get_extent(inode, page, pg_offset, start, len, create); if (IS_ERR(em)) return em; if (em) { /* * if our em maps to a hole, there might * actually be delalloc bytes behind it */ if (em->block_start != EXTENT_MAP_HOLE) return em; else hole_em = em; } /* check to see if we've wrapped (len == -1 or similar) */ end = start + len; if (end < start) end = (u64)-1; else end -= 1; em = NULL; /* ok, we didn't find anything, lets look for delalloc */ found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start, end, len, EXTENT_DELALLOC, 1); found_end = range_start + found; if (found_end < range_start) found_end = (u64)-1; /* * we didn't find anything useful, return * the original results from get_extent() */ if (range_start > end || found_end <= start) { em = hole_em; hole_em = NULL; goto out; } /* adjust the range_start to make sure it doesn't * go backwards from the start they passed in */ range_start = max(start,range_start); found = found_end - range_start; if (found > 0) { u64 hole_start = start; u64 hole_len = len; em = alloc_extent_map(); if (!em) { err = -ENOMEM; goto out; } /* * when btrfs_get_extent can't find anything it * returns one huge hole * * make sure what it found really fits our range, and * adjust to make sure it is based on the start from * the caller */ if (hole_em) { u64 calc_end = extent_map_end(hole_em); if (calc_end <= start || (hole_em->start > end)) { free_extent_map(hole_em); hole_em = NULL; } else { hole_start = max(hole_em->start, start); hole_len = calc_end - hole_start; } } em->bdev = NULL; if (hole_em && range_start > hole_start) { /* our hole starts before our delalloc, so we * have to return just the parts of the hole * that go until the delalloc starts */ em->len = min(hole_len, range_start - hole_start); em->start = hole_start; em->orig_start = hole_start; /* * don't adjust block start at all, * it is fixed at EXTENT_MAP_HOLE */ em->block_start = hole_em->block_start; em->block_len = hole_len; } else { em->start = range_start; em->len = found; em->orig_start = range_start; em->block_start = EXTENT_MAP_DELALLOC; em->block_len = found; } } else if (hole_em) { return hole_em; } out: free_extent_map(hole_em); if (err) { free_extent_map(em); return ERR_PTR(err); } return em; } static struct extent_map *btrfs_new_extent_direct(struct inode *inode, u64 start, u64 len) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; struct extent_map *em; struct btrfs_key ins; u64 alloc_hint; int ret; trans = btrfs_join_transaction(root); if (IS_ERR(trans)) return ERR_CAST(trans); trans->block_rsv = &root->fs_info->delalloc_block_rsv; alloc_hint = get_extent_allocation_hint(inode, start, len); ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0, alloc_hint, &ins, 1); if (ret) { em = ERR_PTR(ret); goto out; } em = create_pinned_em(inode, start, ins.offset, start, ins.objectid, ins.offset, ins.offset, 0); if (IS_ERR(em)) goto out; ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid, ins.offset, ins.offset, 0); if (ret) { btrfs_free_reserved_extent(root, ins.objectid, ins.offset); em = ERR_PTR(ret); } out: btrfs_end_transaction(trans, root); return em; } /* * returns 1 when the nocow is safe, < 1 on error, 0 if the * block must be cow'd */ static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans, struct inode *inode, u64 offset, u64 len) { struct btrfs_path *path; int ret; struct extent_buffer *leaf; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_file_extent_item *fi; struct btrfs_key key; u64 disk_bytenr; u64 backref_offset; u64 extent_end; u64 num_bytes; int slot; int found_type; path = btrfs_alloc_path(); if (!path) return -ENOMEM; ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode), offset, 0); if (ret < 0) goto out; slot = path->slots[0]; if (ret == 1) { if (slot == 0) { /* can't find the item, must cow */ ret = 0; goto out; } slot--; } ret = 0; leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &key, slot); if (key.objectid != btrfs_ino(inode) || key.type != BTRFS_EXTENT_DATA_KEY) { /* not our file or wrong item type, must cow */ goto out; } if (key.offset > offset) { /* Wrong offset, must cow */ goto out; } fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item); found_type = btrfs_file_extent_type(leaf, fi); if (found_type != BTRFS_FILE_EXTENT_REG && found_type != BTRFS_FILE_EXTENT_PREALLOC) { /* not a regular extent, must cow */ goto out; } disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi); backref_offset = btrfs_file_extent_offset(leaf, fi); extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi); if (extent_end < offset + len) { /* extent doesn't include our full range, must cow */ goto out; } if (btrfs_extent_readonly(root, disk_bytenr)) goto out; /* * look for other files referencing this extent, if we * find any we must cow */ if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode), key.offset - backref_offset, disk_bytenr)) goto out; /* * adjust disk_bytenr and num_bytes to cover just the bytes * in this extent we are about to write. If there * are any csums in that range we have to cow in order * to keep the csums correct */ disk_bytenr += backref_offset; disk_bytenr += offset - key.offset; num_bytes = min(offset + len, extent_end) - offset; if (csum_exist_in_range(root, disk_bytenr, num_bytes)) goto out; /* * all of the above have passed, it is safe to overwrite this extent * without cow */ ret = 1; out: btrfs_free_path(path); return ret; } static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend, struct extent_state **cached_state, int writing) { struct btrfs_ordered_extent *ordered; int ret = 0; while (1) { lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend, 0, cached_state); /* * We're concerned with the entire range that we're going to be * doing DIO to, so we need to make sure theres no ordered * extents in this range. */ ordered = btrfs_lookup_ordered_range(inode, lockstart, lockend - lockstart + 1); /* * We need to make sure there are no buffered pages in this * range either, we could have raced between the invalidate in * generic_file_direct_write and locking the extent. The * invalidate needs to happen so that reads after a write do not * get stale data. */ if (!ordered && (!writing || !test_range_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend, EXTENT_UPTODATE, 0, *cached_state))) break; unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend, cached_state, GFP_NOFS); if (ordered) { btrfs_start_ordered_extent(inode, ordered, 1); btrfs_put_ordered_extent(ordered); } else { /* Screw you mmap */ ret = filemap_write_and_wait_range(inode->i_mapping, lockstart, lockend); if (ret) break; /* * If we found a page that couldn't be invalidated just * fall back to buffered. */ ret = invalidate_inode_pages2_range(inode->i_mapping, lockstart >> PAGE_CACHE_SHIFT, lockend >> PAGE_CACHE_SHIFT); if (ret) break; } cond_resched(); } return ret; } static struct extent_map *create_pinned_em(struct inode *inode, u64 start, u64 len, u64 orig_start, u64 block_start, u64 block_len, u64 orig_block_len, int type) { struct extent_map_tree *em_tree; struct extent_map *em; struct btrfs_root *root = BTRFS_I(inode)->root; int ret; em_tree = &BTRFS_I(inode)->extent_tree; em = alloc_extent_map(); if (!em) return ERR_PTR(-ENOMEM); em->start = start; em->orig_start = orig_start; em->len = len; em->block_len = block_len; em->block_start = block_start; em->bdev = root->fs_info->fs_devices->latest_bdev; em->orig_block_len = orig_block_len; em->generation = -1; set_bit(EXTENT_FLAG_PINNED, &em->flags); if (type == BTRFS_ORDERED_PREALLOC) set_bit(EXTENT_FLAG_FILLING, &em->flags); do { btrfs_drop_extent_cache(inode, em->start, em->start + em->len - 1, 0); write_lock(&em_tree->lock); ret = add_extent_mapping(em_tree, em); if (!ret) list_move(&em->list, &em_tree->modified_extents); write_unlock(&em_tree->lock); } while (ret == -EEXIST); if (ret) { free_extent_map(em); return ERR_PTR(ret); } return em; } static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create) { struct extent_map *em; struct btrfs_root *root = BTRFS_I(inode)->root; struct extent_state *cached_state = NULL; u64 start = iblock << inode->i_blkbits; u64 lockstart, lockend; u64 len = bh_result->b_size; struct btrfs_trans_handle *trans; int unlock_bits = EXTENT_LOCKED; int ret; if (create) { ret = btrfs_delalloc_reserve_space(inode, len); if (ret) return ret; unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY; } else { len = min_t(u64, len, root->sectorsize); } lockstart = start; lockend = start + len - 1; /* * If this errors out it's because we couldn't invalidate pagecache for * this range and we need to fallback to buffered. */ if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create)) return -ENOTBLK; if (create) { ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend, EXTENT_DELALLOC, NULL, &cached_state, GFP_NOFS); if (ret) goto unlock_err; } em = btrfs_get_extent(inode, NULL, 0, start, len, 0); if (IS_ERR(em)) { ret = PTR_ERR(em); goto unlock_err; } /* * Ok for INLINE and COMPRESSED extents we need to fallback on buffered * io. INLINE is special, and we could probably kludge it in here, but * it's still buffered so for safety lets just fall back to the generic * buffered path. * * For COMPRESSED we _have_ to read the entire extent in so we can * decompress it, so there will be buffering required no matter what we * do, so go ahead and fallback to buffered. * * We return -ENOTBLK because thats what makes DIO go ahead and go back * to buffered IO. Don't blame me, this is the price we pay for using * the generic code. */ if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) || em->block_start == EXTENT_MAP_INLINE) { free_extent_map(em); ret = -ENOTBLK; goto unlock_err; } /* Just a good old fashioned hole, return */ if (!create && (em->block_start == EXTENT_MAP_HOLE || test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) { free_extent_map(em); ret = 0; goto unlock_err; } /* * We don't allocate a new extent in the following cases * * 1) The inode is marked as NODATACOW. In this case we'll just use the * existing extent. * 2) The extent is marked as PREALLOC. We're good to go here and can * just use the extent. * */ if (!create) { len = min(len, em->len - (start - em->start)); lockstart = start + len; goto unlock; } if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) || ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) && em->block_start != EXTENT_MAP_HOLE)) { int type; int ret; u64 block_start; if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) type = BTRFS_ORDERED_PREALLOC; else type = BTRFS_ORDERED_NOCOW; len = min(len, em->len - (start - em->start)); block_start = em->block_start + (start - em->start); /* * we're not going to log anything, but we do need * to make sure the current transaction stays open * while we look for nocow cross refs */ trans = btrfs_join_transaction(root); if (IS_ERR(trans)) goto must_cow; if (can_nocow_odirect(trans, inode, start, len) == 1) { u64 orig_start = em->orig_start; u64 orig_block_len = em->orig_block_len; if (type == BTRFS_ORDERED_PREALLOC) { free_extent_map(em); em = create_pinned_em(inode, start, len, orig_start, block_start, len, orig_block_len, type); if (IS_ERR(em)) { btrfs_end_transaction(trans, root); goto unlock_err; } } ret = btrfs_add_ordered_extent_dio(inode, start, block_start, len, len, type); btrfs_end_transaction(trans, root); if (ret) { free_extent_map(em); goto unlock_err; } goto unlock; } btrfs_end_transaction(trans, root); } must_cow: /* * this will cow the extent, reset the len in case we changed * it above */ len = bh_result->b_size; free_extent_map(em); em = btrfs_new_extent_direct(inode, start, len); if (IS_ERR(em)) { ret = PTR_ERR(em); goto unlock_err; } len = min(len, em->len - (start - em->start)); unlock: bh_result->b_blocknr = (em->block_start + (start - em->start)) >> inode->i_blkbits; bh_result->b_size = len; bh_result->b_bdev = em->bdev; set_buffer_mapped(bh_result); if (create) { if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) set_buffer_new(bh_result); /* * Need to update the i_size under the extent lock so buffered * readers will get the updated i_size when we unlock. */ if (start + len > i_size_read(inode)) i_size_write(inode, start + len); } /* * In the case of write we need to clear and unlock the entire range, * in the case of read we need to unlock only the end area that we * aren't using if there is any left over space. */ if (lockstart < lockend) { if (create && len < lockend - lockstart) { clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockstart + len - 1, unlock_bits | EXTENT_DEFRAG, 1, 0, &cached_state, GFP_NOFS); /* * Beside unlock, we also need to cleanup reserved space * for the left range by attaching EXTENT_DO_ACCOUNTING. */ clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart + len, lockend, unlock_bits | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 0, NULL, GFP_NOFS); } else { clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend, unlock_bits, 1, 0, &cached_state, GFP_NOFS); } } else { free_extent_state(cached_state); } free_extent_map(em); return 0; unlock_err: if (create) unlock_bits |= EXTENT_DO_ACCOUNTING; clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend, unlock_bits, 1, 0, &cached_state, GFP_NOFS); return ret; } struct btrfs_dio_private { struct inode *inode; u64 logical_offset; u64 disk_bytenr; u64 bytes; void *private; /* number of bios pending for this dio */ atomic_t pending_bios; /* IO errors */ int errors; struct bio *orig_bio; }; static void btrfs_endio_direct_read(struct bio *bio, int err) { struct btrfs_dio_private *dip = bio->bi_private; struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1; struct bio_vec *bvec = bio->bi_io_vec; struct inode *inode = dip->inode; struct btrfs_root *root = BTRFS_I(inode)->root; u64 start; start = dip->logical_offset; do { if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) { struct page *page = bvec->bv_page; char *kaddr; u32 csum = ~(u32)0; u64 private = ~(u32)0; unsigned long flags; if (get_state_private(&BTRFS_I(inode)->io_tree, start, &private)) goto failed; local_irq_save(flags); kaddr = kmap_atomic(page); csum = btrfs_csum_data(root, kaddr + bvec->bv_offset, csum, bvec->bv_len); btrfs_csum_final(csum, (char *)&csum); kunmap_atomic(kaddr); local_irq_restore(flags); flush_dcache_page(bvec->bv_page); if (csum != private) { failed: printk(KERN_ERR "btrfs csum failed ino %llu off" " %llu csum %u private %u\n", (unsigned long long)btrfs_ino(inode), (unsigned long long)start, csum, (unsigned)private); err = -EIO; } } start += bvec->bv_len; bvec++; } while (bvec <= bvec_end); unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset, dip->logical_offset + dip->bytes - 1); bio->bi_private = dip->private; kfree(dip); /* If we had a csum failure make sure to clear the uptodate flag */ if (err) clear_bit(BIO_UPTODATE, &bio->bi_flags); dio_end_io(bio, err); } static void btrfs_endio_direct_write(struct bio *bio, int err) { struct btrfs_dio_private *dip = bio->bi_private; struct inode *inode = dip->inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_ordered_extent *ordered = NULL; u64 ordered_offset = dip->logical_offset; u64 ordered_bytes = dip->bytes; int ret; if (err) goto out_done; again: ret = btrfs_dec_test_first_ordered_pending(inode, &ordered, &ordered_offset, ordered_bytes, !err); if (!ret) goto out_test; ordered->work.func = finish_ordered_fn; ordered->work.flags = 0; btrfs_queue_worker(&root->fs_info->endio_write_workers, &ordered->work); out_test: /* * our bio might span multiple ordered extents. If we haven't * completed the accounting for the whole dio, go back and try again */ if (ordered_offset < dip->logical_offset + dip->bytes) { ordered_bytes = dip->logical_offset + dip->bytes - ordered_offset; ordered = NULL; goto again; } out_done: bio->bi_private = dip->private; kfree(dip); /* If we had an error make sure to clear the uptodate flag */ if (err) clear_bit(BIO_UPTODATE, &bio->bi_flags); dio_end_io(bio, err); } static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw, struct bio *bio, int mirror_num, unsigned long bio_flags, u64 offset) { int ret; struct btrfs_root *root = BTRFS_I(inode)->root; ret = btrfs_csum_one_bio(root, inode, bio, offset, 1); BUG_ON(ret); /* -ENOMEM */ return 0; } static void btrfs_end_dio_bio(struct bio *bio, int err) { struct btrfs_dio_private *dip = bio->bi_private; if (err) { printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu " "sector %#Lx len %u err no %d\n", (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw, (unsigned long long)bio->bi_sector, bio->bi_size, err); dip->errors = 1; /* * before atomic variable goto zero, we must make sure * dip->errors is perceived to be set. */ smp_mb__before_atomic_dec(); } /* if there are more bios still pending for this dio, just exit */ if (!atomic_dec_and_test(&dip->pending_bios)) goto out; if (dip->errors) bio_io_error(dip->orig_bio); else { set_bit(BIO_UPTODATE, &dip->orig_bio->bi_flags); bio_endio(dip->orig_bio, 0); } out: bio_put(bio); } static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev, u64 first_sector, gfp_t gfp_flags) { int nr_vecs = bio_get_nr_vecs(bdev); return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags); } static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode, int rw, u64 file_offset, int skip_sum, int async_submit) { int write = rw & REQ_WRITE; struct btrfs_root *root = BTRFS_I(inode)->root; int ret; if (async_submit) async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers); bio_get(bio); if (!write) { ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0); if (ret) goto err; } if (skip_sum) goto map; if (write && async_submit) { ret = btrfs_wq_submit_bio(root->fs_info, inode, rw, bio, 0, 0, file_offset, __btrfs_submit_bio_start_direct_io, __btrfs_submit_bio_done); goto err; } else if (write) { /* * If we aren't doing async submit, calculate the csum of the * bio now. */ ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1); if (ret) goto err; } else if (!skip_sum) { ret = btrfs_lookup_bio_sums_dio(root, inode, bio, file_offset); if (ret) goto err; } map: ret = btrfs_map_bio(root, rw, bio, 0, async_submit); err: bio_put(bio); return ret; } static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip, int skip_sum) { struct inode *inode = dip->inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct bio *bio; struct bio *orig_bio = dip->orig_bio; struct bio_vec *bvec = orig_bio->bi_io_vec; u64 start_sector = orig_bio->bi_sector; u64 file_offset = dip->logical_offset; u64 submit_len = 0; u64 map_length; int nr_pages = 0; int ret = 0; int async_submit = 0; map_length = orig_bio->bi_size; ret = btrfs_map_block(root->fs_info, READ, start_sector << 9, &map_length, NULL, 0); if (ret) { bio_put(orig_bio); return -EIO; } if (map_length >= orig_bio->bi_size) { bio = orig_bio; goto submit; } async_submit = 1; bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS); if (!bio) return -ENOMEM; bio->bi_private = dip; bio->bi_end_io = btrfs_end_dio_bio; atomic_inc(&dip->pending_bios); while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) { if (unlikely(map_length < submit_len + bvec->bv_len || bio_add_page(bio, bvec->bv_page, bvec->bv_len, bvec->bv_offset) < bvec->bv_len)) { /* * inc the count before we submit the bio so * we know the end IO handler won't happen before * we inc the count. Otherwise, the dip might get freed * before we're done setting it up */ atomic_inc(&dip->pending_bios); ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum, async_submit); if (ret) { bio_put(bio); atomic_dec(&dip->pending_bios); goto out_err; } start_sector += submit_len >> 9; file_offset += submit_len; submit_len = 0; nr_pages = 0; bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS); if (!bio) goto out_err; bio->bi_private = dip; bio->bi_end_io = btrfs_end_dio_bio; map_length = orig_bio->bi_size; ret = btrfs_map_block(root->fs_info, READ, start_sector << 9, &map_length, NULL, 0); if (ret) { bio_put(bio); goto out_err; } } else { submit_len += bvec->bv_len; nr_pages ++; bvec++; } } submit: ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum, async_submit); if (!ret) return 0; bio_put(bio); out_err: dip->errors = 1; /* * before atomic variable goto zero, we must * make sure dip->errors is perceived to be set. */ smp_mb__before_atomic_dec(); if (atomic_dec_and_test(&dip->pending_bios)) bio_io_error(dip->orig_bio); /* bio_end_io() will handle error, so we needn't return it */ return 0; } static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode, loff_t file_offset) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_dio_private *dip; struct bio_vec *bvec = bio->bi_io_vec; int skip_sum; int write = rw & REQ_WRITE; int ret = 0; skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM; dip = kmalloc(sizeof(*dip), GFP_NOFS); if (!dip) { ret = -ENOMEM; goto free_ordered; } dip->private = bio->bi_private; dip->inode = inode; dip->logical_offset = file_offset; dip->bytes = 0; do { dip->bytes += bvec->bv_len; bvec++; } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1)); dip->disk_bytenr = (u64)bio->bi_sector << 9; bio->bi_private = dip; dip->errors = 0; dip->orig_bio = bio; atomic_set(&dip->pending_bios, 0); if (write) bio->bi_end_io = btrfs_endio_direct_write; else bio->bi_end_io = btrfs_endio_direct_read; ret = btrfs_submit_direct_hook(rw, dip, skip_sum); if (!ret) return; free_ordered: /* * If this is a write, we need to clean up the reserved space and kill * the ordered extent. */ if (write) { struct btrfs_ordered_extent *ordered; ordered = btrfs_lookup_ordered_extent(inode, file_offset); if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) && !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags)) btrfs_free_reserved_extent(root, ordered->start, ordered->disk_len); btrfs_put_ordered_extent(ordered); btrfs_put_ordered_extent(ordered); } bio_endio(bio, ret); } static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb, const struct iovec *iov, loff_t offset, unsigned long nr_segs) { int seg; int i; size_t size; unsigned long addr; unsigned blocksize_mask = root->sectorsize - 1; ssize_t retval = -EINVAL; loff_t end = offset; if (offset & blocksize_mask) goto out; /* Check the memory alignment. Blocks cannot straddle pages */ for (seg = 0; seg < nr_segs; seg++) { addr = (unsigned long)iov[seg].iov_base; size = iov[seg].iov_len; end += size; if ((addr & blocksize_mask) || (size & blocksize_mask)) goto out; /* If this is a write we don't need to check anymore */ if (rw & WRITE) continue; /* * Check to make sure we don't have duplicate iov_base's in this * iovec, if so return EINVAL, otherwise we'll get csum errors * when reading back. */ for (i = seg + 1; i < nr_segs; i++) { if (iov[seg].iov_base == iov[i].iov_base) goto out; } } retval = 0; out: return retval; } static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov, loff_t offset, unsigned long nr_segs) { struct file *file = iocb->ki_filp; struct inode *inode = file->f_mapping->host; if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov, offset, nr_segs)) return 0; return __blockdev_direct_IO(rw, iocb, inode, BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev, iov, offset, nr_segs, btrfs_get_blocks_direct, NULL, btrfs_submit_direct, 0); } #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC) static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, __u64 start, __u64 len) { int ret; ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS); if (ret) return ret; return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap); } int btrfs_readpage(struct file *file, struct page *page) { struct extent_io_tree *tree; tree = &BTRFS_I(page->mapping->host)->io_tree; return extent_read_full_page(tree, page, btrfs_get_extent, 0); } static int btrfs_writepage(struct page *page, struct writeback_control *wbc) { struct extent_io_tree *tree; if (current->flags & PF_MEMALLOC) { redirty_page_for_writepage(wbc, page); unlock_page(page); return 0; } tree = &BTRFS_I(page->mapping->host)->io_tree; return extent_write_full_page(tree, page, btrfs_get_extent, wbc); } int btrfs_writepages(struct address_space *mapping, struct writeback_control *wbc) { struct extent_io_tree *tree; tree = &BTRFS_I(mapping->host)->io_tree; return extent_writepages(tree, mapping, btrfs_get_extent, wbc); } static int btrfs_readpages(struct file *file, struct address_space *mapping, struct list_head *pages, unsigned nr_pages) { struct extent_io_tree *tree; tree = &BTRFS_I(mapping->host)->io_tree; return extent_readpages(tree, mapping, pages, nr_pages, btrfs_get_extent); } static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags) { struct extent_io_tree *tree; struct extent_map_tree *map; int ret; tree = &BTRFS_I(page->mapping->host)->io_tree; map = &BTRFS_I(page->mapping->host)->extent_tree; ret = try_release_extent_mapping(map, tree, page, gfp_flags); if (ret == 1) { ClearPagePrivate(page); set_page_private(page, 0); page_cache_release(page); } return ret; } static int btrfs_releasepage(struct page *page, gfp_t gfp_flags) { if (PageWriteback(page) || PageDirty(page)) return 0; return __btrfs_releasepage(page, gfp_flags & GFP_NOFS); } static void btrfs_invalidatepage(struct page *page, unsigned long offset) { struct inode *inode = page->mapping->host; struct extent_io_tree *tree; struct btrfs_ordered_extent *ordered; struct extent_state *cached_state = NULL; u64 page_start = page_offset(page); u64 page_end = page_start + PAGE_CACHE_SIZE - 1; /* * we have the page locked, so new writeback can't start, * and the dirty bit won't be cleared while we are here. * * Wait for IO on this page so that we can safely clear * the PagePrivate2 bit and do ordered accounting */ wait_on_page_writeback(page); tree = &BTRFS_I(inode)->io_tree; if (offset) { btrfs_releasepage(page, GFP_NOFS); return; } lock_extent_bits(tree, page_start, page_end, 0, &cached_state); ordered = btrfs_lookup_ordered_extent(inode, page_offset(page)); if (ordered) { /* * IO on this page will never be started, so we need * to account for any ordered extents now */ clear_extent_bit(tree, page_start, page_end, EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_LOCKED | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 0, &cached_state, GFP_NOFS); /* * whoever cleared the private bit is responsible * for the finish_ordered_io */ if (TestClearPagePrivate2(page) && btrfs_dec_test_ordered_pending(inode, &ordered, page_start, PAGE_CACHE_SIZE, 1)) { btrfs_finish_ordered_io(ordered); } btrfs_put_ordered_extent(ordered); cached_state = NULL; lock_extent_bits(tree, page_start, page_end, 0, &cached_state); } clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1, &cached_state, GFP_NOFS); __btrfs_releasepage(page, GFP_NOFS); ClearPageChecked(page); if (PagePrivate(page)) { ClearPagePrivate(page); set_page_private(page, 0); page_cache_release(page); } } /* * btrfs_page_mkwrite() is not allowed to change the file size as it gets * called from a page fault handler when a page is first dirtied. Hence we must * be careful to check for EOF conditions here. We set the page up correctly * for a written page which means we get ENOSPC checking when writing into * holes and correct delalloc and unwritten extent mapping on filesystems that * support these features. * * We are not allowed to take the i_mutex here so we have to play games to * protect against truncate races as the page could now be beyond EOF. Because * vmtruncate() writes the inode size before removing pages, once we have the * page lock we can determine safely if the page is beyond EOF. If it is not * beyond EOF, then the page is guaranteed safe against truncation until we * unlock the page. */ int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { struct page *page = vmf->page; struct inode *inode = fdentry(vma->vm_file)->d_inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct btrfs_ordered_extent *ordered; struct extent_state *cached_state = NULL; char *kaddr; unsigned long zero_start; loff_t size; int ret; int reserved = 0; u64 page_start; u64 page_end; sb_start_pagefault(inode->i_sb); ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE); if (!ret) { ret = file_update_time(vma->vm_file); reserved = 1; } if (ret) { if (ret == -ENOMEM) ret = VM_FAULT_OOM; else /* -ENOSPC, -EIO, etc */ ret = VM_FAULT_SIGBUS; if (reserved) goto out; goto out_noreserve; } ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */ again: lock_page(page); size = i_size_read(inode); page_start = page_offset(page); page_end = page_start + PAGE_CACHE_SIZE - 1; if ((page->mapping != inode->i_mapping) || (page_start >= size)) { /* page got truncated out from underneath us */ goto out_unlock; } wait_on_page_writeback(page); lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state); set_page_extent_mapped(page); /* * we can't set the delalloc bits if there are pending ordered * extents. Drop our locks and wait for them to finish */ ordered = btrfs_lookup_ordered_extent(inode, page_start); if (ordered) { unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS); unlock_page(page); btrfs_start_ordered_extent(inode, ordered, 1); btrfs_put_ordered_extent(ordered); goto again; } /* * XXX - page_mkwrite gets called every time the page is dirtied, even * if it was already dirty, so for space accounting reasons we need to * clear any delalloc bits for the range we are fixing to save. There * is probably a better way to do this, but for now keep consistent with * prepare_pages in the normal write path. */ clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end, EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS); ret = btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state); if (ret) { unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS); ret = VM_FAULT_SIGBUS; goto out_unlock; } ret = 0; /* page is wholly or partially inside EOF */ if (page_start + PAGE_CACHE_SIZE > size) zero_start = size & ~PAGE_CACHE_MASK; else zero_start = PAGE_CACHE_SIZE; if (zero_start != PAGE_CACHE_SIZE) { kaddr = kmap(page); memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start); flush_dcache_page(page); kunmap(page); } ClearPageChecked(page); set_page_dirty(page); SetPageUptodate(page); BTRFS_I(inode)->last_trans = root->fs_info->generation; BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid; BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit; unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS); out_unlock: if (!ret) { sb_end_pagefault(inode->i_sb); return VM_FAULT_LOCKED; } unlock_page(page); out: btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE); out_noreserve: sb_end_pagefault(inode->i_sb); return ret; } static int btrfs_truncate(struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_block_rsv *rsv; int ret; int err = 0; struct btrfs_trans_handle *trans; u64 mask = root->sectorsize - 1; u64 min_size = btrfs_calc_trunc_metadata_size(root, 1); ret = btrfs_truncate_page(inode, inode->i_size, 0, 0); if (ret) return ret; btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1); btrfs_ordered_update_i_size(inode, inode->i_size, NULL); /* * Yes ladies and gentelment, this is indeed ugly. The fact is we have * 3 things going on here * * 1) We need to reserve space for our orphan item and the space to * delete our orphan item. Lord knows we don't want to have a dangling * orphan item because we didn't reserve space to remove it. * * 2) We need to reserve space to update our inode. * * 3) We need to have something to cache all the space that is going to * be free'd up by the truncate operation, but also have some slack * space reserved in case it uses space during the truncate (thank you * very much snapshotting). * * And we need these to all be seperate. The fact is we can use alot of * space doing the truncate, and we have no earthly idea how much space * we will use, so we need the truncate reservation to be seperate so it * doesn't end up using space reserved for updating the inode or * removing the orphan item. We also need to be able to stop the * transaction and start a new one, which means we need to be able to * update the inode several times, and we have no idea of knowing how * many times that will be, so we can't just reserve 1 item for the * entirety of the opration, so that has to be done seperately as well. * Then there is the orphan item, which does indeed need to be held on * to for the whole operation, and we need nobody to touch this reserved * space except the orphan code. * * So that leaves us with * * 1) root->orphan_block_rsv - for the orphan deletion. * 2) rsv - for the truncate reservation, which we will steal from the * transaction reservation. * 3) fs_info->trans_block_rsv - this will have 1 items worth left for * updating the inode. */ rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP); if (!rsv) return -ENOMEM; rsv->size = min_size; rsv->failfast = 1; /* * 1 for the truncate slack space * 1 for the orphan item we're going to add * 1 for the orphan item deletion * 1 for updating the inode. */ trans = btrfs_start_transaction(root, 4); if (IS_ERR(trans)) { err = PTR_ERR(trans); goto out; } /* Migrate the slack space for the truncate to our reserve */ ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv, min_size); BUG_ON(ret); ret = btrfs_orphan_add(trans, inode); if (ret) { btrfs_end_transaction(trans, root); goto out; } /* * setattr is responsible for setting the ordered_data_close flag, * but that is only tested during the last file release. That * could happen well after the next commit, leaving a great big * window where new writes may get lost if someone chooses to write * to this file after truncating to zero * * The inode doesn't have any dirty data here, and so if we commit * this is a noop. If someone immediately starts writing to the inode * it is very likely we'll catch some of their writes in this * transaction, and the commit will find this file on the ordered * data list with good things to send down. * * This is a best effort solution, there is still a window where * using truncate to replace the contents of the file will * end up with a zero length file after a crash. */ if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE, &BTRFS_I(inode)->runtime_flags)) btrfs_add_ordered_operation(trans, root, inode); /* * So if we truncate and then write and fsync we normally would just * write the extents that changed, which is a problem if we need to * first truncate that entire inode. So set this flag so we write out * all of the extents in the inode to the sync log so we're completely * safe. */ set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags); trans->block_rsv = rsv; while (1) { ret = btrfs_truncate_inode_items(trans, root, inode, inode->i_size, BTRFS_EXTENT_DATA_KEY); if (ret != -ENOSPC) { err = ret; break; } trans->block_rsv = &root->fs_info->trans_block_rsv; ret = btrfs_update_inode(trans, root, inode); if (ret) { err = ret; break; } btrfs_end_transaction(trans, root); btrfs_btree_balance_dirty(root); trans = btrfs_start_transaction(root, 2); if (IS_ERR(trans)) { ret = err = PTR_ERR(trans); trans = NULL; break; } ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv, min_size); BUG_ON(ret); /* shouldn't happen */ trans->block_rsv = rsv; } if (ret == 0 && inode->i_nlink > 0) { trans->block_rsv = root->orphan_block_rsv; ret = btrfs_orphan_del(trans, inode); if (ret) err = ret; } else if (ret && inode->i_nlink > 0) { /* * Failed to do the truncate, remove us from the in memory * orphan list. */ ret = btrfs_orphan_del(NULL, inode); } if (trans) { trans->block_rsv = &root->fs_info->trans_block_rsv; ret = btrfs_update_inode(trans, root, inode); if (ret && !err) err = ret; ret = btrfs_end_transaction(trans, root); btrfs_btree_balance_dirty(root); } out: btrfs_free_block_rsv(root, rsv); if (ret && !err) err = ret; return err; } /* * create a new subvolume directory/inode (helper for the ioctl). */ int btrfs_create_subvol_root(struct btrfs_trans_handle *trans, struct btrfs_root *new_root, u64 new_dirid) { struct inode *inode; int err; u64 index = 0; inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, new_dirid, new_dirid, S_IFDIR | (~current_umask() & S_IRWXUGO), &index); if (IS_ERR(inode)) return PTR_ERR(inode); inode->i_op = &btrfs_dir_inode_operations; inode->i_fop = &btrfs_dir_file_operations; set_nlink(inode, 1); btrfs_i_size_write(inode, 0); err = btrfs_update_inode(trans, new_root, inode); iput(inode); return err; } struct inode *btrfs_alloc_inode(struct super_block *sb) { struct btrfs_inode *ei; struct inode *inode; ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS); if (!ei) return NULL; ei->root = NULL; ei->generation = 0; ei->last_trans = 0; ei->last_sub_trans = 0; ei->logged_trans = 0; ei->delalloc_bytes = 0; ei->disk_i_size = 0; ei->flags = 0; ei->csum_bytes = 0; ei->index_cnt = (u64)-1; ei->last_unlink_trans = 0; ei->last_log_commit = 0; spin_lock_init(&ei->lock); ei->outstanding_extents = 0; ei->reserved_extents = 0; ei->runtime_flags = 0; ei->force_compress = BTRFS_COMPRESS_NONE; ei->delayed_node = NULL; inode = &ei->vfs_inode; extent_map_tree_init(&ei->extent_tree); extent_io_tree_init(&ei->io_tree, &inode->i_data); extent_io_tree_init(&ei->io_failure_tree, &inode->i_data); ei->io_tree.track_uptodate = 1; ei->io_failure_tree.track_uptodate = 1; atomic_set(&ei->sync_writers, 0); mutex_init(&ei->log_mutex); mutex_init(&ei->delalloc_mutex); btrfs_ordered_inode_tree_init(&ei->ordered_tree); INIT_LIST_HEAD(&ei->delalloc_inodes); INIT_LIST_HEAD(&ei->ordered_operations); RB_CLEAR_NODE(&ei->rb_node); return inode; } static void btrfs_i_callback(struct rcu_head *head) { struct inode *inode = container_of(head, struct inode, i_rcu); kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode)); } void btrfs_destroy_inode(struct inode *inode) { struct btrfs_ordered_extent *ordered; struct btrfs_root *root = BTRFS_I(inode)->root; WARN_ON(!hlist_empty(&inode->i_dentry)); WARN_ON(inode->i_data.nrpages); WARN_ON(BTRFS_I(inode)->outstanding_extents); WARN_ON(BTRFS_I(inode)->reserved_extents); WARN_ON(BTRFS_I(inode)->delalloc_bytes); WARN_ON(BTRFS_I(inode)->csum_bytes); /* * This can happen where we create an inode, but somebody else also * created the same inode and we need to destroy the one we already * created. */ if (!root) goto free; /* * Make sure we're properly removed from the ordered operation * lists. */ smp_mb(); if (!list_empty(&BTRFS_I(inode)->ordered_operations)) { spin_lock(&root->fs_info->ordered_extent_lock); list_del_init(&BTRFS_I(inode)->ordered_operations); spin_unlock(&root->fs_info->ordered_extent_lock); } if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM, &BTRFS_I(inode)->runtime_flags)) { printk(KERN_INFO "BTRFS: inode %llu still on the orphan list\n", (unsigned long long)btrfs_ino(inode)); atomic_dec(&root->orphan_inodes); } while (1) { ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1); if (!ordered) break; else { printk(KERN_ERR "btrfs found ordered " "extent %llu %llu on inode cleanup\n", (unsigned long long)ordered->file_offset, (unsigned long long)ordered->len); btrfs_remove_ordered_extent(inode, ordered); btrfs_put_ordered_extent(ordered); btrfs_put_ordered_extent(ordered); } } inode_tree_del(inode); btrfs_drop_extent_cache(inode, 0, (u64)-1, 0); free: btrfs_remove_delayed_node(inode); call_rcu(&inode->i_rcu, btrfs_i_callback); } int btrfs_drop_inode(struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; if (btrfs_root_refs(&root->root_item) == 0 && !btrfs_is_free_space_inode(inode)) return 1; else return generic_drop_inode(inode); } static void init_once(void *foo) { struct btrfs_inode *ei = (struct btrfs_inode *) foo; inode_init_once(&ei->vfs_inode); } void btrfs_destroy_cachep(void) { /* * Make sure all delayed rcu free inodes are flushed before we * destroy cache. */ rcu_barrier(); if (btrfs_inode_cachep) kmem_cache_destroy(btrfs_inode_cachep); if (btrfs_trans_handle_cachep) kmem_cache_destroy(btrfs_trans_handle_cachep); if (btrfs_transaction_cachep) kmem_cache_destroy(btrfs_transaction_cachep); if (btrfs_path_cachep) kmem_cache_destroy(btrfs_path_cachep); if (btrfs_free_space_cachep) kmem_cache_destroy(btrfs_free_space_cachep); if (btrfs_delalloc_work_cachep) kmem_cache_destroy(btrfs_delalloc_work_cachep); } int btrfs_init_cachep(void) { btrfs_inode_cachep = kmem_cache_create("btrfs_inode", sizeof(struct btrfs_inode), 0, SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once); if (!btrfs_inode_cachep) goto fail; btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle", sizeof(struct btrfs_trans_handle), 0, SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL); if (!btrfs_trans_handle_cachep) goto fail; btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction", sizeof(struct btrfs_transaction), 0, SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL); if (!btrfs_transaction_cachep) goto fail; btrfs_path_cachep = kmem_cache_create("btrfs_path", sizeof(struct btrfs_path), 0, SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL); if (!btrfs_path_cachep) goto fail; btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space", sizeof(struct btrfs_free_space), 0, SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL); if (!btrfs_free_space_cachep) goto fail; btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work", sizeof(struct btrfs_delalloc_work), 0, SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL); if (!btrfs_delalloc_work_cachep) goto fail; return 0; fail: btrfs_destroy_cachep(); return -ENOMEM; } static int btrfs_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat) { struct inode *inode = dentry->d_inode; u32 blocksize = inode->i_sb->s_blocksize; generic_fillattr(inode, stat); stat->dev = BTRFS_I(inode)->root->anon_dev; stat->blksize = PAGE_CACHE_SIZE; stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) + ALIGN(BTRFS_I(inode)->delalloc_bytes, blocksize)) >> 9; return 0; } /* * If a file is moved, it will inherit the cow and compression flags of the new * directory. */ static void fixup_inode_flags(struct inode *dir, struct inode *inode) { struct btrfs_inode *b_dir = BTRFS_I(dir); struct btrfs_inode *b_inode = BTRFS_I(inode); if (b_dir->flags & BTRFS_INODE_NODATACOW) b_inode->flags |= BTRFS_INODE_NODATACOW; else b_inode->flags &= ~BTRFS_INODE_NODATACOW; if (b_dir->flags & BTRFS_INODE_COMPRESS) { b_inode->flags |= BTRFS_INODE_COMPRESS; b_inode->flags &= ~BTRFS_INODE_NOCOMPRESS; } else { b_inode->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS); } } static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(old_dir)->root; struct btrfs_root *dest = BTRFS_I(new_dir)->root; struct inode *new_inode = new_dentry->d_inode; struct inode *old_inode = old_dentry->d_inode; struct timespec ctime = CURRENT_TIME; u64 index = 0; u64 root_objectid; int ret; u64 old_ino = btrfs_ino(old_inode); if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) return -EPERM; /* we only allow rename subvolume link between subvolumes */ if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest) return -EXDEV; if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID || (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID)) return -ENOTEMPTY; if (S_ISDIR(old_inode->i_mode) && new_inode && new_inode->i_size > BTRFS_EMPTY_DIR_SIZE) return -ENOTEMPTY; /* * we're using rename to replace one file with another. * and the replacement file is large. Start IO on it now so * we don't add too much work to the end of the transaction */ if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size && old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT) filemap_flush(old_inode->i_mapping); /* close the racy window with snapshot create/destroy ioctl */ if (old_ino == BTRFS_FIRST_FREE_OBJECTID) down_read(&root->fs_info->subvol_sem); /* * We want to reserve the absolute worst case amount of items. So if * both inodes are subvols and we need to unlink them then that would * require 4 item modifications, but if they are both normal inodes it * would require 5 item modifications, so we'll assume their normal * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items * should cover the worst case number of items we'll modify. */ trans = btrfs_start_transaction(root, 20); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out_notrans; } if (dest != root) btrfs_record_root_in_trans(trans, dest); ret = btrfs_set_inode_index(new_dir, &index); if (ret) goto out_fail; if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) { /* force full log commit if subvolume involved. */ root->fs_info->last_trans_log_full_commit = trans->transid; } else { ret = btrfs_insert_inode_ref(trans, dest, new_dentry->d_name.name, new_dentry->d_name.len, old_ino, btrfs_ino(new_dir), index); if (ret) goto out_fail; /* * this is an ugly little race, but the rename is required * to make sure that if we crash, the inode is either at the * old name or the new one. pinning the log transaction lets * us make sure we don't allow a log commit to come in after * we unlink the name but before we add the new name back in. */ btrfs_pin_log_trans(root); } /* * make sure the inode gets flushed if it is replacing * something. */ if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode)) btrfs_add_ordered_operation(trans, root, old_inode); inode_inc_iversion(old_dir); inode_inc_iversion(new_dir); inode_inc_iversion(old_inode); old_dir->i_ctime = old_dir->i_mtime = ctime; new_dir->i_ctime = new_dir->i_mtime = ctime; old_inode->i_ctime = ctime; if (old_dentry->d_parent != new_dentry->d_parent) btrfs_record_unlink_dir(trans, old_dir, old_inode, 1); if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) { root_objectid = BTRFS_I(old_inode)->root->root_key.objectid; ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid, old_dentry->d_name.name, old_dentry->d_name.len); } else { ret = __btrfs_unlink_inode(trans, root, old_dir, old_dentry->d_inode, old_dentry->d_name.name, old_dentry->d_name.len); if (!ret) ret = btrfs_update_inode(trans, root, old_inode); } if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_fail; } if (new_inode) { inode_inc_iversion(new_inode); new_inode->i_ctime = CURRENT_TIME; if (unlikely(btrfs_ino(new_inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) { root_objectid = BTRFS_I(new_inode)->location.objectid; ret = btrfs_unlink_subvol(trans, dest, new_dir, root_objectid, new_dentry->d_name.name, new_dentry->d_name.len); BUG_ON(new_inode->i_nlink == 0); } else { ret = btrfs_unlink_inode(trans, dest, new_dir, new_dentry->d_inode, new_dentry->d_name.name, new_dentry->d_name.len); } if (!ret && new_inode->i_nlink == 0) { ret = btrfs_orphan_add(trans, new_dentry->d_inode); BUG_ON(ret); } if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_fail; } } fixup_inode_flags(new_dir, old_inode); ret = btrfs_add_link(trans, new_dir, old_inode, new_dentry->d_name.name, new_dentry->d_name.len, 0, index); if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_fail; } if (old_ino != BTRFS_FIRST_FREE_OBJECTID) { struct dentry *parent = new_dentry->d_parent; btrfs_log_new_name(trans, old_inode, old_dir, parent); btrfs_end_log_trans(root); } out_fail: btrfs_end_transaction(trans, root); out_notrans: if (old_ino == BTRFS_FIRST_FREE_OBJECTID) up_read(&root->fs_info->subvol_sem); return ret; } static void btrfs_run_delalloc_work(struct btrfs_work *work) { struct btrfs_delalloc_work *delalloc_work; delalloc_work = container_of(work, struct btrfs_delalloc_work, work); if (delalloc_work->wait) btrfs_wait_ordered_range(delalloc_work->inode, 0, (u64)-1); else filemap_flush(delalloc_work->inode->i_mapping); if (delalloc_work->delay_iput) btrfs_add_delayed_iput(delalloc_work->inode); else iput(delalloc_work->inode); complete(&delalloc_work->completion); } struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode, int wait, int delay_iput) { struct btrfs_delalloc_work *work; work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS); if (!work) return NULL; init_completion(&work->completion); INIT_LIST_HEAD(&work->list); work->inode = inode; work->wait = wait; work->delay_iput = delay_iput; work->work.func = btrfs_run_delalloc_work; return work; } void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work) { wait_for_completion(&work->completion); kmem_cache_free(btrfs_delalloc_work_cachep, work); } /* * some fairly slow code that needs optimization. This walks the list * of all the inodes with pending delalloc and forces them to disk. */ int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput) { struct list_head *head = &root->fs_info->delalloc_inodes; struct btrfs_inode *binode; struct inode *inode; struct btrfs_delalloc_work *work, *next; struct list_head works; int ret = 0; if (root->fs_info->sb->s_flags & MS_RDONLY) return -EROFS; INIT_LIST_HEAD(&works); spin_lock(&root->fs_info->delalloc_lock); while (!list_empty(head)) { binode = list_entry(head->next, struct btrfs_inode, delalloc_inodes); inode = igrab(&binode->vfs_inode); if (!inode) list_del_init(&binode->delalloc_inodes); spin_unlock(&root->fs_info->delalloc_lock); if (inode) { work = btrfs_alloc_delalloc_work(inode, 0, delay_iput); if (!work) { ret = -ENOMEM; goto out; } list_add_tail(&work->list, &works); btrfs_queue_worker(&root->fs_info->flush_workers, &work->work); } cond_resched(); spin_lock(&root->fs_info->delalloc_lock); } spin_unlock(&root->fs_info->delalloc_lock); /* the filemap_flush will queue IO into the worker threads, but * we have to make sure the IO is actually started and that * ordered extents get created before we return */ atomic_inc(&root->fs_info->async_submit_draining); while (atomic_read(&root->fs_info->nr_async_submits) || atomic_read(&root->fs_info->async_delalloc_pages)) { wait_event(root->fs_info->async_submit_wait, (atomic_read(&root->fs_info->nr_async_submits) == 0 && atomic_read(&root->fs_info->async_delalloc_pages) == 0)); } atomic_dec(&root->fs_info->async_submit_draining); out: list_for_each_entry_safe(work, next, &works, list) { list_del_init(&work->list); btrfs_wait_and_free_delalloc_work(work); } return ret; } static int btrfs_symlink(struct inode *dir, struct dentry *dentry, const char *symname) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(dir)->root; struct btrfs_path *path; struct btrfs_key key; struct inode *inode = NULL; int err; int drop_inode = 0; u64 objectid; u64 index = 0 ; int name_len; int datasize; unsigned long ptr; struct btrfs_file_extent_item *ei; struct extent_buffer *leaf; name_len = strlen(symname) + 1; if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root)) return -ENAMETOOLONG; /* * 2 items for inode item and ref * 2 items for dir items * 1 item for xattr if selinux is on */ trans = btrfs_start_transaction(root, 5); if (IS_ERR(trans)) return PTR_ERR(trans); err = btrfs_find_free_ino(root, &objectid); if (err) goto out_unlock; inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name, dentry->d_name.len, btrfs_ino(dir), objectid, S_IFLNK|S_IRWXUGO, &index); if (IS_ERR(inode)) { err = PTR_ERR(inode); goto out_unlock; } err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name); if (err) { drop_inode = 1; goto out_unlock; } /* * If the active LSM wants to access the inode during * d_instantiate it needs these. Smack checks to see * if the filesystem supports xattrs by looking at the * ops vector. */ inode->i_fop = &btrfs_file_operations; inode->i_op = &btrfs_file_inode_operations; err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index); if (err) drop_inode = 1; else { inode->i_mapping->a_ops = &btrfs_aops; inode->i_mapping->backing_dev_info = &root->fs_info->bdi; BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops; } if (drop_inode) goto out_unlock; path = btrfs_alloc_path(); if (!path) { err = -ENOMEM; drop_inode = 1; goto out_unlock; } key.objectid = btrfs_ino(inode); key.offset = 0; btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY); datasize = btrfs_file_extent_calc_inline_size(name_len); err = btrfs_insert_empty_item(trans, root, path, &key, datasize); if (err) { drop_inode = 1; btrfs_free_path(path); goto out_unlock; } leaf = path->nodes[0]; ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); btrfs_set_file_extent_generation(leaf, ei, trans->transid); btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE); btrfs_set_file_extent_encryption(leaf, ei, 0); btrfs_set_file_extent_compression(leaf, ei, 0); btrfs_set_file_extent_other_encoding(leaf, ei, 0); btrfs_set_file_extent_ram_bytes(leaf, ei, name_len); ptr = btrfs_file_extent_inline_start(ei); write_extent_buffer(leaf, symname, ptr, name_len); btrfs_mark_buffer_dirty(leaf); btrfs_free_path(path); inode->i_op = &btrfs_symlink_inode_operations; inode->i_mapping->a_ops = &btrfs_symlink_aops; inode->i_mapping->backing_dev_info = &root->fs_info->bdi; inode_set_bytes(inode, name_len); btrfs_i_size_write(inode, name_len - 1); err = btrfs_update_inode(trans, root, inode); if (err) drop_inode = 1; out_unlock: if (!err) d_instantiate(dentry, inode); btrfs_end_transaction(trans, root); if (drop_inode) { inode_dec_link_count(inode); iput(inode); } btrfs_btree_balance_dirty(root); return err; } static int __btrfs_prealloc_file_range(struct inode *inode, int mode, u64 start, u64 num_bytes, u64 min_size, loff_t actual_len, u64 *alloc_hint, struct btrfs_trans_handle *trans) { struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; struct extent_map *em; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_key ins; u64 cur_offset = start; u64 i_size; int ret = 0; bool own_trans = true; if (trans) own_trans = false; while (num_bytes > 0) { if (own_trans) { trans = btrfs_start_transaction(root, 3); if (IS_ERR(trans)) { ret = PTR_ERR(trans); break; } } ret = btrfs_reserve_extent(trans, root, num_bytes, min_size, 0, *alloc_hint, &ins, 1); if (ret) { if (own_trans) btrfs_end_transaction(trans, root); break; } ret = insert_reserved_file_extent(trans, inode, cur_offset, ins.objectid, ins.offset, ins.offset, ins.offset, 0, 0, 0, BTRFS_FILE_EXTENT_PREALLOC); if (ret) { btrfs_abort_transaction(trans, root, ret); if (own_trans) btrfs_end_transaction(trans, root); break; } btrfs_drop_extent_cache(inode, cur_offset, cur_offset + ins.offset -1, 0); em = alloc_extent_map(); if (!em) { set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags); goto next; } em->start = cur_offset; em->orig_start = cur_offset; em->len = ins.offset; em->block_start = ins.objectid; em->block_len = ins.offset; em->orig_block_len = ins.offset; em->bdev = root->fs_info->fs_devices->latest_bdev; set_bit(EXTENT_FLAG_PREALLOC, &em->flags); em->generation = trans->transid; while (1) { write_lock(&em_tree->lock); ret = add_extent_mapping(em_tree, em); if (!ret) list_move(&em->list, &em_tree->modified_extents); write_unlock(&em_tree->lock); if (ret != -EEXIST) break; btrfs_drop_extent_cache(inode, cur_offset, cur_offset + ins.offset - 1, 0); } free_extent_map(em); next: num_bytes -= ins.offset; cur_offset += ins.offset; *alloc_hint = ins.objectid + ins.offset; inode_inc_iversion(inode); inode->i_ctime = CURRENT_TIME; BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC; if (!(mode & FALLOC_FL_KEEP_SIZE) && (actual_len > inode->i_size) && (cur_offset > inode->i_size)) { if (cur_offset > actual_len) i_size = actual_len; else i_size = cur_offset; i_size_write(inode, i_size); btrfs_ordered_update_i_size(inode, i_size, NULL); } ret = btrfs_update_inode(trans, root, inode); if (ret) { btrfs_abort_transaction(trans, root, ret); if (own_trans) btrfs_end_transaction(trans, root); break; } if (own_trans) btrfs_end_transaction(trans, root); } return ret; } int btrfs_prealloc_file_range(struct inode *inode, int mode, u64 start, u64 num_bytes, u64 min_size, loff_t actual_len, u64 *alloc_hint) { return __btrfs_prealloc_file_range(inode, mode, start, num_bytes, min_size, actual_len, alloc_hint, NULL); } int btrfs_prealloc_file_range_trans(struct inode *inode, struct btrfs_trans_handle *trans, int mode, u64 start, u64 num_bytes, u64 min_size, loff_t actual_len, u64 *alloc_hint) { return __btrfs_prealloc_file_range(inode, mode, start, num_bytes, min_size, actual_len, alloc_hint, trans); } static int btrfs_set_page_dirty(struct page *page) { return __set_page_dirty_nobuffers(page); } static int btrfs_permission(struct inode *inode, int mask) { struct btrfs_root *root = BTRFS_I(inode)->root; umode_t mode = inode->i_mode; if (mask & MAY_WRITE && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) { if (btrfs_root_readonly(root)) return -EROFS; if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY) return -EACCES; } return generic_permission(inode, mask); } static const struct inode_operations btrfs_dir_inode_operations = { .getattr = btrfs_getattr, .lookup = btrfs_lookup, .create = btrfs_create, .unlink = btrfs_unlink, .link = btrfs_link, .mkdir = btrfs_mkdir, .rmdir = btrfs_rmdir, .rename = btrfs_rename, .symlink = btrfs_symlink, .setattr = btrfs_setattr, .mknod = btrfs_mknod, .setxattr = btrfs_setxattr, .getxattr = btrfs_getxattr, .listxattr = btrfs_listxattr, .removexattr = btrfs_removexattr, .permission = btrfs_permission, .get_acl = btrfs_get_acl, }; static const struct inode_operations btrfs_dir_ro_inode_operations = { .lookup = btrfs_lookup, .permission = btrfs_permission, .get_acl = btrfs_get_acl, }; static const struct file_operations btrfs_dir_file_operations = { .llseek = generic_file_llseek, .read = generic_read_dir, .readdir = btrfs_real_readdir, .unlocked_ioctl = btrfs_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = btrfs_ioctl, #endif .release = btrfs_release_file, .fsync = btrfs_sync_file, }; static struct extent_io_ops btrfs_extent_io_ops = { .fill_delalloc = run_delalloc_range, .submit_bio_hook = btrfs_submit_bio_hook, .merge_bio_hook = btrfs_merge_bio_hook, .readpage_end_io_hook = btrfs_readpage_end_io_hook, .writepage_end_io_hook = btrfs_writepage_end_io_hook, .writepage_start_hook = btrfs_writepage_start_hook, .set_bit_hook = btrfs_set_bit_hook, .clear_bit_hook = btrfs_clear_bit_hook, .merge_extent_hook = btrfs_merge_extent_hook, .split_extent_hook = btrfs_split_extent_hook, }; /* * btrfs doesn't support the bmap operation because swapfiles * use bmap to make a mapping of extents in the file. They assume * these extents won't change over the life of the file and they * use the bmap result to do IO directly to the drive. * * the btrfs bmap call would return logical addresses that aren't * suitable for IO and they also will change frequently as COW * operations happen. So, swapfile + btrfs == corruption. * * For now we're avoiding this by dropping bmap. */ static const struct address_space_operations btrfs_aops = { .readpage = btrfs_readpage, .writepage = btrfs_writepage, .writepages = btrfs_writepages, .readpages = btrfs_readpages, .direct_IO = btrfs_direct_IO, .invalidatepage = btrfs_invalidatepage, .releasepage = btrfs_releasepage, .set_page_dirty = btrfs_set_page_dirty, .error_remove_page = generic_error_remove_page, }; static const struct address_space_operations btrfs_symlink_aops = { .readpage = btrfs_readpage, .writepage = btrfs_writepage, .invalidatepage = btrfs_invalidatepage, .releasepage = btrfs_releasepage, }; static const struct inode_operations btrfs_file_inode_operations = { .getattr = btrfs_getattr, .setattr = btrfs_setattr, .setxattr = btrfs_setxattr, .getxattr = btrfs_getxattr, .listxattr = btrfs_listxattr, .removexattr = btrfs_removexattr, .permission = btrfs_permission, .fiemap = btrfs_fiemap, .get_acl = btrfs_get_acl, .update_time = btrfs_update_time, }; static const struct inode_operations btrfs_special_inode_operations = { .getattr = btrfs_getattr, .setattr = btrfs_setattr, .permission = btrfs_permission, .setxattr = btrfs_setxattr, .getxattr = btrfs_getxattr, .listxattr = btrfs_listxattr, .removexattr = btrfs_removexattr, .get_acl = btrfs_get_acl, .update_time = btrfs_update_time, }; static const struct inode_operations btrfs_symlink_inode_operations = { .readlink = generic_readlink, .follow_link = page_follow_link_light, .put_link = page_put_link, .getattr = btrfs_getattr, .setattr = btrfs_setattr, .permission = btrfs_permission, .setxattr = btrfs_setxattr, .getxattr = btrfs_getxattr, .listxattr = btrfs_listxattr, .removexattr = btrfs_removexattr, .get_acl = btrfs_get_acl, .update_time = btrfs_update_time, }; const struct dentry_operations btrfs_dentry_operations = { .d_delete = btrfs_dentry_delete, .d_release = btrfs_dentry_release, };
./CrossVul/dataset_final_sorted/CWE-310/c/bad_3783_2
crossvul-cpp_data_good_2152_1
/* ssl/s3_clnt.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ /* ==================================================================== * Copyright (c) 1998-2007 The OpenSSL 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: * * 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. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* ==================================================================== * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * * Portions of the attached software ("Contribution") are developed by * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project. * * The Contribution is licensed pursuant to the OpenSSL open source * license provided above. * * ECC cipher suite support in OpenSSL originally written by * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories. * */ /* ==================================================================== * Copyright 2005 Nokia. All rights reserved. * * The portions of the attached software ("Contribution") is developed by * Nokia Corporation and is licensed pursuant to the OpenSSL open source * license. * * The Contribution, originally written by Mika Kousa and Pasi Eronen of * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites * support (see RFC 4279) to OpenSSL. * * No patent licenses or other rights except those expressly stated in * the OpenSSL open source license shall be deemed granted or received * expressly, by implication, estoppel, or otherwise. * * No assurances are provided by Nokia that the Contribution does not * infringe the patent or other intellectual property rights of any third * party or that the license provides you with all the necessary rights * to make use of the Contribution. * * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR * OTHERWISE. */ #include <stdio.h> #include "ssl_locl.h" #include "kssl_lcl.h" #include <openssl/buffer.h> #include <openssl/rand.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/md5.h> #ifndef OPENSSL_NO_DH #include <openssl/dh.h> #endif #include <openssl/bn.h> #ifndef OPENSSL_NO_ENGINE #include <openssl/engine.h> #endif static int ca_dn_cmp(const X509_NAME * const *a,const X509_NAME * const *b); #ifndef OPENSSL_NO_SSL3_METHOD static const SSL_METHOD *ssl3_get_client_method(int ver) { if (ver == SSL3_VERSION) return(SSLv3_client_method()); else return(NULL); } IMPLEMENT_ssl3_meth_func(SSLv3_client_method, ssl_undefined_function, ssl3_connect, ssl3_get_client_method) #endif int ssl3_connect(SSL *s) { BUF_MEM *buf=NULL; unsigned long Time=(unsigned long)time(NULL); void (*cb)(const SSL *ssl,int type,int val)=NULL; int ret= -1; int new_state,state,skip=0; RAND_add(&Time,sizeof(Time),0); ERR_clear_error(); clear_sys_error(); if (s->info_callback != NULL) cb=s->info_callback; else if (s->ctx->info_callback != NULL) cb=s->ctx->info_callback; s->in_handshake++; if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); #ifndef OPENSSL_NO_HEARTBEATS /* If we're awaiting a HeartbeatResponse, pretend we * already got and don't await it anymore, because * Heartbeats don't make sense during handshakes anyway. */ if (s->tlsext_hb_pending) { s->tlsext_hb_pending = 0; s->tlsext_hb_seq++; } #endif for (;;) { state=s->state; switch(s->state) { case SSL_ST_RENEGOTIATE: s->renegotiate=1; s->state=SSL_ST_CONNECT; s->ctx->stats.sess_connect_renegotiate++; /* break */ case SSL_ST_BEFORE: case SSL_ST_CONNECT: case SSL_ST_BEFORE|SSL_ST_CONNECT: case SSL_ST_OK|SSL_ST_CONNECT: s->server=0; if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1); if ((s->version & 0xff00 ) != 0x0300) { SSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR); ret = -1; goto end; } if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) { SSLerr(SSL_F_SSL3_CONNECT, SSL_R_VERSION_TOO_LOW); return -1; } /* s->version=SSL3_VERSION; */ s->type=SSL_ST_CONNECT; if (s->init_buf == NULL) { if ((buf=BUF_MEM_new()) == NULL) { ret= -1; goto end; } if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH)) { ret= -1; goto end; } s->init_buf=buf; buf=NULL; } if (!ssl3_setup_buffers(s)) { ret= -1; goto end; } /* setup buffing BIO */ if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; } /* don't push the buffering BIO quite yet */ ssl3_init_finished_mac(s); s->state=SSL3_ST_CW_CLNT_HELLO_A; s->ctx->stats.sess_connect++; s->init_num=0; s->s3->flags &= ~SSL3_FLAGS_CCS_OK; /* Should have been reset by ssl3_get_finished, too. */ s->s3->change_cipher_spec = 0; break; case SSL3_ST_CW_CLNT_HELLO_A: case SSL3_ST_CW_CLNT_HELLO_B: s->shutdown=0; ret=ssl3_client_hello(s); if (ret <= 0) goto end; s->state=SSL3_ST_CR_SRVR_HELLO_A; s->init_num=0; /* turn on buffering for the next lot of output */ if (s->bbio != s->wbio) s->wbio=BIO_push(s->bbio,s->wbio); break; case SSL3_ST_CR_SRVR_HELLO_A: case SSL3_ST_CR_SRVR_HELLO_B: ret=ssl3_get_server_hello(s); if (ret <= 0) goto end; if (s->hit) { s->state=SSL3_ST_CR_FINISHED_A; #ifndef OPENSSL_NO_TLSEXT if (s->tlsext_ticket_expected) { /* receive renewed session ticket */ s->state=SSL3_ST_CR_SESSION_TICKET_A; } #endif } else { s->state=SSL3_ST_CR_CERT_A; } s->init_num=0; break; case SSL3_ST_CR_CERT_A: case SSL3_ST_CR_CERT_B: /* Check if it is anon DH/ECDH, SRP auth */ /* or PSK */ if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP)) && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { ret=ssl3_get_server_certificate(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_TLSEXT if (s->tlsext_status_expected) s->state=SSL3_ST_CR_CERT_STATUS_A; else s->state=SSL3_ST_CR_KEY_EXCH_A; } else { skip = 1; s->state=SSL3_ST_CR_KEY_EXCH_A; } #else } else skip=1; s->state=SSL3_ST_CR_KEY_EXCH_A; #endif s->init_num=0; break; case SSL3_ST_CR_KEY_EXCH_A: case SSL3_ST_CR_KEY_EXCH_B: ret=ssl3_get_key_exchange(s); if (ret <= 0) goto end; s->state=SSL3_ST_CR_CERT_REQ_A; s->init_num=0; /* at this point we check that we have the * required stuff from the server */ if (!ssl3_check_cert_and_algorithm(s)) { ret= -1; goto end; } break; case SSL3_ST_CR_CERT_REQ_A: case SSL3_ST_CR_CERT_REQ_B: ret=ssl3_get_certificate_request(s); if (ret <= 0) goto end; s->state=SSL3_ST_CR_SRVR_DONE_A; s->init_num=0; break; case SSL3_ST_CR_SRVR_DONE_A: case SSL3_ST_CR_SRVR_DONE_B: ret=ssl3_get_server_done(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_SRP if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) { if ((ret = SRP_Calc_A_param(s))<=0) { SSLerr(SSL_F_SSL3_CONNECT,SSL_R_SRP_A_CALC); ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR); goto end; } } #endif if (s->s3->tmp.cert_req) s->state=SSL3_ST_CW_CERT_A; else s->state=SSL3_ST_CW_KEY_EXCH_A; s->init_num=0; break; case SSL3_ST_CW_CERT_A: case SSL3_ST_CW_CERT_B: case SSL3_ST_CW_CERT_C: case SSL3_ST_CW_CERT_D: ret=ssl3_send_client_certificate(s); if (ret <= 0) goto end; s->state=SSL3_ST_CW_KEY_EXCH_A; s->init_num=0; break; case SSL3_ST_CW_KEY_EXCH_A: case SSL3_ST_CW_KEY_EXCH_B: ret=ssl3_send_client_key_exchange(s); if (ret <= 0) goto end; /* EAY EAY EAY need to check for DH fix cert * sent back */ /* For TLS, cert_req is set to 2, so a cert chain * of nothing is sent, but no verify packet is sent */ /* XXX: For now, we do not support client * authentication in ECDH cipher suites with * ECDH (rather than ECDSA) certificates. * We need to skip the certificate verify * message when client's ECDH public key is sent * inside the client certificate. */ if (s->s3->tmp.cert_req == 1) { s->state=SSL3_ST_CW_CERT_VRFY_A; } else { s->state=SSL3_ST_CW_CHANGE_A; } if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) { s->state=SSL3_ST_CW_CHANGE_A; } s->init_num=0; break; case SSL3_ST_CW_CERT_VRFY_A: case SSL3_ST_CW_CERT_VRFY_B: ret=ssl3_send_client_verify(s); if (ret <= 0) goto end; s->state=SSL3_ST_CW_CHANGE_A; s->init_num=0; break; case SSL3_ST_CW_CHANGE_A: case SSL3_ST_CW_CHANGE_B: ret=ssl3_send_change_cipher_spec(s, SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B); if (ret <= 0) goto end; #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) s->state=SSL3_ST_CW_FINISHED_A; #else if (s->s3->next_proto_neg_seen) s->state=SSL3_ST_CW_NEXT_PROTO_A; else s->state=SSL3_ST_CW_FINISHED_A; #endif s->init_num=0; s->session->cipher=s->s3->tmp.new_cipher; #ifdef OPENSSL_NO_COMP s->session->compress_meth=0; #else if (s->s3->tmp.new_compression == NULL) s->session->compress_meth=0; else s->session->compress_meth= s->s3->tmp.new_compression->id; #endif if (!s->method->ssl3_enc->setup_key_block(s)) { ret= -1; goto end; } if (!s->method->ssl3_enc->change_cipher_state(s, SSL3_CHANGE_CIPHER_CLIENT_WRITE)) { ret= -1; goto end; } break; #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) case SSL3_ST_CW_NEXT_PROTO_A: case SSL3_ST_CW_NEXT_PROTO_B: ret=ssl3_send_next_proto(s); if (ret <= 0) goto end; s->state=SSL3_ST_CW_FINISHED_A; break; #endif case SSL3_ST_CW_FINISHED_A: case SSL3_ST_CW_FINISHED_B: ret=ssl3_send_finished(s, SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B, s->method->ssl3_enc->client_finished_label, s->method->ssl3_enc->client_finished_label_len); if (ret <= 0) goto end; s->state=SSL3_ST_CW_FLUSH; /* clear flags */ s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER; if (s->hit) { s->s3->tmp.next_state=SSL_ST_OK; if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED) { s->state=SSL_ST_OK; s->s3->flags|=SSL3_FLAGS_POP_BUFFER; s->s3->delay_buf_pop_ret=0; } } else { #ifndef OPENSSL_NO_TLSEXT /* Allow NewSessionTicket if ticket expected */ if (s->tlsext_ticket_expected) s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A; else #endif s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A; } s->init_num=0; break; #ifndef OPENSSL_NO_TLSEXT case SSL3_ST_CR_SESSION_TICKET_A: case SSL3_ST_CR_SESSION_TICKET_B: ret=ssl3_get_new_session_ticket(s); if (ret <= 0) goto end; s->state=SSL3_ST_CR_FINISHED_A; s->init_num=0; break; case SSL3_ST_CR_CERT_STATUS_A: case SSL3_ST_CR_CERT_STATUS_B: ret=ssl3_get_cert_status(s); if (ret <= 0) goto end; s->state=SSL3_ST_CR_KEY_EXCH_A; s->init_num=0; break; #endif case SSL3_ST_CR_FINISHED_A: case SSL3_ST_CR_FINISHED_B: s->s3->flags |= SSL3_FLAGS_CCS_OK; ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A, SSL3_ST_CR_FINISHED_B); if (ret <= 0) goto end; if (s->hit) s->state=SSL3_ST_CW_CHANGE_A; else s->state=SSL_ST_OK; s->init_num=0; break; case SSL3_ST_CW_FLUSH: s->rwstate=SSL_WRITING; if (BIO_flush(s->wbio) <= 0) { ret= -1; goto end; } s->rwstate=SSL_NOTHING; s->state=s->s3->tmp.next_state; break; case SSL_ST_OK: /* clean a few things up */ ssl3_cleanup_key_block(s); if (s->init_buf != NULL) { BUF_MEM_free(s->init_buf); s->init_buf=NULL; } /* If we are not 'joining' the last two packets, * remove the buffering now */ if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER)) ssl_free_wbio_buffer(s); /* else do it later in ssl3_write */ s->init_num=0; s->renegotiate=0; s->new_session=0; ssl_update_cache(s,SSL_SESS_CACHE_CLIENT); if (s->hit) s->ctx->stats.sess_hit++; ret=1; /* s->server=0; */ s->handshake_func=ssl3_connect; s->ctx->stats.sess_connect_good++; if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1); goto end; /* break; */ default: SSLerr(SSL_F_SSL3_CONNECT,SSL_R_UNKNOWN_STATE); ret= -1; goto end; /* break; */ } /* did we do anything */ if (!s->s3->tmp.reuse_message && !skip) { if (s->debug) { if ((ret=BIO_flush(s->wbio)) <= 0) goto end; } if ((cb != NULL) && (s->state != state)) { new_state=s->state; s->state=state; cb(s,SSL_CB_CONNECT_LOOP,1); s->state=new_state; } } skip=0; } end: s->in_handshake--; if (buf != NULL) BUF_MEM_free(buf); if (cb != NULL) cb(s,SSL_CB_CONNECT_EXIT,ret); return(ret); } int ssl3_client_hello(SSL *s) { unsigned char *buf; unsigned char *p,*d; int i; unsigned long l; int al = 0; #ifndef OPENSSL_NO_COMP int j; SSL_COMP *comp; #endif buf=(unsigned char *)s->init_buf->data; if (s->state == SSL3_ST_CW_CLNT_HELLO_A) { SSL_SESSION *sess = s->session; if ((sess == NULL) || (sess->ssl_version != s->version) || !sess->session_id_length || (sess->not_resumable)) { if (!ssl_get_new_session(s,0)) goto err; } if (s->method->version == DTLS_ANY_VERSION) { /* Determine which DTLS version to use */ int options = s->options; /* If DTLS 1.2 disabled correct the version number */ if (options & SSL_OP_NO_DTLSv1_2) { if (tls1_suiteb(s)) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE); goto err; } /* Disabling all versions is silly: return an * error. */ if (options & SSL_OP_NO_DTLSv1) { SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_WRONG_SSL_VERSION); goto err; } /* Update method so we don't use any DTLS 1.2 * features. */ s->method = DTLSv1_client_method(); s->version = DTLS1_VERSION; } else { /* We only support one version: update method */ if (options & SSL_OP_NO_DTLSv1) s->method = DTLSv1_2_client_method(); s->version = DTLS1_2_VERSION; } s->client_version = s->version; } /* else use the pre-loaded session */ p=s->s3->client_random; /* for DTLS if client_random is initialized, reuse it, we are * required to use same upon reply to HelloVerify */ if (SSL_IS_DTLS(s)) { size_t idx; i = 1; for (idx=0; idx < sizeof(s->s3->client_random); idx++) { if (p[idx]) { i = 0; break; } } } else i = 1; if (i) ssl_fill_hello_random(s, 0, p, sizeof(s->s3->client_random)); /* Do the message type and length last */ d=p= ssl_handshake_start(s); /*- * version indicates the negotiated version: for example from * an SSLv2/v3 compatible client hello). The client_version * field is the maximum version we permit and it is also * used in RSA encrypted premaster secrets. Some servers can * choke if we initially report a higher version then * renegotiate to a lower one in the premaster secret. This * didn't happen with TLS 1.0 as most servers supported it * but it can with TLS 1.1 or later if the server only supports * 1.0. * * Possible scenario with previous logic: * 1. Client hello indicates TLS 1.2 * 2. Server hello says TLS 1.0 * 3. RSA encrypted premaster secret uses 1.2. * 4. Handhaked proceeds using TLS 1.0. * 5. Server sends hello request to renegotiate. * 6. Client hello indicates TLS v1.0 as we now * know that is maximum server supports. * 7. Server chokes on RSA encrypted premaster secret * containing version 1.0. * * For interoperability it should be OK to always use the * maximum version we support in client hello and then rely * on the checking of version to ensure the servers isn't * being inconsistent: for example initially negotiating with * TLS 1.0 and renegotiating with TLS 1.2. We do this by using * client_version in client hello and not resetting it to * the negotiated version. */ #if 0 *(p++)=s->version>>8; *(p++)=s->version&0xff; s->client_version=s->version; #else *(p++)=s->client_version>>8; *(p++)=s->client_version&0xff; #endif /* Random stuff */ memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE); p+=SSL3_RANDOM_SIZE; /* Session ID */ if (s->new_session) i=0; else i=s->session->session_id_length; *(p++)=i; if (i != 0) { if (i > (int)sizeof(s->session->session_id)) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } memcpy(p,s->session->session_id,i); p+=i; } /* cookie stuff for DTLS */ if (SSL_IS_DTLS(s)) { if ( s->d1->cookie_len > sizeof(s->d1->cookie)) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } *(p++) = s->d1->cookie_len; memcpy(p, s->d1->cookie, s->d1->cookie_len); p += s->d1->cookie_len; } /* Ciphers supported */ i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0); if (i == 0) { SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE); goto err; } #ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH /* Some servers hang if client hello > 256 bytes * as hack workaround chop number of supported ciphers * to keep it well below this if we use TLS v1.2 */ if (TLS1_get_version(s) >= TLS1_2_VERSION && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH) i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1; #endif s2n(i,p); p+=i; /* COMPRESSION */ #ifdef OPENSSL_NO_COMP *(p++)=1; #else if (!ssl_allow_compression(s) || !s->ctx->comp_methods) j=0; else j=sk_SSL_COMP_num(s->ctx->comp_methods); *(p++)=1+j; for (i=0; i<j; i++) { comp=sk_SSL_COMP_value(s->ctx->comp_methods,i); *(p++)=comp->id; } #endif *(p++)=0; /* Add the NULL method */ #ifndef OPENSSL_NO_TLSEXT /* TLS extensions*/ if (ssl_prepare_clienthello_tlsext(s) <= 0) { SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT); goto err; } if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH, &al)) == NULL) { ssl3_send_alert(s,SSL3_AL_FATAL,al); SSLerr(SSL_F_SSL3_CLIENT_HELLO,ERR_R_INTERNAL_ERROR); goto err; } #endif l= p-d; ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l); s->state=SSL3_ST_CW_CLNT_HELLO_B; } /* SSL3_ST_CW_CLNT_HELLO_B */ return ssl_do_write(s); err: return(-1); } int ssl3_get_server_hello(SSL *s) { STACK_OF(SSL_CIPHER) *sk; const SSL_CIPHER *c; CERT *ct = s->cert; unsigned char *p,*d; int i,al=SSL_AD_INTERNAL_ERROR,ok; unsigned int j; long n; #ifndef OPENSSL_NO_COMP SSL_COMP *comp; #endif /* Hello verify request and/or server hello version may not * match so set first packet if we're negotiating version. */ if (SSL_IS_DTLS(s)) s->first_packet = 1; n=s->method->ssl_get_message(s, SSL3_ST_CR_SRVR_HELLO_A, SSL3_ST_CR_SRVR_HELLO_B, -1, 20000, /* ?? */ &ok); if (!ok) return((int)n); if (SSL_IS_DTLS(s)) { s->first_packet = 0; if ( s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST) { if ( s->d1->send_cookie == 0) { s->s3->tmp.reuse_message = 1; return 1; } else /* already sent a cookie */ { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } } } if ( s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } d=p=(unsigned char *)s->init_msg; if (s->method->version == DTLS_ANY_VERSION) { /* Work out correct protocol version to use */ int hversion = (p[0] << 8)|p[1]; int options = s->options; if (hversion == DTLS1_2_VERSION && !(options & SSL_OP_NO_DTLSv1_2)) s->method = DTLSv1_2_client_method(); else if (tls1_suiteb(s)) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE); s->version = hversion; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } else if (hversion == DTLS1_VERSION && !(options & SSL_OP_NO_DTLSv1)) s->method = DTLSv1_client_method(); else { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION); s->version = hversion; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } s->version = s->method->version; } if ((p[0] != (s->version>>8)) || (p[1] != (s->version&0xff))) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION); s->version=(s->version&0xff00)|p[1]; al=SSL_AD_PROTOCOL_VERSION; goto f_err; } p+=2; /* load the server hello data */ /* load the server random */ memcpy(s->s3->server_random,p,SSL3_RANDOM_SIZE); p+=SSL3_RANDOM_SIZE; s->hit = 0; /* get the session-id */ j= *(p++); if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SSL3_SESSION_ID_TOO_LONG); goto f_err; } #ifndef OPENSSL_NO_TLSEXT /* check if we want to resume the session based on external pre-shared secret */ if (s->version >= TLS1_VERSION && s->tls_session_secret_cb) { SSL_CIPHER *pref_cipher=NULL; s->session->master_key_length=sizeof(s->session->master_key); if (s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length, NULL, &pref_cipher, s->tls_session_secret_cb_arg)) { s->session->cipher = pref_cipher ? pref_cipher : ssl_get_cipher_by_char(s, p+j); s->hit = 1; } } #endif /* OPENSSL_NO_TLSEXT */ if (!s->hit && j != 0 && j == s->session->session_id_length && memcmp(p,s->session->session_id,j) == 0) { if(s->sid_ctx_length != s->session->sid_ctx_length || memcmp(s->session->sid_ctx,s->sid_ctx,s->sid_ctx_length)) { /* actually a client application bug */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT); goto f_err; } s->hit=1; } /* a miss or crap from the other end */ if (!s->hit) { /* If we were trying for session-id reuse, make a new * SSL_SESSION so we don't stuff up other people */ if (s->session->session_id_length > 0) { if (!ssl_get_new_session(s,0)) { goto f_err; } } s->session->session_id_length=j; memcpy(s->session->session_id,p,j); /* j could be 0 */ } p+=j; c=ssl_get_cipher_by_char(s,p); if (c == NULL) { /* unknown cipher */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNKNOWN_CIPHER_RETURNED); goto f_err; } /* Set version disabled mask now we know version */ if (!SSL_USE_TLS1_2_CIPHERS(s)) ct->mask_ssl = SSL_TLSV1_2; else ct->mask_ssl = 0; /* If it is a disabled cipher we didn't send it in client hello, * so return an error. */ if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_CHECK)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED); goto f_err; } p+=ssl_put_cipher_by_char(s,NULL,NULL); sk=ssl_get_ciphers_by_id(s); i=sk_SSL_CIPHER_find(sk,c); if (i < 0) { /* we did not say we would use this cipher */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED); goto f_err; } /* Depending on the session caching (internal/external), the cipher and/or cipher_id values may not be set. Make sure that cipher_id is set and use it for comparison. */ if (s->session->cipher) s->session->cipher_id = s->session->cipher->id; if (s->hit && (s->session->cipher_id != c->id)) { /* Workaround is now obsolete */ #if 0 if (!(s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)) #endif { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED); goto f_err; } } s->s3->tmp.new_cipher=c; /* Don't digest cached records if no sigalgs: we may need them for * client authentication. */ if (!SSL_USE_SIGALGS(s) && !ssl3_digest_cached_records(s)) goto f_err; /* lets get the compression algorithm */ /* COMPRESSION */ #ifdef OPENSSL_NO_COMP if (*(p++) != 0) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM); goto f_err; } /* If compression is disabled we'd better not try to resume a session * using compression. */ if (s->session->compress_meth != 0) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } #else j= *(p++); if (s->hit && j != s->session->compress_meth) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED); goto f_err; } if (j == 0) comp=NULL; else if (!ssl_allow_compression(s)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_COMPRESSION_DISABLED); goto f_err; } else comp=ssl3_comp_find(s->ctx->comp_methods,j); if ((j != 0) && (comp == NULL)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM); goto f_err; } else { s->s3->tmp.new_compression=comp; } #endif #ifndef OPENSSL_NO_TLSEXT /* TLS extensions*/ if (!ssl_parse_serverhello_tlsext(s,&p,d,n)) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_PARSE_TLSEXT); goto err; } #endif if (p != (d+n)) { /* wrong packet length */ al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_PACKET_LENGTH); goto f_err; } return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(-1); } int ssl3_get_server_certificate(SSL *s) { int al,i,ok,ret= -1; unsigned long n,nc,llen,l; X509 *x=NULL; const unsigned char *q,*p; unsigned char *d; STACK_OF(X509) *sk=NULL; SESS_CERT *sc; EVP_PKEY *pkey=NULL; int need_cert = 1; /* VRS: 0=> will allow null cert if auth == KRB5 */ n=s->method->ssl_get_message(s, SSL3_ST_CR_CERT_A, SSL3_ST_CR_CERT_B, -1, s->max_cert_list, &ok); if (!ok) return((int)n); if ((s->s3->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) || ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) && (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE))) { s->s3->tmp.reuse_message=1; return(1); } if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } p=d=(unsigned char *)s->init_msg; if ((sk=sk_X509_new_null()) == NULL) { SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE); goto err; } n2l3(p,llen); if (llen+3 != n) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_LENGTH_MISMATCH); goto f_err; } for (nc=0; nc<llen; ) { n2l3(p,l); if ((l+nc+3) > llen) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH); goto f_err; } q=p; x=d2i_X509(NULL,&q,l); if (x == NULL) { al=SSL_AD_BAD_CERTIFICATE; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_ASN1_LIB); goto f_err; } if (q != (p+l)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH); goto f_err; } if (!sk_X509_push(sk,x)) { SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE); goto err; } x=NULL; nc+=l+3; p=q; } i=ssl_verify_cert_chain(s,sk); if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0) #ifndef OPENSSL_NO_KRB5 && !((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) && (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5)) #endif /* OPENSSL_NO_KRB5 */ ) { al=ssl_verify_alarm_type(s->verify_result); SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED); goto f_err; } ERR_clear_error(); /* but we keep s->verify_result */ if (i > 1) { SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, i); al = SSL_AD_HANDSHAKE_FAILURE; goto f_err; } sc=ssl_sess_cert_new(); if (sc == NULL) goto err; if (s->session->sess_cert) ssl_sess_cert_free(s->session->sess_cert); s->session->sess_cert=sc; sc->cert_chain=sk; /* Inconsistency alert: cert_chain does include the peer's * certificate, which we don't include in s3_srvr.c */ x=sk_X509_value(sk,0); sk=NULL; /* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/ pkey=X509_get_pubkey(x); /* VRS: allow null cert if auth == KRB5 */ need_cert = ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) && (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5)) ? 0 : 1; #ifdef KSSL_DEBUG fprintf(stderr,"pkey,x = %p, %p\n", pkey,x); fprintf(stderr,"ssl_cert_type(x,pkey) = %d\n", ssl_cert_type(x,pkey)); fprintf(stderr,"cipher, alg, nc = %s, %lx, %lx, %d\n", s->s3->tmp.new_cipher->name, s->s3->tmp.new_cipher->algorithm_mkey, s->s3->tmp.new_cipher->algorithm_auth, need_cert); #endif /* KSSL_DEBUG */ if (need_cert && ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey))) { x=NULL; al=SSL3_AL_FATAL; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS); goto f_err; } i=ssl_cert_type(x,pkey); if (need_cert && i < 0) { x=NULL; al=SSL3_AL_FATAL; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_UNKNOWN_CERTIFICATE_TYPE); goto f_err; } if (need_cert) { int exp_idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher); if (exp_idx >= 0 && i != exp_idx) { x=NULL; al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_WRONG_CERTIFICATE_TYPE); goto f_err; } sc->peer_cert_type=i; CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509); /* Why would the following ever happen? * We just created sc a couple of lines ago. */ if (sc->peer_pkeys[i].x509 != NULL) X509_free(sc->peer_pkeys[i].x509); sc->peer_pkeys[i].x509=x; sc->peer_key= &(sc->peer_pkeys[i]); if (s->session->peer != NULL) X509_free(s->session->peer); CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509); s->session->peer=x; } else { sc->peer_cert_type=i; sc->peer_key= NULL; if (s->session->peer != NULL) X509_free(s->session->peer); s->session->peer=NULL; } s->session->verify_result = s->verify_result; x=NULL; ret=1; if (0) { f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); } err: EVP_PKEY_free(pkey); X509_free(x); sk_X509_pop_free(sk,X509_free); return(ret); } int ssl3_get_key_exchange(SSL *s) { #ifndef OPENSSL_NO_RSA unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2]; #endif EVP_MD_CTX md_ctx; unsigned char *param,*p; int al,j,ok; long i,param_len,n,alg_k,alg_a; EVP_PKEY *pkey=NULL; const EVP_MD *md = NULL; #ifndef OPENSSL_NO_RSA RSA *rsa=NULL; #endif #ifndef OPENSSL_NO_DH DH *dh=NULL; #endif #ifndef OPENSSL_NO_ECDH EC_KEY *ecdh = NULL; BN_CTX *bn_ctx = NULL; EC_POINT *srvr_ecpoint = NULL; int curve_nid = 0; int encoded_pt_len = 0; #endif EVP_MD_CTX_init(&md_ctx); /* use same message size as in ssl3_get_certificate_request() * as ServerKeyExchange message may be skipped */ n=s->method->ssl_get_message(s, SSL3_ST_CR_KEY_EXCH_A, SSL3_ST_CR_KEY_EXCH_B, -1, s->max_cert_list, &ok); if (!ok) return((int)n); alg_k=s->s3->tmp.new_cipher->algorithm_mkey; if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) { /* * Can't skip server key exchange if this is an ephemeral * ciphersuite. */ if (alg_k & (SSL_kDHE|SSL_kECDHE)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE); al = SSL_AD_UNEXPECTED_MESSAGE; goto f_err; } #ifndef OPENSSL_NO_PSK /* In plain PSK ciphersuite, ServerKeyExchange can be omitted if no identity hint is sent. Set session->sess_cert anyway to avoid problems later.*/ if (alg_k & SSL_kPSK) { s->session->sess_cert=ssl_sess_cert_new(); if (s->ctx->psk_identity_hint) OPENSSL_free(s->ctx->psk_identity_hint); s->ctx->psk_identity_hint = NULL; } #endif s->s3->tmp.reuse_message=1; return(1); } param=p=(unsigned char *)s->init_msg; if (s->session->sess_cert != NULL) { #ifndef OPENSSL_NO_RSA if (s->session->sess_cert->peer_rsa_tmp != NULL) { RSA_free(s->session->sess_cert->peer_rsa_tmp); s->session->sess_cert->peer_rsa_tmp=NULL; } #endif #ifndef OPENSSL_NO_DH if (s->session->sess_cert->peer_dh_tmp) { DH_free(s->session->sess_cert->peer_dh_tmp); s->session->sess_cert->peer_dh_tmp=NULL; } #endif #ifndef OPENSSL_NO_ECDH if (s->session->sess_cert->peer_ecdh_tmp) { EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp); s->session->sess_cert->peer_ecdh_tmp=NULL; } #endif } else { s->session->sess_cert=ssl_sess_cert_new(); } /* Total length of the parameters including the length prefix */ param_len=0; alg_a=s->s3->tmp.new_cipher->algorithm_auth; al=SSL_AD_DECODE_ERROR; #ifndef OPENSSL_NO_PSK if (alg_k & SSL_kPSK) { char tmp_id_hint[PSK_MAX_IDENTITY_LEN+1]; param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); /* Store PSK identity hint for later use, hint is used * in ssl3_send_client_key_exchange. Assume that the * maximum length of a PSK identity hint can be as * long as the maximum length of a PSK identity. */ if (i > PSK_MAX_IDENTITY_LEN) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH); goto f_err; } param_len += i; /* If received PSK identity hint contains NULL * characters, the hint is truncated from the first * NULL. p may not be ending with NULL, so create a * NULL-terminated string. */ memcpy(tmp_id_hint, p, i); memset(tmp_id_hint+i, 0, PSK_MAX_IDENTITY_LEN+1-i); if (s->ctx->psk_identity_hint != NULL) OPENSSL_free(s->ctx->psk_identity_hint); s->ctx->psk_identity_hint = BUF_strdup(tmp_id_hint); if (s->ctx->psk_identity_hint == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto f_err; } p+=i; n-=param_len; } else #endif /* !OPENSSL_NO_PSK */ #ifndef OPENSSL_NO_SRP if (alg_k & SSL_kSRP) { param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_N_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.N=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_G_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.g=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (1 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 1; i = (unsigned int)(p[0]); p++; if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_S_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.s=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_B_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.B=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; if (!srp_verify_server_param(s, &al)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS); goto f_err; } /* We must check if there is a certificate */ #ifndef OPENSSL_NO_RSA if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #else if (0) ; #endif #ifndef OPENSSL_NO_DSA else if (alg_a & SSL_aDSS) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509); #endif } else #endif /* !OPENSSL_NO_SRP */ #ifndef OPENSSL_NO_RSA if (alg_k & SSL_kRSA) { if ((rsa=RSA_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH); goto f_err; } param_len += i; if (!(rsa->n=BN_bin2bn(p,i,rsa->n))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH); goto f_err; } param_len += i; if (!(rsa->e=BN_bin2bn(p,i,rsa->e))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; /* this should be because we are using an export cipher */ if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); else { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } s->session->sess_cert->peer_rsa_tmp=rsa; rsa=NULL; } #else /* OPENSSL_NO_RSA */ if (0) ; #endif #ifndef OPENSSL_NO_DH else if (alg_k & SSL_kDHE) { if ((dh=DH_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB); goto err; } param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH); goto f_err; } param_len += i; if (!(dh->p=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH); goto f_err; } param_len += i; if (!(dh->g=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH); goto f_err; } param_len += i; if (!(dh->pub_key=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; if (!ssl_security(s, SSL_SECOP_TMP_DH, DH_security_bits(dh), 0, dh)) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_DH_KEY_TOO_SMALL); goto f_err; } #ifndef OPENSSL_NO_RSA if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #else if (0) ; #endif #ifndef OPENSSL_NO_DSA else if (alg_a & SSL_aDSS) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509); #endif /* else anonymous DH, so no certificate or pkey. */ s->session->sess_cert->peer_dh_tmp=dh; dh=NULL; } else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER); goto f_err; } #endif /* !OPENSSL_NO_DH */ #ifndef OPENSSL_NO_ECDH else if (alg_k & SSL_kECDHE) { EC_GROUP *ngroup; const EC_GROUP *group; if ((ecdh=EC_KEY_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } /* Extract elliptic curve parameters and the * server's ephemeral ECDH public key. * Keep accumulating lengths of various components in * param_len and make sure it never exceeds n. */ /* XXX: For now we only support named (not generic) curves * and the ECParameters in this case is just three bytes. We * also need one byte for the length of the encoded point */ param_len=4; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } /* Check curve is one of our preferences, if not server has * sent an invalid curve. ECParameters is 3 bytes. */ if (!tls1_check_curve(s, p, 3)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_CURVE); goto f_err; } if ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0) { al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS); goto f_err; } ngroup = EC_GROUP_new_by_curve_name(curve_nid); if (ngroup == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } if (EC_KEY_set_group(ecdh, ngroup) == 0) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } EC_GROUP_free(ngroup); group = EC_KEY_get0_group(ecdh); if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && (EC_GROUP_get_degree(group) > 163)) { al=SSL_AD_EXPORT_RESTRICTION; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER); goto f_err; } p+=3; /* Next, get the encoded ECPoint */ if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) || ((bn_ctx = BN_CTX_new()) == NULL)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } encoded_pt_len = *p; /* length of encoded point */ p+=1; if ((encoded_pt_len > n - param_len) || (EC_POINT_oct2point(group, srvr_ecpoint, p, encoded_pt_len, bn_ctx) == 0)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT); goto f_err; } param_len += encoded_pt_len; n-=param_len; p+=encoded_pt_len; /* The ECC/TLS specification does not mention * the use of DSA to sign ECParameters in the server * key exchange message. We do support RSA and ECDSA. */ if (0) ; #ifndef OPENSSL_NO_RSA else if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #endif #ifndef OPENSSL_NO_ECDSA else if (alg_a & SSL_aECDSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509); #endif /* else anonymous ECDH, so no certificate or pkey. */ EC_KEY_set_public_key(ecdh, srvr_ecpoint); s->session->sess_cert->peer_ecdh_tmp=ecdh; ecdh=NULL; BN_CTX_free(bn_ctx); bn_ctx = NULL; EC_POINT_free(srvr_ecpoint); srvr_ecpoint = NULL; } else if (alg_k) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE); goto f_err; } #endif /* !OPENSSL_NO_ECDH */ /* p points to the next byte, there are 'n' bytes left */ /* if it was signed, check the signature */ if (pkey != NULL) { if (SSL_USE_SIGALGS(s)) { int rv; if (2 > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } rv = tls12_check_peer_sigalg(&md, s, p, pkey); if (rv == -1) goto err; else if (rv == 0) { goto f_err; } #ifdef SSL_DEBUG fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md)); #endif p += 2; n -= 2; } else md = EVP_sha1(); if (2 > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); n-=2; j=EVP_PKEY_size(pkey); /* Check signature length. If n is 0 then signature is empty */ if ((i != n) || (n > j) || (n <= 0)) { /* wrong packet length */ SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH); goto f_err; } #ifndef OPENSSL_NO_RSA if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) { int num; unsigned int size; j=0; q=md_buf; for (num=2; num > 0; num--) { EVP_MD_CTX_set_flags(&md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); EVP_DigestInit_ex(&md_ctx,(num == 2) ?s->ctx->md5:s->ctx->sha1, NULL); EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,param,param_len); EVP_DigestFinal_ex(&md_ctx,q,&size); q+=size; j+=size; } i=RSA_verify(NID_md5_sha1, md_buf, j, p, n, pkey->pkey.rsa); if (i < 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT); goto f_err; } if (i == 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); goto f_err; } } else #endif { EVP_VerifyInit_ex(&md_ctx, md, NULL); EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_VerifyUpdate(&md_ctx,param,param_len); if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); goto f_err; } } } else { /* aNULL, aSRP or kPSK do not need public keys */ if (!(alg_a & (SSL_aNULL|SSL_aSRP)) && !(alg_k & SSL_kPSK)) { /* Might be wrong key type, check it */ if (ssl3_check_cert_and_algorithm(s)) /* Otherwise this shouldn't happen */ SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } /* still data left over */ if (n != 0) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE); goto f_err; } } EVP_PKEY_free(pkey); EVP_MD_CTX_cleanup(&md_ctx); return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: EVP_PKEY_free(pkey); #ifndef OPENSSL_NO_RSA if (rsa != NULL) RSA_free(rsa); #endif #ifndef OPENSSL_NO_DH if (dh != NULL) DH_free(dh); #endif #ifndef OPENSSL_NO_ECDH BN_CTX_free(bn_ctx); EC_POINT_free(srvr_ecpoint); if (ecdh != NULL) EC_KEY_free(ecdh); #endif EVP_MD_CTX_cleanup(&md_ctx); return(-1); } int ssl3_get_certificate_request(SSL *s) { int ok,ret=0; unsigned long n,nc,l; unsigned int llen, ctype_num,i; X509_NAME *xn=NULL; const unsigned char *p,*q; unsigned char *d; STACK_OF(X509_NAME) *ca_sk=NULL; n=s->method->ssl_get_message(s, SSL3_ST_CR_CERT_REQ_A, SSL3_ST_CR_CERT_REQ_B, -1, s->max_cert_list, &ok); if (!ok) return((int)n); s->s3->tmp.cert_req=0; if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE) { s->s3->tmp.reuse_message=1; /* If we get here we don't need any cached handshake records * as we wont be doing client auth. */ if (s->s3->handshake_buffer) { if (!ssl3_digest_cached_records(s)) goto err; } return(1); } if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_WRONG_MESSAGE_TYPE); goto err; } /* TLS does not like anon-DH with client cert */ if (s->version > SSL3_VERSION) { if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER); goto err; } } p=d=(unsigned char *)s->init_msg; if ((ca_sk=sk_X509_NAME_new(ca_dn_cmp)) == NULL) { SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE); goto err; } /* get the certificate types */ ctype_num= *(p++); if (s->cert->ctypes) { OPENSSL_free(s->cert->ctypes); s->cert->ctypes = NULL; } if (ctype_num > SSL3_CT_NUMBER) { /* If we exceed static buffer copy all to cert structure */ s->cert->ctypes = OPENSSL_malloc(ctype_num); if (s->cert->ctypes == NULL) { SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE); goto err; } memcpy(s->cert->ctypes, p, ctype_num); s->cert->ctype_num = (size_t)ctype_num; ctype_num=SSL3_CT_NUMBER; } for (i=0; i<ctype_num; i++) s->s3->tmp.ctype[i]= p[i]; p+=p[-1]; if (SSL_USE_SIGALGS(s)) { n2s(p, llen); /* Check we have enough room for signature algorithms and * following length value. */ if ((unsigned long)(p - d + llen + 2) > n) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_DATA_LENGTH_TOO_LONG); goto err; } /* Clear certificate digests and validity flags */ for (i = 0; i < SSL_PKEY_NUM; i++) { s->cert->pkeys[i].digest = NULL; s->cert->pkeys[i].valid_flags = 0; } if ((llen & 1) || !tls1_save_sigalgs(s, p, llen)) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_SIGNATURE_ALGORITHMS_ERROR); goto err; } if (!tls1_process_sigalgs(s)) { ssl3_send_alert(s,SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE); goto err; } p += llen; } /* get the CA RDNs */ n2s(p,llen); #if 0 { FILE *out; out=fopen("/tmp/vsign.der","w"); fwrite(p,1,llen,out); fclose(out); } #endif if ((unsigned long)(p - d + llen) != n) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_LENGTH_MISMATCH); goto err; } for (nc=0; nc<llen; ) { n2s(p,l); if ((l+nc+2) > llen) { if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG)) goto cont; /* netscape bugs */ ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_TOO_LONG); goto err; } q=p; if ((xn=d2i_X509_NAME(NULL,&q,l)) == NULL) { /* If netscape tolerance is on, ignore errors */ if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG) goto cont; else { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_ASN1_LIB); goto err; } } if (q != (p+l)) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_LENGTH_MISMATCH); goto err; } if (!sk_X509_NAME_push(ca_sk,xn)) { SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE); goto err; } p+=l; nc+=l+2; } if (0) { cont: ERR_clear_error(); } /* we should setup a certificate to return.... */ s->s3->tmp.cert_req=1; s->s3->tmp.ctype_num=ctype_num; if (s->s3->tmp.ca_names != NULL) sk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free); s->s3->tmp.ca_names=ca_sk; ca_sk=NULL; ret=1; err: if (ca_sk != NULL) sk_X509_NAME_pop_free(ca_sk,X509_NAME_free); return(ret); } static int ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b) { return(X509_NAME_cmp(*a,*b)); } #ifndef OPENSSL_NO_TLSEXT int ssl3_get_new_session_ticket(SSL *s) { int ok,al,ret=0, ticklen; long n; const unsigned char *p; unsigned char *d; n=s->method->ssl_get_message(s, SSL3_ST_CR_SESSION_TICKET_A, SSL3_ST_CR_SESSION_TICKET_B, SSL3_MT_NEWSESSION_TICKET, 16384, &ok); if (!ok) return((int)n); if (n < 6) { /* need at least ticket_lifetime_hint + ticket length */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH); goto f_err; } p=d=(unsigned char *)s->init_msg; n2l(p, s->session->tlsext_tick_lifetime_hint); n2s(p, ticklen); /* ticket_lifetime_hint + ticket_length + ticket */ if (ticklen + 6 != n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH); goto f_err; } if (s->session->tlsext_tick) { OPENSSL_free(s->session->tlsext_tick); s->session->tlsext_ticklen = 0; } s->session->tlsext_tick = OPENSSL_malloc(ticklen); if (!s->session->tlsext_tick) { SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,ERR_R_MALLOC_FAILURE); goto err; } memcpy(s->session->tlsext_tick, p, ticklen); s->session->tlsext_ticklen = ticklen; /* There are two ways to detect a resumed ticket session. * One is to set an appropriate session ID and then the server * must return a match in ServerHello. This allows the normal * client session ID matching to work and we know much * earlier that the ticket has been accepted. * * The other way is to set zero length session ID when the * ticket is presented and rely on the handshake to determine * session resumption. * * We choose the former approach because this fits in with * assumptions elsewhere in OpenSSL. The session ID is set * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the * ticket. */ EVP_Digest(p, ticklen, s->session->session_id, &s->session->session_id_length, #ifndef OPENSSL_NO_SHA256 EVP_sha256(), NULL); #else EVP_sha1(), NULL); #endif ret=1; return(ret); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(-1); } int ssl3_get_cert_status(SSL *s) { int ok, al; unsigned long resplen,n; const unsigned char *p; n=s->method->ssl_get_message(s, SSL3_ST_CR_CERT_STATUS_A, SSL3_ST_CR_CERT_STATUS_B, SSL3_MT_CERTIFICATE_STATUS, 16384, &ok); if (!ok) return((int)n); if (n < 4) { /* need at least status type + length */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH); goto f_err; } p = (unsigned char *)s->init_msg; if (*p++ != TLSEXT_STATUSTYPE_ocsp) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_UNSUPPORTED_STATUS_TYPE); goto f_err; } n2l3(p, resplen); if (resplen + 4 != n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH); goto f_err; } if (s->tlsext_ocsp_resp) OPENSSL_free(s->tlsext_ocsp_resp); s->tlsext_ocsp_resp = BUF_memdup(p, resplen); if (!s->tlsext_ocsp_resp) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE); goto f_err; } s->tlsext_ocsp_resplen = resplen; if (s->ctx->tlsext_status_cb) { int ret; ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg); if (ret == 0) { al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE; SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_INVALID_STATUS_RESPONSE); goto f_err; } if (ret < 0) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE); goto f_err; } } return 1; f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); return(-1); } #endif int ssl3_get_server_done(SSL *s) { int ok,ret=0; long n; n=s->method->ssl_get_message(s, SSL3_ST_CR_SRVR_DONE_A, SSL3_ST_CR_SRVR_DONE_B, SSL3_MT_SERVER_DONE, 30, /* should be very small, like 0 :-) */ &ok); if (!ok) return((int)n); if (n > 0) { /* should contain no data */ ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_SERVER_DONE,SSL_R_LENGTH_MISMATCH); return -1; } ret=1; return(ret); } int ssl3_send_client_key_exchange(SSL *s) { unsigned char *p; int n; unsigned long alg_k; #ifndef OPENSSL_NO_RSA unsigned char *q; EVP_PKEY *pkey=NULL; #endif #ifndef OPENSSL_NO_KRB5 KSSL_ERR kssl_err; #endif /* OPENSSL_NO_KRB5 */ #ifndef OPENSSL_NO_ECDH EC_KEY *clnt_ecdh = NULL; const EC_POINT *srvr_ecpoint = NULL; EVP_PKEY *srvr_pub_pkey = NULL; unsigned char *encodedPoint = NULL; int encoded_pt_len = 0; BN_CTX * bn_ctx = NULL; #endif if (s->state == SSL3_ST_CW_KEY_EXCH_A) { p = ssl_handshake_start(s); alg_k=s->s3->tmp.new_cipher->algorithm_mkey; /* Fool emacs indentation */ if (0) {} #ifndef OPENSSL_NO_RSA else if (alg_k & SSL_kRSA) { RSA *rsa; unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH]; if (s->session->sess_cert == NULL) { /* We should always have a server certificate with SSL_kRSA. */ SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } if (s->session->sess_cert->peer_rsa_tmp != NULL) rsa=s->session->sess_cert->peer_rsa_tmp; else { pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } rsa=pkey->pkey.rsa; EVP_PKEY_free(pkey); } tmp_buf[0]=s->client_version>>8; tmp_buf[1]=s->client_version&0xff; if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0) goto err; s->session->master_key_length=sizeof tmp_buf; q=p; /* Fix buf for TLS and beyond */ if (s->version > SSL3_VERSION) p+=2; n=RSA_public_encrypt(sizeof tmp_buf, tmp_buf,p,rsa,RSA_PKCS1_PADDING); #ifdef PKCS1_CHECK if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++; if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70; #endif if (n <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT); goto err; } /* Fix buf for TLS and beyond */ if (s->version > SSL3_VERSION) { s2n(n,q); n+=2; } s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key, tmp_buf,sizeof tmp_buf); OPENSSL_cleanse(tmp_buf,sizeof tmp_buf); } #endif #ifndef OPENSSL_NO_KRB5 else if (alg_k & SSL_kKRB5) { krb5_error_code krb5rc; KSSL_CTX *kssl_ctx = s->kssl_ctx; /* krb5_data krb5_ap_req; */ krb5_data *enc_ticket; krb5_data authenticator, *authp = NULL; EVP_CIPHER_CTX ciph_ctx; const EVP_CIPHER *enc = NULL; unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH]; unsigned char epms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_IV_LENGTH]; int padl, outl = sizeof(epms); EVP_CIPHER_CTX_init(&ciph_ctx); #ifdef KSSL_DEBUG fprintf(stderr,"ssl3_send_client_key_exchange(%lx & %lx)\n", alg_k, SSL_kKRB5); #endif /* KSSL_DEBUG */ authp = NULL; #ifdef KRB5SENDAUTH if (KRB5SENDAUTH) authp = &authenticator; #endif /* KRB5SENDAUTH */ krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp, &kssl_err); enc = kssl_map_enc(kssl_ctx->enctype); if (enc == NULL) goto err; #ifdef KSSL_DEBUG { fprintf(stderr,"kssl_cget_tkt rtn %d\n", krb5rc); if (krb5rc && kssl_err.text) fprintf(stderr,"kssl_cget_tkt kssl_err=%s\n", kssl_err.text); } #endif /* KSSL_DEBUG */ if (krb5rc) { ssl3_send_alert(s,SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, kssl_err.reason); goto err; } /*- * 20010406 VRS - Earlier versions used KRB5 AP_REQ * in place of RFC 2712 KerberosWrapper, as in: * * Send ticket (copy to *p, set n = length) * n = krb5_ap_req.length; * memcpy(p, krb5_ap_req.data, krb5_ap_req.length); * if (krb5_ap_req.data) * kssl_krb5_free_data_contents(NULL,&krb5_ap_req); * * Now using real RFC 2712 KerberosWrapper * (Thanks to Simon Wilkinson <sxw@sxw.org.uk>) * Note: 2712 "opaque" types are here replaced * with a 2-byte length followed by the value. * Example: * KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms * Where "xx xx" = length bytes. Shown here with * optional authenticator omitted. */ /* KerberosWrapper.Ticket */ s2n(enc_ticket->length,p); memcpy(p, enc_ticket->data, enc_ticket->length); p+= enc_ticket->length; n = enc_ticket->length + 2; /* KerberosWrapper.Authenticator */ if (authp && authp->length) { s2n(authp->length,p); memcpy(p, authp->data, authp->length); p+= authp->length; n+= authp->length + 2; free(authp->data); authp->data = NULL; authp->length = 0; } else { s2n(0,p);/* null authenticator length */ n+=2; } tmp_buf[0]=s->client_version>>8; tmp_buf[1]=s->client_version&0xff; if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0) goto err; /*- * 20010420 VRS. Tried it this way; failed. * EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL); * EVP_CIPHER_CTX_set_key_length(&ciph_ctx, * kssl_ctx->length); * EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv); */ memset(iv, 0, sizeof iv); /* per RFC 1510 */ EVP_EncryptInit_ex(&ciph_ctx,enc, NULL, kssl_ctx->key,iv); EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf, sizeof tmp_buf); EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl); outl += padl; if (outl > (int)sizeof epms) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } EVP_CIPHER_CTX_cleanup(&ciph_ctx); /* KerberosWrapper.EncryptedPreMasterSecret */ s2n(outl,p); memcpy(p, epms, outl); p+=outl; n+=outl + 2; s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key, tmp_buf, sizeof tmp_buf); OPENSSL_cleanse(tmp_buf, sizeof tmp_buf); OPENSSL_cleanse(epms, outl); } #endif #ifndef OPENSSL_NO_DH else if (alg_k & (SSL_kDHE|SSL_kDHr|SSL_kDHd)) { DH *dh_srvr,*dh_clnt; SESS_CERT *scert = s->session->sess_cert; if (scert == NULL) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE); goto err; } if (scert->peer_dh_tmp != NULL) dh_srvr=scert->peer_dh_tmp; else { /* we get them from the cert */ int idx = scert->peer_cert_type; EVP_PKEY *spkey = NULL; dh_srvr = NULL; if (idx >= 0) spkey = X509_get_pubkey( scert->peer_pkeys[idx].x509); if (spkey) { dh_srvr = EVP_PKEY_get1_DH(spkey); EVP_PKEY_free(spkey); } if (dh_srvr == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } } if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) { /* Use client certificate key */ EVP_PKEY *clkey = s->cert->key->privatekey; dh_clnt = NULL; if (clkey) dh_clnt = EVP_PKEY_get1_DH(clkey); if (dh_clnt == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } } else { /* generate a new random key */ if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); goto err; } if (!DH_generate_key(dh_clnt)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); DH_free(dh_clnt); goto err; } } /* use the 'p' output buffer for the DH key, but * make sure to clear it out afterwards */ n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt); if (scert->peer_dh_tmp == NULL) DH_free(dh_srvr); if (n <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); DH_free(dh_clnt); goto err; } /* generate master key from the result */ s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key,p,n); /* clean up */ memset(p,0,n); if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) n = 0; else { /* send off the data */ n=BN_num_bytes(dh_clnt->pub_key); s2n(n,p); BN_bn2bin(dh_clnt->pub_key,p); n+=2; } DH_free(dh_clnt); /* perhaps clean things up a bit EAY EAY EAY EAY*/ } #endif #ifndef OPENSSL_NO_ECDH else if (alg_k & (SSL_kECDHE|SSL_kECDHr|SSL_kECDHe)) { const EC_GROUP *srvr_group = NULL; EC_KEY *tkey; int ecdh_clnt_cert = 0; int field_size = 0; if (s->session->sess_cert == NULL) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE); goto err; } /* Did we send out the client's * ECDH share for use in premaster * computation as part of client certificate? * If so, set ecdh_clnt_cert to 1. */ if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL)) { /*- * XXX: For now, we do not support client * authentication using ECDH certificates. * To add such support, one needs to add * code that checks for appropriate * conditions and sets ecdh_clnt_cert to 1. * For example, the cert have an ECC * key on the same curve as the server's * and the key should be authorized for * key agreement. * * One also needs to add code in ssl3_connect * to skip sending the certificate verify * message. * * if ((s->cert->key->privatekey != NULL) && * (s->cert->key->privatekey->type == * EVP_PKEY_EC) && ...) * ecdh_clnt_cert = 1; */ } if (s->session->sess_cert->peer_ecdh_tmp != NULL) { tkey = s->session->sess_cert->peer_ecdh_tmp; } else { /* Get the Server Public Key from Cert */ srvr_pub_pkey = X509_get_pubkey(s->session-> \ sess_cert->peer_pkeys[SSL_PKEY_ECC].x509); if ((srvr_pub_pkey == NULL) || (srvr_pub_pkey->type != EVP_PKEY_EC) || (srvr_pub_pkey->pkey.ec == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } tkey = srvr_pub_pkey->pkey.ec; } srvr_group = EC_KEY_get0_group(tkey); srvr_ecpoint = EC_KEY_get0_public_key(tkey); if ((srvr_group == NULL) || (srvr_ecpoint == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } if ((clnt_ecdh=EC_KEY_new()) == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } if (!EC_KEY_set_group(clnt_ecdh, srvr_group)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } if (ecdh_clnt_cert) { /* Reuse key info from our certificate * We only need our private key to perform * the ECDH computation. */ const BIGNUM *priv_key; tkey = s->cert->key->privatekey->pkey.ec; priv_key = EC_KEY_get0_private_key(tkey); if (priv_key == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } if (!EC_KEY_set_private_key(clnt_ecdh, priv_key)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } } else { /* Generate a new ECDH key pair */ if (!(EC_KEY_generate_key(clnt_ecdh))) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } } /* use the 'p' output buffer for the ECDH key, but * make sure to clear it out afterwards */ field_size = EC_GROUP_get_degree(srvr_group); if (field_size <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL); if (n <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } /* generate master key from the result */ s->session->master_key_length = s->method->ssl3_enc \ -> generate_master_secret(s, s->session->master_key, p, n); memset(p, 0, n); /* clean up */ if (ecdh_clnt_cert) { /* Send empty client key exch message */ n = 0; } else { /* First check the size of encoding and * allocate memory accordingly. */ encoded_pt_len = EC_POINT_point2oct(srvr_group, EC_KEY_get0_public_key(clnt_ecdh), POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL); encodedPoint = (unsigned char *) OPENSSL_malloc(encoded_pt_len * sizeof(unsigned char)); bn_ctx = BN_CTX_new(); if ((encodedPoint == NULL) || (bn_ctx == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } /* Encode the public key */ n = EC_POINT_point2oct(srvr_group, EC_KEY_get0_public_key(clnt_ecdh), POINT_CONVERSION_UNCOMPRESSED, encodedPoint, encoded_pt_len, bn_ctx); *p = n; /* length of encoded point */ /* Encoded point will be copied here */ p += 1; /* copy the point */ memcpy((unsigned char *)p, encodedPoint, n); /* increment n to account for length field */ n += 1; } /* Free allocated memory */ BN_CTX_free(bn_ctx); if (encodedPoint != NULL) OPENSSL_free(encodedPoint); if (clnt_ecdh != NULL) EC_KEY_free(clnt_ecdh); EVP_PKEY_free(srvr_pub_pkey); } #endif /* !OPENSSL_NO_ECDH */ else if (alg_k & SSL_kGOST) { /* GOST key exchange message creation */ EVP_PKEY_CTX *pkey_ctx; X509 *peer_cert; size_t msglen; unsigned int md_len; int keytype; unsigned char premaster_secret[32],shared_ukm[32], tmp[256]; EVP_MD_CTX *ukm_hash; EVP_PKEY *pub_key; /* Get server sertificate PKEY and create ctx from it */ peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST01)].x509; if (!peer_cert) peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST94)].x509; if (!peer_cert) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER); goto err; } pkey_ctx=EVP_PKEY_CTX_new(pub_key=X509_get_pubkey(peer_cert),NULL); /* If we have send a certificate, and certificate key * parameters match those of server certificate, use * certificate key for key exchange */ /* Otherwise, generate ephemeral key pair */ EVP_PKEY_encrypt_init(pkey_ctx); /* Generate session key */ RAND_bytes(premaster_secret,32); /* If we have client certificate, use its secret as peer key */ if (s->s3->tmp.cert_req && s->cert->key->privatekey) { if (EVP_PKEY_derive_set_peer(pkey_ctx,s->cert->key->privatekey) <=0) { /* If there was an error - just ignore it. Ephemeral key * would be used */ ERR_clear_error(); } } /* Compute shared IV and store it in algorithm-specific * context data */ ukm_hash = EVP_MD_CTX_create(); EVP_DigestInit(ukm_hash,EVP_get_digestbynid(NID_id_GostR3411_94)); EVP_DigestUpdate(ukm_hash,s->s3->client_random,SSL3_RANDOM_SIZE); EVP_DigestUpdate(ukm_hash,s->s3->server_random,SSL3_RANDOM_SIZE); EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len); EVP_MD_CTX_destroy(ukm_hash); if (EVP_PKEY_CTX_ctrl(pkey_ctx,-1,EVP_PKEY_OP_ENCRYPT,EVP_PKEY_CTRL_SET_IV, 8,shared_ukm)<0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_LIBRARY_BUG); goto err; } /* Make GOST keytransport blob message */ /*Encapsulate it into sequence */ *(p++)=V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED; msglen=255; if (EVP_PKEY_encrypt(pkey_ctx,tmp,&msglen,premaster_secret,32)<0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_LIBRARY_BUG); goto err; } if (msglen >= 0x80) { *(p++)=0x81; *(p++)= msglen & 0xff; n=msglen+3; } else { *(p++)= msglen & 0xff; n=msglen+2; } memcpy(p, tmp, msglen); /* Check if pubkey from client certificate was used */ if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) { /* Set flag "skip certificate verify" */ s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY; } EVP_PKEY_CTX_free(pkey_ctx); s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key,premaster_secret,32); EVP_PKEY_free(pub_key); } #ifndef OPENSSL_NO_SRP else if (alg_k & SSL_kSRP) { if (s->srp_ctx.A != NULL) { /* send off the data */ n=BN_num_bytes(s->srp_ctx.A); s2n(n,p); BN_bn2bin(s->srp_ctx.A,p); n+=2; } else { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } if (s->session->srp_username != NULL) OPENSSL_free(s->session->srp_username); s->session->srp_username = BUF_strdup(s->srp_ctx.login); if (s->session->srp_username == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } if ((s->session->master_key_length = SRP_generate_client_master_secret(s,s->session->master_key))<0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } } #endif #ifndef OPENSSL_NO_PSK else if (alg_k & SSL_kPSK) { /* The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes * to return a \0-terminated identity. The last byte * is for us for simulating strnlen. */ char identity[PSK_MAX_IDENTITY_LEN + 2]; size_t identity_len; unsigned char *t = NULL; unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4]; unsigned int pre_ms_len = 0, psk_len = 0; int psk_err = 1; n = 0; if (s->psk_client_callback == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_PSK_NO_CLIENT_CB); goto err; } memset(identity, 0, sizeof(identity)); psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint, identity, sizeof(identity) - 1, psk_or_pre_ms, sizeof(psk_or_pre_ms)); if (psk_len > PSK_MAX_PSK_LEN) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto psk_err; } else if (psk_len == 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_PSK_IDENTITY_NOT_FOUND); goto psk_err; } identity[PSK_MAX_IDENTITY_LEN + 1] = '\0'; identity_len = strlen(identity); if (identity_len > PSK_MAX_IDENTITY_LEN) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto psk_err; } /* create PSK pre_master_secret */ pre_ms_len = 2+psk_len+2+psk_len; t = psk_or_pre_ms; memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len); s2n(psk_len, t); memset(t, 0, psk_len); t+=psk_len; s2n(psk_len, t); if (s->session->psk_identity_hint != NULL) OPENSSL_free(s->session->psk_identity_hint); s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint); if (s->ctx->psk_identity_hint != NULL && s->session->psk_identity_hint == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto psk_err; } if (s->session->psk_identity != NULL) OPENSSL_free(s->session->psk_identity); s->session->psk_identity = BUF_strdup(identity); if (s->session->psk_identity == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto psk_err; } s->session->master_key_length = s->method->ssl3_enc->generate_master_secret(s, s->session->master_key, psk_or_pre_ms, pre_ms_len); s2n(identity_len, p); memcpy(p, identity, identity_len); n = 2 + identity_len; psk_err = 0; psk_err: OPENSSL_cleanse(identity, sizeof(identity)); OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms)); if (psk_err != 0) { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); goto err; } } #endif else { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n); s->state=SSL3_ST_CW_KEY_EXCH_B; } /* SSL3_ST_CW_KEY_EXCH_B */ return ssl_do_write(s); err: #ifndef OPENSSL_NO_ECDH BN_CTX_free(bn_ctx); if (encodedPoint != NULL) OPENSSL_free(encodedPoint); if (clnt_ecdh != NULL) EC_KEY_free(clnt_ecdh); EVP_PKEY_free(srvr_pub_pkey); #endif return(-1); } int ssl3_send_client_verify(SSL *s) { unsigned char *p; unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH]; EVP_PKEY *pkey; EVP_PKEY_CTX *pctx=NULL; EVP_MD_CTX mctx; unsigned u=0; unsigned long n; int j; EVP_MD_CTX_init(&mctx); if (s->state == SSL3_ST_CW_CERT_VRFY_A) { p= ssl_handshake_start(s); pkey=s->cert->key->privatekey; /* Create context from key and test if sha1 is allowed as digest */ pctx = EVP_PKEY_CTX_new(pkey,NULL); EVP_PKEY_sign_init(pctx); if (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1())>0) { if (!SSL_USE_SIGALGS(s)) s->method->ssl3_enc->cert_verify_mac(s, NID_sha1, &(data[MD5_DIGEST_LENGTH])); } else { ERR_clear_error(); } /* For TLS v1.2 send signature algorithm and signature * using agreed digest and cached handshake records. */ if (SSL_USE_SIGALGS(s)) { long hdatalen = 0; void *hdata; const EVP_MD *md = s->cert->key->digest; hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata); if (hdatalen <= 0 || !tls12_get_sigandhash(p, pkey, md)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR); goto err; } p += 2; #ifdef SSL_DEBUG fprintf(stderr, "Using TLS 1.2 with client alg %s\n", EVP_MD_name(md)); #endif if (!EVP_SignInit_ex(&mctx, md, NULL) || !EVP_SignUpdate(&mctx, hdata, hdatalen) || !EVP_SignFinal(&mctx, p + 2, &u, pkey)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_EVP_LIB); goto err; } s2n(u,p); n = u + 4; if (!ssl3_digest_cached_records(s)) goto err; } else #ifndef OPENSSL_NO_RSA if (pkey->type == EVP_PKEY_RSA) { s->method->ssl3_enc->cert_verify_mac(s, NID_md5, &(data[0])); if (RSA_sign(NID_md5_sha1, data, MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, &(p[2]), &u, pkey->pkey.rsa) <= 0 ) { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB); goto err; } s2n(u,p); n=u+2; } else #endif #ifndef OPENSSL_NO_DSA if (pkey->type == EVP_PKEY_DSA) { if (!DSA_sign(pkey->save_type, &(data[MD5_DIGEST_LENGTH]), SHA_DIGEST_LENGTH,&(p[2]), (unsigned int *)&j,pkey->pkey.dsa)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB); goto err; } s2n(j,p); n=j+2; } else #endif #ifndef OPENSSL_NO_ECDSA if (pkey->type == EVP_PKEY_EC) { if (!ECDSA_sign(pkey->save_type, &(data[MD5_DIGEST_LENGTH]), SHA_DIGEST_LENGTH,&(p[2]), (unsigned int *)&j,pkey->pkey.ec)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_ECDSA_LIB); goto err; } s2n(j,p); n=j+2; } else #endif if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001) { unsigned char signbuf[64]; int i; size_t sigsize=64; s->method->ssl3_enc->cert_verify_mac(s, NID_id_GostR3411_94, data); if (EVP_PKEY_sign(pctx, signbuf, &sigsize, data, 32) <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR); goto err; } for (i=63,j=0; i>=0; j++, i--) { p[2+j]=signbuf[i]; } s2n(j,p); n=j+2; } else { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR); goto err; } ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_VERIFY, n); s->state=SSL3_ST_CW_CERT_VRFY_B; } EVP_MD_CTX_cleanup(&mctx); EVP_PKEY_CTX_free(pctx); return ssl_do_write(s); err: EVP_MD_CTX_cleanup(&mctx); EVP_PKEY_CTX_free(pctx); return(-1); } /* Check a certificate can be used for client authentication. Currently * check cert exists, if we have a suitable digest for TLS 1.2 if * static DH client certificates can be used and optionally checks * suitability for Suite B. */ static int ssl3_check_client_certificate(SSL *s) { unsigned long alg_k; if (!s->cert || !s->cert->key->x509 || !s->cert->key->privatekey) return 0; /* If no suitable signature algorithm can't use certificate */ if (SSL_USE_SIGALGS(s) && !s->cert->key->digest) return 0; /* If strict mode check suitability of chain before using it. * This also adjusts suite B digest if necessary. */ if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT && !tls1_check_chain(s, NULL, NULL, NULL, -2)) return 0; alg_k=s->s3->tmp.new_cipher->algorithm_mkey; /* See if we can use client certificate for fixed DH */ if (alg_k & (SSL_kDHr|SSL_kDHd)) { SESS_CERT *scert = s->session->sess_cert; int i = scert->peer_cert_type; EVP_PKEY *clkey = NULL, *spkey = NULL; clkey = s->cert->key->privatekey; /* If client key not DH assume it can be used */ if (EVP_PKEY_id(clkey) != EVP_PKEY_DH) return 1; if (i >= 0) spkey = X509_get_pubkey(scert->peer_pkeys[i].x509); if (spkey) { /* Compare server and client parameters */ i = EVP_PKEY_cmp_parameters(clkey, spkey); EVP_PKEY_free(spkey); if (i != 1) return 0; } s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY; } return 1; } int ssl3_send_client_certificate(SSL *s) { X509 *x509=NULL; EVP_PKEY *pkey=NULL; int i; if (s->state == SSL3_ST_CW_CERT_A) { /* Let cert callback update client certificates if required */ if (s->cert->cert_cb) { i = s->cert->cert_cb(s, s->cert->cert_cb_arg); if (i < 0) { s->rwstate=SSL_X509_LOOKUP; return -1; } if (i == 0) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR); return 0; } s->rwstate=SSL_NOTHING; } if (ssl3_check_client_certificate(s)) s->state=SSL3_ST_CW_CERT_C; else s->state=SSL3_ST_CW_CERT_B; } /* We need to get a client cert */ if (s->state == SSL3_ST_CW_CERT_B) { /* If we get an error, we need to * ssl->rwstate=SSL_X509_LOOKUP; return(-1); * We then get retied later */ i=0; i = ssl_do_client_cert_cb(s, &x509, &pkey); if (i < 0) { s->rwstate=SSL_X509_LOOKUP; return(-1); } s->rwstate=SSL_NOTHING; if ((i == 1) && (pkey != NULL) && (x509 != NULL)) { s->state=SSL3_ST_CW_CERT_B; if ( !SSL_use_certificate(s,x509) || !SSL_use_PrivateKey(s,pkey)) i=0; } else if (i == 1) { i=0; SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK); } if (x509 != NULL) X509_free(x509); if (pkey != NULL) EVP_PKEY_free(pkey); if (i && !ssl3_check_client_certificate(s)) i = 0; if (i == 0) { if (s->version == SSL3_VERSION) { s->s3->tmp.cert_req=0; ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE); return(1); } else { s->s3->tmp.cert_req=2; } } /* Ok, we have a cert */ s->state=SSL3_ST_CW_CERT_C; } if (s->state == SSL3_ST_CW_CERT_C) { s->state=SSL3_ST_CW_CERT_D; if (!ssl3_output_cert_chain(s, (s->s3->tmp.cert_req == 2)?NULL:s->cert->key)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR); ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR); return 0; } } /* SSL3_ST_CW_CERT_D */ return ssl_do_write(s); } #define has_bits(i,m) (((i)&(m)) == (m)) int ssl3_check_cert_and_algorithm(SSL *s) { int i,idx; long alg_k,alg_a; EVP_PKEY *pkey=NULL; SESS_CERT *sc; #ifndef OPENSSL_NO_RSA RSA *rsa; #endif #ifndef OPENSSL_NO_DH DH *dh; #endif alg_k=s->s3->tmp.new_cipher->algorithm_mkey; alg_a=s->s3->tmp.new_cipher->algorithm_auth; /* we don't have a certificate */ if ((alg_a & (SSL_aNULL|SSL_aKRB5)) || (alg_k & SSL_kPSK)) return(1); sc=s->session->sess_cert; if (sc == NULL) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,ERR_R_INTERNAL_ERROR); goto err; } #ifndef OPENSSL_NO_RSA rsa=s->session->sess_cert->peer_rsa_tmp; #endif #ifndef OPENSSL_NO_DH dh=s->session->sess_cert->peer_dh_tmp; #endif /* This is the passed certificate */ idx=sc->peer_cert_type; #ifndef OPENSSL_NO_ECDH if (idx == SSL_PKEY_ECC) { if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509, s) == 0) { /* check failed */ SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_BAD_ECC_CERT); goto f_err; } else { return 1; } } else if (alg_a & SSL_aECDSA) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_ECDSA_SIGNING_CERT); goto f_err; } else if (alg_k & (SSL_kECDHr|SSL_kECDHe)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_ECDH_CERT); goto f_err; } #endif pkey=X509_get_pubkey(sc->peer_pkeys[idx].x509); i=X509_certificate_type(sc->peer_pkeys[idx].x509,pkey); EVP_PKEY_free(pkey); /* Check that we have a certificate if we require one */ if ((alg_a & SSL_aRSA) && !has_bits(i,EVP_PK_RSA|EVP_PKT_SIGN)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_SIGNING_CERT); goto f_err; } #ifndef OPENSSL_NO_DSA else if ((alg_a & SSL_aDSS) && !has_bits(i,EVP_PK_DSA|EVP_PKT_SIGN)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DSA_SIGNING_CERT); goto f_err; } #endif #ifndef OPENSSL_NO_RSA if ((alg_k & SSL_kRSA) && !(has_bits(i,EVP_PK_RSA|EVP_PKT_ENC) || (rsa != NULL))) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_ENCRYPTING_CERT); goto f_err; } #endif #ifndef OPENSSL_NO_DH if ((alg_k & SSL_kDHE) && !(has_bits(i,EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL))) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_KEY); goto f_err; } else if ((alg_k & SSL_kDHr) && !SSL_USE_SIGALGS(s) && !has_bits(i,EVP_PK_DH|EVP_PKS_RSA)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_RSA_CERT); goto f_err; } #ifndef OPENSSL_NO_DSA else if ((alg_k & SSL_kDHd) && !SSL_USE_SIGALGS(s) && !has_bits(i,EVP_PK_DH|EVP_PKS_DSA)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_DSA_CERT); goto f_err; } #endif #endif if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && !has_bits(i,EVP_PKT_EXP)) { #ifndef OPENSSL_NO_RSA if (alg_k & SSL_kRSA) { if (rsa == NULL || RSA_size(rsa)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_RSA_KEY); goto f_err; } } else #endif #ifndef OPENSSL_NO_DH if (alg_k & (SSL_kDHE|SSL_kDHr|SSL_kDHd)) { if (dh == NULL || DH_size(dh)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_DH_KEY); goto f_err; } } else #endif { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE); goto f_err; } } return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); err: return(0); } /* Check to see if handshake is full or resumed. Usually this is just a * case of checking to see if a cache hit has occurred. In the case of * session tickets we have to check the next message to be sure. */ #ifndef OPENSSL_NO_TLSEXT # ifndef OPENSSL_NO_NEXTPROTONEG int ssl3_send_next_proto(SSL *s) { unsigned int len, padding_len; unsigned char *d; if (s->state == SSL3_ST_CW_NEXT_PROTO_A) { len = s->next_proto_negotiated_len; padding_len = 32 - ((len + 2) % 32); d = (unsigned char *)s->init_buf->data; d[4] = len; memcpy(d + 5, s->next_proto_negotiated, len); d[5 + len] = padding_len; memset(d + 6 + len, 0, padding_len); *(d++)=SSL3_MT_NEXT_PROTO; l2n3(2 + len + padding_len, d); s->state = SSL3_ST_CW_NEXT_PROTO_B; s->init_num = 4 + 2 + len + padding_len; s->init_off = 0; } return ssl3_do_write(s, SSL3_RT_HANDSHAKE); } # endif #endif int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey) { int i = 0; #ifndef OPENSSL_NO_ENGINE if (s->ctx->client_cert_engine) { i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s, SSL_get_client_CA_list(s), px509, ppkey, NULL, NULL, NULL); if (i != 0) return i; } #endif if (s->ctx->client_cert_cb) i = s->ctx->client_cert_cb(s,px509,ppkey); return i; }
./CrossVul/dataset_final_sorted/CWE-310/c/good_2152_1
crossvul-cpp_data_good_2309_4
/* crypto/x509/x_all.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <stdio.h> #include <openssl/stack.h> #include "cryptlib.h" #include <openssl/buffer.h> #include <openssl/asn1.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/ocsp.h> #ifndef OPENSSL_NO_RSA #include <openssl/rsa.h> #endif #ifndef OPENSSL_NO_DSA #include <openssl/dsa.h> #endif int X509_verify(X509 *a, EVP_PKEY *r) { if (X509_ALGOR_cmp(a->sig_alg, a->cert_info->signature)) return 0; return(ASN1_item_verify(ASN1_ITEM_rptr(X509_CINF),a->sig_alg, a->signature,a->cert_info,r)); } int X509_REQ_verify(X509_REQ *a, EVP_PKEY *r) { return( ASN1_item_verify(ASN1_ITEM_rptr(X509_REQ_INFO), a->sig_alg,a->signature,a->req_info,r)); } int NETSCAPE_SPKI_verify(NETSCAPE_SPKI *a, EVP_PKEY *r) { return(ASN1_item_verify(ASN1_ITEM_rptr(NETSCAPE_SPKAC), a->sig_algor,a->signature,a->spkac,r)); } int X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md) { x->cert_info->enc.modified = 1; return(ASN1_item_sign(ASN1_ITEM_rptr(X509_CINF), x->cert_info->signature, x->sig_alg, x->signature, x->cert_info,pkey,md)); } int X509_sign_ctx(X509 *x, EVP_MD_CTX *ctx) { x->cert_info->enc.modified = 1; return ASN1_item_sign_ctx(ASN1_ITEM_rptr(X509_CINF), x->cert_info->signature, x->sig_alg, x->signature, x->cert_info, ctx); } int X509_http_nbio(OCSP_REQ_CTX *rctx, X509 **pcert) { return OCSP_REQ_CTX_nbio_d2i(rctx, (ASN1_VALUE **)pcert, ASN1_ITEM_rptr(X509)); } int X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md) { return(ASN1_item_sign(ASN1_ITEM_rptr(X509_REQ_INFO),x->sig_alg, NULL, x->signature, x->req_info,pkey,md)); } int X509_REQ_sign_ctx(X509_REQ *x, EVP_MD_CTX *ctx) { return ASN1_item_sign_ctx(ASN1_ITEM_rptr(X509_REQ_INFO), x->sig_alg, NULL, x->signature, x->req_info, ctx); } int X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md) { x->crl->enc.modified = 1; return(ASN1_item_sign(ASN1_ITEM_rptr(X509_CRL_INFO),x->crl->sig_alg, x->sig_alg, x->signature, x->crl,pkey,md)); } int X509_CRL_sign_ctx(X509_CRL *x, EVP_MD_CTX *ctx) { x->crl->enc.modified = 1; return ASN1_item_sign_ctx(ASN1_ITEM_rptr(X509_CRL_INFO), x->crl->sig_alg, x->sig_alg, x->signature, x->crl, ctx); } int X509_CRL_http_nbio(OCSP_REQ_CTX *rctx, X509_CRL **pcrl) { return OCSP_REQ_CTX_nbio_d2i(rctx, (ASN1_VALUE **)pcrl, ASN1_ITEM_rptr(X509_CRL)); } int NETSCAPE_SPKI_sign(NETSCAPE_SPKI *x, EVP_PKEY *pkey, const EVP_MD *md) { return(ASN1_item_sign(ASN1_ITEM_rptr(NETSCAPE_SPKAC), x->sig_algor,NULL, x->signature, x->spkac,pkey,md)); } #ifndef OPENSSL_NO_FP_API X509 *d2i_X509_fp(FILE *fp, X509 **x509) { return ASN1_item_d2i_fp(ASN1_ITEM_rptr(X509), fp, x509); } int i2d_X509_fp(FILE *fp, X509 *x509) { return ASN1_item_i2d_fp(ASN1_ITEM_rptr(X509), fp, x509); } #endif X509 *d2i_X509_bio(BIO *bp, X509 **x509) { return ASN1_item_d2i_bio(ASN1_ITEM_rptr(X509), bp, x509); } int i2d_X509_bio(BIO *bp, X509 *x509) { return ASN1_item_i2d_bio(ASN1_ITEM_rptr(X509), bp, x509); } #ifndef OPENSSL_NO_FP_API X509_CRL *d2i_X509_CRL_fp(FILE *fp, X509_CRL **crl) { return ASN1_item_d2i_fp(ASN1_ITEM_rptr(X509_CRL), fp, crl); } int i2d_X509_CRL_fp(FILE *fp, X509_CRL *crl) { return ASN1_item_i2d_fp(ASN1_ITEM_rptr(X509_CRL), fp, crl); } #endif X509_CRL *d2i_X509_CRL_bio(BIO *bp, X509_CRL **crl) { return ASN1_item_d2i_bio(ASN1_ITEM_rptr(X509_CRL), bp, crl); } int i2d_X509_CRL_bio(BIO *bp, X509_CRL *crl) { return ASN1_item_i2d_bio(ASN1_ITEM_rptr(X509_CRL), bp, crl); } #ifndef OPENSSL_NO_FP_API PKCS7 *d2i_PKCS7_fp(FILE *fp, PKCS7 **p7) { return ASN1_item_d2i_fp(ASN1_ITEM_rptr(PKCS7), fp, p7); } int i2d_PKCS7_fp(FILE *fp, PKCS7 *p7) { return ASN1_item_i2d_fp(ASN1_ITEM_rptr(PKCS7), fp, p7); } #endif PKCS7 *d2i_PKCS7_bio(BIO *bp, PKCS7 **p7) { return ASN1_item_d2i_bio(ASN1_ITEM_rptr(PKCS7), bp, p7); } int i2d_PKCS7_bio(BIO *bp, PKCS7 *p7) { return ASN1_item_i2d_bio(ASN1_ITEM_rptr(PKCS7), bp, p7); } #ifndef OPENSSL_NO_FP_API X509_REQ *d2i_X509_REQ_fp(FILE *fp, X509_REQ **req) { return ASN1_item_d2i_fp(ASN1_ITEM_rptr(X509_REQ), fp, req); } int i2d_X509_REQ_fp(FILE *fp, X509_REQ *req) { return ASN1_item_i2d_fp(ASN1_ITEM_rptr(X509_REQ), fp, req); } #endif X509_REQ *d2i_X509_REQ_bio(BIO *bp, X509_REQ **req) { return ASN1_item_d2i_bio(ASN1_ITEM_rptr(X509_REQ), bp, req); } int i2d_X509_REQ_bio(BIO *bp, X509_REQ *req) { return ASN1_item_i2d_bio(ASN1_ITEM_rptr(X509_REQ), bp, req); } #ifndef OPENSSL_NO_RSA #ifndef OPENSSL_NO_FP_API RSA *d2i_RSAPrivateKey_fp(FILE *fp, RSA **rsa) { return ASN1_item_d2i_fp(ASN1_ITEM_rptr(RSAPrivateKey), fp, rsa); } int i2d_RSAPrivateKey_fp(FILE *fp, RSA *rsa) { return ASN1_item_i2d_fp(ASN1_ITEM_rptr(RSAPrivateKey), fp, rsa); } RSA *d2i_RSAPublicKey_fp(FILE *fp, RSA **rsa) { return ASN1_item_d2i_fp(ASN1_ITEM_rptr(RSAPublicKey), fp, rsa); } RSA *d2i_RSA_PUBKEY_fp(FILE *fp, RSA **rsa) { return ASN1_d2i_fp((void *(*)(void)) RSA_new,(D2I_OF(void))d2i_RSA_PUBKEY, fp, (void **)rsa); } int i2d_RSAPublicKey_fp(FILE *fp, RSA *rsa) { return ASN1_item_i2d_fp(ASN1_ITEM_rptr(RSAPublicKey), fp, rsa); } int i2d_RSA_PUBKEY_fp(FILE *fp, RSA *rsa) { return ASN1_i2d_fp((I2D_OF(void))i2d_RSA_PUBKEY,fp,rsa); } #endif RSA *d2i_RSAPrivateKey_bio(BIO *bp, RSA **rsa) { return ASN1_item_d2i_bio(ASN1_ITEM_rptr(RSAPrivateKey), bp, rsa); } int i2d_RSAPrivateKey_bio(BIO *bp, RSA *rsa) { return ASN1_item_i2d_bio(ASN1_ITEM_rptr(RSAPrivateKey), bp, rsa); } RSA *d2i_RSAPublicKey_bio(BIO *bp, RSA **rsa) { return ASN1_item_d2i_bio(ASN1_ITEM_rptr(RSAPublicKey), bp, rsa); } RSA *d2i_RSA_PUBKEY_bio(BIO *bp, RSA **rsa) { return ASN1_d2i_bio_of(RSA,RSA_new,d2i_RSA_PUBKEY,bp,rsa); } int i2d_RSAPublicKey_bio(BIO *bp, RSA *rsa) { return ASN1_item_i2d_bio(ASN1_ITEM_rptr(RSAPublicKey), bp, rsa); } int i2d_RSA_PUBKEY_bio(BIO *bp, RSA *rsa) { return ASN1_i2d_bio_of(RSA,i2d_RSA_PUBKEY,bp,rsa); } #endif #ifndef OPENSSL_NO_DSA #ifndef OPENSSL_NO_FP_API DSA *d2i_DSAPrivateKey_fp(FILE *fp, DSA **dsa) { return ASN1_d2i_fp_of(DSA,DSA_new,d2i_DSAPrivateKey,fp,dsa); } int i2d_DSAPrivateKey_fp(FILE *fp, DSA *dsa) { return ASN1_i2d_fp_of_const(DSA,i2d_DSAPrivateKey,fp,dsa); } DSA *d2i_DSA_PUBKEY_fp(FILE *fp, DSA **dsa) { return ASN1_d2i_fp_of(DSA,DSA_new,d2i_DSA_PUBKEY,fp,dsa); } int i2d_DSA_PUBKEY_fp(FILE *fp, DSA *dsa) { return ASN1_i2d_fp_of(DSA,i2d_DSA_PUBKEY,fp,dsa); } #endif DSA *d2i_DSAPrivateKey_bio(BIO *bp, DSA **dsa) { return ASN1_d2i_bio_of(DSA,DSA_new,d2i_DSAPrivateKey,bp,dsa ); } int i2d_DSAPrivateKey_bio(BIO *bp, DSA *dsa) { return ASN1_i2d_bio_of_const(DSA,i2d_DSAPrivateKey,bp,dsa); } DSA *d2i_DSA_PUBKEY_bio(BIO *bp, DSA **dsa) { return ASN1_d2i_bio_of(DSA,DSA_new,d2i_DSA_PUBKEY,bp,dsa); } int i2d_DSA_PUBKEY_bio(BIO *bp, DSA *dsa) { return ASN1_i2d_bio_of(DSA,i2d_DSA_PUBKEY,bp,dsa); } #endif #ifndef OPENSSL_NO_EC #ifndef OPENSSL_NO_FP_API EC_KEY *d2i_EC_PUBKEY_fp(FILE *fp, EC_KEY **eckey) { return ASN1_d2i_fp_of(EC_KEY,EC_KEY_new,d2i_EC_PUBKEY,fp,eckey); } int i2d_EC_PUBKEY_fp(FILE *fp, EC_KEY *eckey) { return ASN1_i2d_fp_of(EC_KEY,i2d_EC_PUBKEY,fp,eckey); } EC_KEY *d2i_ECPrivateKey_fp(FILE *fp, EC_KEY **eckey) { return ASN1_d2i_fp_of(EC_KEY,EC_KEY_new,d2i_ECPrivateKey,fp,eckey); } int i2d_ECPrivateKey_fp(FILE *fp, EC_KEY *eckey) { return ASN1_i2d_fp_of(EC_KEY,i2d_ECPrivateKey,fp,eckey); } #endif EC_KEY *d2i_EC_PUBKEY_bio(BIO *bp, EC_KEY **eckey) { return ASN1_d2i_bio_of(EC_KEY,EC_KEY_new,d2i_EC_PUBKEY,bp,eckey); } int i2d_EC_PUBKEY_bio(BIO *bp, EC_KEY *ecdsa) { return ASN1_i2d_bio_of(EC_KEY,i2d_EC_PUBKEY,bp,ecdsa); } EC_KEY *d2i_ECPrivateKey_bio(BIO *bp, EC_KEY **eckey) { return ASN1_d2i_bio_of(EC_KEY,EC_KEY_new,d2i_ECPrivateKey,bp,eckey); } int i2d_ECPrivateKey_bio(BIO *bp, EC_KEY *eckey) { return ASN1_i2d_bio_of(EC_KEY,i2d_ECPrivateKey,bp,eckey); } #endif int X509_pubkey_digest(const X509 *data, const EVP_MD *type, unsigned char *md, unsigned int *len) { ASN1_BIT_STRING *key; key = X509_get0_pubkey_bitstr(data); if(!key) return 0; return EVP_Digest(key->data, key->length, md, len, type, NULL); } int X509_digest(const X509 *data, const EVP_MD *type, unsigned char *md, unsigned int *len) { return(ASN1_item_digest(ASN1_ITEM_rptr(X509),type,(char *)data,md,len)); } int X509_CRL_digest(const X509_CRL *data, const EVP_MD *type, unsigned char *md, unsigned int *len) { return(ASN1_item_digest(ASN1_ITEM_rptr(X509_CRL),type,(char *)data,md,len)); } int X509_REQ_digest(const X509_REQ *data, const EVP_MD *type, unsigned char *md, unsigned int *len) { return(ASN1_item_digest(ASN1_ITEM_rptr(X509_REQ),type,(char *)data,md,len)); } int X509_NAME_digest(const X509_NAME *data, const EVP_MD *type, unsigned char *md, unsigned int *len) { return(ASN1_item_digest(ASN1_ITEM_rptr(X509_NAME),type,(char *)data,md,len)); } int PKCS7_ISSUER_AND_SERIAL_digest(PKCS7_ISSUER_AND_SERIAL *data, const EVP_MD *type, unsigned char *md, unsigned int *len) { return(ASN1_item_digest(ASN1_ITEM_rptr(PKCS7_ISSUER_AND_SERIAL),type, (char *)data,md,len)); } #ifndef OPENSSL_NO_FP_API X509_SIG *d2i_PKCS8_fp(FILE *fp, X509_SIG **p8) { return ASN1_d2i_fp_of(X509_SIG,X509_SIG_new,d2i_X509_SIG,fp,p8); } int i2d_PKCS8_fp(FILE *fp, X509_SIG *p8) { return ASN1_i2d_fp_of(X509_SIG,i2d_X509_SIG,fp,p8); } #endif X509_SIG *d2i_PKCS8_bio(BIO *bp, X509_SIG **p8) { return ASN1_d2i_bio_of(X509_SIG,X509_SIG_new,d2i_X509_SIG,bp,p8); } int i2d_PKCS8_bio(BIO *bp, X509_SIG *p8) { return ASN1_i2d_bio_of(X509_SIG,i2d_X509_SIG,bp,p8); } #ifndef OPENSSL_NO_FP_API PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_fp(FILE *fp, PKCS8_PRIV_KEY_INFO **p8inf) { return ASN1_d2i_fp_of(PKCS8_PRIV_KEY_INFO,PKCS8_PRIV_KEY_INFO_new, d2i_PKCS8_PRIV_KEY_INFO,fp,p8inf); } int i2d_PKCS8_PRIV_KEY_INFO_fp(FILE *fp, PKCS8_PRIV_KEY_INFO *p8inf) { return ASN1_i2d_fp_of(PKCS8_PRIV_KEY_INFO,i2d_PKCS8_PRIV_KEY_INFO,fp, p8inf); } int i2d_PKCS8PrivateKeyInfo_fp(FILE *fp, EVP_PKEY *key) { PKCS8_PRIV_KEY_INFO *p8inf; int ret; p8inf = EVP_PKEY2PKCS8(key); if(!p8inf) return 0; ret = i2d_PKCS8_PRIV_KEY_INFO_fp(fp, p8inf); PKCS8_PRIV_KEY_INFO_free(p8inf); return ret; } int i2d_PrivateKey_fp(FILE *fp, EVP_PKEY *pkey) { return ASN1_i2d_fp_of(EVP_PKEY,i2d_PrivateKey,fp,pkey); } EVP_PKEY *d2i_PrivateKey_fp(FILE *fp, EVP_PKEY **a) { return ASN1_d2i_fp_of(EVP_PKEY,EVP_PKEY_new,d2i_AutoPrivateKey,fp,a); } int i2d_PUBKEY_fp(FILE *fp, EVP_PKEY *pkey) { return ASN1_i2d_fp_of(EVP_PKEY,i2d_PUBKEY,fp,pkey); } EVP_PKEY *d2i_PUBKEY_fp(FILE *fp, EVP_PKEY **a) { return ASN1_d2i_fp_of(EVP_PKEY,EVP_PKEY_new,d2i_PUBKEY,fp,a); } #endif PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_bio(BIO *bp, PKCS8_PRIV_KEY_INFO **p8inf) { return ASN1_d2i_bio_of(PKCS8_PRIV_KEY_INFO,PKCS8_PRIV_KEY_INFO_new, d2i_PKCS8_PRIV_KEY_INFO,bp,p8inf); } int i2d_PKCS8_PRIV_KEY_INFO_bio(BIO *bp, PKCS8_PRIV_KEY_INFO *p8inf) { return ASN1_i2d_bio_of(PKCS8_PRIV_KEY_INFO,i2d_PKCS8_PRIV_KEY_INFO,bp, p8inf); } int i2d_PKCS8PrivateKeyInfo_bio(BIO *bp, EVP_PKEY *key) { PKCS8_PRIV_KEY_INFO *p8inf; int ret; p8inf = EVP_PKEY2PKCS8(key); if(!p8inf) return 0; ret = i2d_PKCS8_PRIV_KEY_INFO_bio(bp, p8inf); PKCS8_PRIV_KEY_INFO_free(p8inf); return ret; } int i2d_PrivateKey_bio(BIO *bp, EVP_PKEY *pkey) { return ASN1_i2d_bio_of(EVP_PKEY,i2d_PrivateKey,bp,pkey); } EVP_PKEY *d2i_PrivateKey_bio(BIO *bp, EVP_PKEY **a) { return ASN1_d2i_bio_of(EVP_PKEY,EVP_PKEY_new,d2i_AutoPrivateKey,bp,a); } int i2d_PUBKEY_bio(BIO *bp, EVP_PKEY *pkey) { return ASN1_i2d_bio_of(EVP_PKEY,i2d_PUBKEY,bp,pkey); } EVP_PKEY *d2i_PUBKEY_bio(BIO *bp, EVP_PKEY **a) { return ASN1_d2i_bio_of(EVP_PKEY,EVP_PKEY_new,d2i_PUBKEY,bp,a); }
./CrossVul/dataset_final_sorted/CWE-310/c/good_2309_4
crossvul-cpp_data_bad_5666_0
/* * Asynchronous block chaining cipher operations. * * This is the asynchronous version of blkcipher.c indicating completion * via a callback. * * Copyright (c) 2006 Herbert Xu <herbert@gondor.apana.org.au> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include <crypto/internal/skcipher.h> #include <linux/cpumask.h> #include <linux/err.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/rtnetlink.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/seq_file.h> #include <linux/cryptouser.h> #include <net/netlink.h> #include <crypto/scatterwalk.h> #include "internal.h" static const char *skcipher_default_geniv __read_mostly; struct ablkcipher_buffer { struct list_head entry; struct scatter_walk dst; unsigned int len; void *data; }; enum { ABLKCIPHER_WALK_SLOW = 1 << 0, }; static inline void ablkcipher_buffer_write(struct ablkcipher_buffer *p) { scatterwalk_copychunks(p->data, &p->dst, p->len, 1); } void __ablkcipher_walk_complete(struct ablkcipher_walk *walk) { struct ablkcipher_buffer *p, *tmp; list_for_each_entry_safe(p, tmp, &walk->buffers, entry) { ablkcipher_buffer_write(p); list_del(&p->entry); kfree(p); } } EXPORT_SYMBOL_GPL(__ablkcipher_walk_complete); static inline void ablkcipher_queue_write(struct ablkcipher_walk *walk, struct ablkcipher_buffer *p) { p->dst = walk->out; list_add_tail(&p->entry, &walk->buffers); } /* Get a spot of the specified length that does not straddle a page. * The caller needs to ensure that there is enough space for this operation. */ static inline u8 *ablkcipher_get_spot(u8 *start, unsigned int len) { u8 *end_page = (u8 *)(((unsigned long)(start + len - 1)) & PAGE_MASK); return max(start, end_page); } static inline unsigned int ablkcipher_done_slow(struct ablkcipher_walk *walk, unsigned int bsize) { unsigned int n = bsize; for (;;) { unsigned int len_this_page = scatterwalk_pagelen(&walk->out); if (len_this_page > n) len_this_page = n; scatterwalk_advance(&walk->out, n); if (n == len_this_page) break; n -= len_this_page; scatterwalk_start(&walk->out, scatterwalk_sg_next(walk->out.sg)); } return bsize; } static inline unsigned int ablkcipher_done_fast(struct ablkcipher_walk *walk, unsigned int n) { scatterwalk_advance(&walk->in, n); scatterwalk_advance(&walk->out, n); return n; } static int ablkcipher_walk_next(struct ablkcipher_request *req, struct ablkcipher_walk *walk); int ablkcipher_walk_done(struct ablkcipher_request *req, struct ablkcipher_walk *walk, int err) { struct crypto_tfm *tfm = req->base.tfm; unsigned int nbytes = 0; if (likely(err >= 0)) { unsigned int n = walk->nbytes - err; if (likely(!(walk->flags & ABLKCIPHER_WALK_SLOW))) n = ablkcipher_done_fast(walk, n); else if (WARN_ON(err)) { err = -EINVAL; goto err; } else n = ablkcipher_done_slow(walk, n); nbytes = walk->total - n; err = 0; } scatterwalk_done(&walk->in, 0, nbytes); scatterwalk_done(&walk->out, 1, nbytes); err: walk->total = nbytes; walk->nbytes = nbytes; if (nbytes) { crypto_yield(req->base.flags); return ablkcipher_walk_next(req, walk); } if (walk->iv != req->info) memcpy(req->info, walk->iv, tfm->crt_ablkcipher.ivsize); kfree(walk->iv_buffer); return err; } EXPORT_SYMBOL_GPL(ablkcipher_walk_done); static inline int ablkcipher_next_slow(struct ablkcipher_request *req, struct ablkcipher_walk *walk, unsigned int bsize, unsigned int alignmask, void **src_p, void **dst_p) { unsigned aligned_bsize = ALIGN(bsize, alignmask + 1); struct ablkcipher_buffer *p; void *src, *dst, *base; unsigned int n; n = ALIGN(sizeof(struct ablkcipher_buffer), alignmask + 1); n += (aligned_bsize * 3 - (alignmask + 1) + (alignmask & ~(crypto_tfm_ctx_alignment() - 1))); p = kmalloc(n, GFP_ATOMIC); if (!p) return ablkcipher_walk_done(req, walk, -ENOMEM); base = p + 1; dst = (u8 *)ALIGN((unsigned long)base, alignmask + 1); src = dst = ablkcipher_get_spot(dst, bsize); p->len = bsize; p->data = dst; scatterwalk_copychunks(src, &walk->in, bsize, 0); ablkcipher_queue_write(walk, p); walk->nbytes = bsize; walk->flags |= ABLKCIPHER_WALK_SLOW; *src_p = src; *dst_p = dst; return 0; } static inline int ablkcipher_copy_iv(struct ablkcipher_walk *walk, struct crypto_tfm *tfm, unsigned int alignmask) { unsigned bs = walk->blocksize; unsigned int ivsize = tfm->crt_ablkcipher.ivsize; unsigned aligned_bs = ALIGN(bs, alignmask + 1); unsigned int size = aligned_bs * 2 + ivsize + max(aligned_bs, ivsize) - (alignmask + 1); u8 *iv; size += alignmask & ~(crypto_tfm_ctx_alignment() - 1); walk->iv_buffer = kmalloc(size, GFP_ATOMIC); if (!walk->iv_buffer) return -ENOMEM; iv = (u8 *)ALIGN((unsigned long)walk->iv_buffer, alignmask + 1); iv = ablkcipher_get_spot(iv, bs) + aligned_bs; iv = ablkcipher_get_spot(iv, bs) + aligned_bs; iv = ablkcipher_get_spot(iv, ivsize); walk->iv = memcpy(iv, walk->iv, ivsize); return 0; } static inline int ablkcipher_next_fast(struct ablkcipher_request *req, struct ablkcipher_walk *walk) { walk->src.page = scatterwalk_page(&walk->in); walk->src.offset = offset_in_page(walk->in.offset); walk->dst.page = scatterwalk_page(&walk->out); walk->dst.offset = offset_in_page(walk->out.offset); return 0; } static int ablkcipher_walk_next(struct ablkcipher_request *req, struct ablkcipher_walk *walk) { struct crypto_tfm *tfm = req->base.tfm; unsigned int alignmask, bsize, n; void *src, *dst; int err; alignmask = crypto_tfm_alg_alignmask(tfm); n = walk->total; if (unlikely(n < crypto_tfm_alg_blocksize(tfm))) { req->base.flags |= CRYPTO_TFM_RES_BAD_BLOCK_LEN; return ablkcipher_walk_done(req, walk, -EINVAL); } walk->flags &= ~ABLKCIPHER_WALK_SLOW; src = dst = NULL; bsize = min(walk->blocksize, n); n = scatterwalk_clamp(&walk->in, n); n = scatterwalk_clamp(&walk->out, n); if (n < bsize || !scatterwalk_aligned(&walk->in, alignmask) || !scatterwalk_aligned(&walk->out, alignmask)) { err = ablkcipher_next_slow(req, walk, bsize, alignmask, &src, &dst); goto set_phys_lowmem; } walk->nbytes = n; return ablkcipher_next_fast(req, walk); set_phys_lowmem: if (err >= 0) { walk->src.page = virt_to_page(src); walk->dst.page = virt_to_page(dst); walk->src.offset = ((unsigned long)src & (PAGE_SIZE - 1)); walk->dst.offset = ((unsigned long)dst & (PAGE_SIZE - 1)); } return err; } static int ablkcipher_walk_first(struct ablkcipher_request *req, struct ablkcipher_walk *walk) { struct crypto_tfm *tfm = req->base.tfm; unsigned int alignmask; alignmask = crypto_tfm_alg_alignmask(tfm); if (WARN_ON_ONCE(in_irq())) return -EDEADLK; walk->nbytes = walk->total; if (unlikely(!walk->total)) return 0; walk->iv_buffer = NULL; walk->iv = req->info; if (unlikely(((unsigned long)walk->iv & alignmask))) { int err = ablkcipher_copy_iv(walk, tfm, alignmask); if (err) return err; } scatterwalk_start(&walk->in, walk->in.sg); scatterwalk_start(&walk->out, walk->out.sg); return ablkcipher_walk_next(req, walk); } int ablkcipher_walk_phys(struct ablkcipher_request *req, struct ablkcipher_walk *walk) { walk->blocksize = crypto_tfm_alg_blocksize(req->base.tfm); return ablkcipher_walk_first(req, walk); } EXPORT_SYMBOL_GPL(ablkcipher_walk_phys); static int setkey_unaligned(struct crypto_ablkcipher *tfm, const u8 *key, unsigned int keylen) { struct ablkcipher_alg *cipher = crypto_ablkcipher_alg(tfm); unsigned long alignmask = crypto_ablkcipher_alignmask(tfm); int ret; u8 *buffer, *alignbuffer; unsigned long absize; absize = keylen + alignmask; buffer = kmalloc(absize, GFP_ATOMIC); if (!buffer) return -ENOMEM; alignbuffer = (u8 *)ALIGN((unsigned long)buffer, alignmask + 1); memcpy(alignbuffer, key, keylen); ret = cipher->setkey(tfm, alignbuffer, keylen); memset(alignbuffer, 0, keylen); kfree(buffer); return ret; } static int setkey(struct crypto_ablkcipher *tfm, const u8 *key, unsigned int keylen) { struct ablkcipher_alg *cipher = crypto_ablkcipher_alg(tfm); unsigned long alignmask = crypto_ablkcipher_alignmask(tfm); if (keylen < cipher->min_keysize || keylen > cipher->max_keysize) { crypto_ablkcipher_set_flags(tfm, CRYPTO_TFM_RES_BAD_KEY_LEN); return -EINVAL; } if ((unsigned long)key & alignmask) return setkey_unaligned(tfm, key, keylen); return cipher->setkey(tfm, key, keylen); } static unsigned int crypto_ablkcipher_ctxsize(struct crypto_alg *alg, u32 type, u32 mask) { return alg->cra_ctxsize; } int skcipher_null_givencrypt(struct skcipher_givcrypt_request *req) { return crypto_ablkcipher_encrypt(&req->creq); } int skcipher_null_givdecrypt(struct skcipher_givcrypt_request *req) { return crypto_ablkcipher_decrypt(&req->creq); } static int crypto_init_ablkcipher_ops(struct crypto_tfm *tfm, u32 type, u32 mask) { struct ablkcipher_alg *alg = &tfm->__crt_alg->cra_ablkcipher; struct ablkcipher_tfm *crt = &tfm->crt_ablkcipher; if (alg->ivsize > PAGE_SIZE / 8) return -EINVAL; crt->setkey = setkey; crt->encrypt = alg->encrypt; crt->decrypt = alg->decrypt; if (!alg->ivsize) { crt->givencrypt = skcipher_null_givencrypt; crt->givdecrypt = skcipher_null_givdecrypt; } crt->base = __crypto_ablkcipher_cast(tfm); crt->ivsize = alg->ivsize; return 0; } #ifdef CONFIG_NET static int crypto_ablkcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_blkcipher rblkcipher; snprintf(rblkcipher.type, CRYPTO_MAX_ALG_NAME, "%s", "ablkcipher"); snprintf(rblkcipher.geniv, CRYPTO_MAX_ALG_NAME, "%s", alg->cra_ablkcipher.geniv ?: "<default>"); rblkcipher.blocksize = alg->cra_blocksize; rblkcipher.min_keysize = alg->cra_ablkcipher.min_keysize; rblkcipher.max_keysize = alg->cra_ablkcipher.max_keysize; rblkcipher.ivsize = alg->cra_ablkcipher.ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER, sizeof(struct crypto_report_blkcipher), &rblkcipher)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } #else static int crypto_ablkcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { return -ENOSYS; } #endif static void crypto_ablkcipher_show(struct seq_file *m, struct crypto_alg *alg) __attribute__ ((unused)); static void crypto_ablkcipher_show(struct seq_file *m, struct crypto_alg *alg) { struct ablkcipher_alg *ablkcipher = &alg->cra_ablkcipher; seq_printf(m, "type : ablkcipher\n"); seq_printf(m, "async : %s\n", alg->cra_flags & CRYPTO_ALG_ASYNC ? "yes" : "no"); seq_printf(m, "blocksize : %u\n", alg->cra_blocksize); seq_printf(m, "min keysize : %u\n", ablkcipher->min_keysize); seq_printf(m, "max keysize : %u\n", ablkcipher->max_keysize); seq_printf(m, "ivsize : %u\n", ablkcipher->ivsize); seq_printf(m, "geniv : %s\n", ablkcipher->geniv ?: "<default>"); } const struct crypto_type crypto_ablkcipher_type = { .ctxsize = crypto_ablkcipher_ctxsize, .init = crypto_init_ablkcipher_ops, #ifdef CONFIG_PROC_FS .show = crypto_ablkcipher_show, #endif .report = crypto_ablkcipher_report, }; EXPORT_SYMBOL_GPL(crypto_ablkcipher_type); static int no_givdecrypt(struct skcipher_givcrypt_request *req) { return -ENOSYS; } static int crypto_init_givcipher_ops(struct crypto_tfm *tfm, u32 type, u32 mask) { struct ablkcipher_alg *alg = &tfm->__crt_alg->cra_ablkcipher; struct ablkcipher_tfm *crt = &tfm->crt_ablkcipher; if (alg->ivsize > PAGE_SIZE / 8) return -EINVAL; crt->setkey = tfm->__crt_alg->cra_flags & CRYPTO_ALG_GENIV ? alg->setkey : setkey; crt->encrypt = alg->encrypt; crt->decrypt = alg->decrypt; crt->givencrypt = alg->givencrypt; crt->givdecrypt = alg->givdecrypt ?: no_givdecrypt; crt->base = __crypto_ablkcipher_cast(tfm); crt->ivsize = alg->ivsize; return 0; } #ifdef CONFIG_NET static int crypto_givcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_blkcipher rblkcipher; snprintf(rblkcipher.type, CRYPTO_MAX_ALG_NAME, "%s", "givcipher"); snprintf(rblkcipher.geniv, CRYPTO_MAX_ALG_NAME, "%s", alg->cra_ablkcipher.geniv ?: "<built-in>"); rblkcipher.blocksize = alg->cra_blocksize; rblkcipher.min_keysize = alg->cra_ablkcipher.min_keysize; rblkcipher.max_keysize = alg->cra_ablkcipher.max_keysize; rblkcipher.ivsize = alg->cra_ablkcipher.ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER, sizeof(struct crypto_report_blkcipher), &rblkcipher)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } #else static int crypto_givcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { return -ENOSYS; } #endif static void crypto_givcipher_show(struct seq_file *m, struct crypto_alg *alg) __attribute__ ((unused)); static void crypto_givcipher_show(struct seq_file *m, struct crypto_alg *alg) { struct ablkcipher_alg *ablkcipher = &alg->cra_ablkcipher; seq_printf(m, "type : givcipher\n"); seq_printf(m, "async : %s\n", alg->cra_flags & CRYPTO_ALG_ASYNC ? "yes" : "no"); seq_printf(m, "blocksize : %u\n", alg->cra_blocksize); seq_printf(m, "min keysize : %u\n", ablkcipher->min_keysize); seq_printf(m, "max keysize : %u\n", ablkcipher->max_keysize); seq_printf(m, "ivsize : %u\n", ablkcipher->ivsize); seq_printf(m, "geniv : %s\n", ablkcipher->geniv ?: "<built-in>"); } const struct crypto_type crypto_givcipher_type = { .ctxsize = crypto_ablkcipher_ctxsize, .init = crypto_init_givcipher_ops, #ifdef CONFIG_PROC_FS .show = crypto_givcipher_show, #endif .report = crypto_givcipher_report, }; EXPORT_SYMBOL_GPL(crypto_givcipher_type); const char *crypto_default_geniv(const struct crypto_alg *alg) { if (((alg->cra_flags & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_BLKCIPHER ? alg->cra_blkcipher.ivsize : alg->cra_ablkcipher.ivsize) != alg->cra_blocksize) return "chainiv"; return alg->cra_flags & CRYPTO_ALG_ASYNC ? "eseqiv" : skcipher_default_geniv; } static int crypto_givcipher_default(struct crypto_alg *alg, u32 type, u32 mask) { struct rtattr *tb[3]; struct { struct rtattr attr; struct crypto_attr_type data; } ptype; struct { struct rtattr attr; struct crypto_attr_alg data; } palg; struct crypto_template *tmpl; struct crypto_instance *inst; struct crypto_alg *larval; const char *geniv; int err; larval = crypto_larval_lookup(alg->cra_driver_name, (type & ~CRYPTO_ALG_TYPE_MASK) | CRYPTO_ALG_TYPE_GIVCIPHER, mask | CRYPTO_ALG_TYPE_MASK); err = PTR_ERR(larval); if (IS_ERR(larval)) goto out; err = -EAGAIN; if (!crypto_is_larval(larval)) goto drop_larval; ptype.attr.rta_len = sizeof(ptype); ptype.attr.rta_type = CRYPTOA_TYPE; ptype.data.type = type | CRYPTO_ALG_GENIV; /* GENIV tells the template that we're making a default geniv. */ ptype.data.mask = mask | CRYPTO_ALG_GENIV; tb[0] = &ptype.attr; palg.attr.rta_len = sizeof(palg); palg.attr.rta_type = CRYPTOA_ALG; /* Must use the exact name to locate ourselves. */ memcpy(palg.data.name, alg->cra_driver_name, CRYPTO_MAX_ALG_NAME); tb[1] = &palg.attr; tb[2] = NULL; if ((alg->cra_flags & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_BLKCIPHER) geniv = alg->cra_blkcipher.geniv; else geniv = alg->cra_ablkcipher.geniv; if (!geniv) geniv = crypto_default_geniv(alg); tmpl = crypto_lookup_template(geniv); err = -ENOENT; if (!tmpl) goto kill_larval; inst = tmpl->alloc(tb); err = PTR_ERR(inst); if (IS_ERR(inst)) goto put_tmpl; if ((err = crypto_register_instance(tmpl, inst))) { tmpl->free(inst); goto put_tmpl; } /* Redo the lookup to use the instance we just registered. */ err = -EAGAIN; put_tmpl: crypto_tmpl_put(tmpl); kill_larval: crypto_larval_kill(larval); drop_larval: crypto_mod_put(larval); out: crypto_mod_put(alg); return err; } struct crypto_alg *crypto_lookup_skcipher(const char *name, u32 type, u32 mask) { struct crypto_alg *alg; alg = crypto_alg_mod_lookup(name, type, mask); if (IS_ERR(alg)) return alg; if ((alg->cra_flags & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_GIVCIPHER) return alg; if (!((alg->cra_flags & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_BLKCIPHER ? alg->cra_blkcipher.ivsize : alg->cra_ablkcipher.ivsize)) return alg; crypto_mod_put(alg); alg = crypto_alg_mod_lookup(name, type | CRYPTO_ALG_TESTED, mask & ~CRYPTO_ALG_TESTED); if (IS_ERR(alg)) return alg; if ((alg->cra_flags & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_GIVCIPHER) { if ((alg->cra_flags ^ type ^ ~mask) & CRYPTO_ALG_TESTED) { crypto_mod_put(alg); alg = ERR_PTR(-ENOENT); } return alg; } BUG_ON(!((alg->cra_flags & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_BLKCIPHER ? alg->cra_blkcipher.ivsize : alg->cra_ablkcipher.ivsize)); return ERR_PTR(crypto_givcipher_default(alg, type, mask)); } EXPORT_SYMBOL_GPL(crypto_lookup_skcipher); int crypto_grab_skcipher(struct crypto_skcipher_spawn *spawn, const char *name, u32 type, u32 mask) { struct crypto_alg *alg; int err; type = crypto_skcipher_type(type); mask = crypto_skcipher_mask(mask); alg = crypto_lookup_skcipher(name, type, mask); if (IS_ERR(alg)) return PTR_ERR(alg); err = crypto_init_spawn(&spawn->base, alg, spawn->base.inst, mask); crypto_mod_put(alg); return err; } EXPORT_SYMBOL_GPL(crypto_grab_skcipher); struct crypto_ablkcipher *crypto_alloc_ablkcipher(const char *alg_name, u32 type, u32 mask) { struct crypto_tfm *tfm; int err; type = crypto_skcipher_type(type); mask = crypto_skcipher_mask(mask); for (;;) { struct crypto_alg *alg; alg = crypto_lookup_skcipher(alg_name, type, mask); if (IS_ERR(alg)) { err = PTR_ERR(alg); goto err; } tfm = __crypto_alloc_tfm(alg, type, mask); if (!IS_ERR(tfm)) return __crypto_ablkcipher_cast(tfm); crypto_mod_put(alg); err = PTR_ERR(tfm); err: if (err != -EAGAIN) break; if (signal_pending(current)) { err = -EINTR; break; } } return ERR_PTR(err); } EXPORT_SYMBOL_GPL(crypto_alloc_ablkcipher); static int __init skcipher_module_init(void) { skcipher_default_geniv = num_possible_cpus() > 1 ? "eseqiv" : "chainiv"; return 0; } static void skcipher_module_exit(void) { } module_init(skcipher_module_init); module_exit(skcipher_module_exit);
./CrossVul/dataset_final_sorted/CWE-310/c/bad_5666_0
crossvul-cpp_data_bad_2309_1
/* crypto/asn1/a_verify.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <stdio.h> #include <time.h> #include "cryptlib.h" #ifndef NO_SYS_TYPES_H # include <sys/types.h> #endif #include <openssl/bn.h> #include <openssl/x509.h> #include <openssl/objects.h> #include <openssl/buffer.h> #include <openssl/evp.h> #include "asn1_locl.h" #ifndef NO_ASN1_OLD int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *a, ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey) { EVP_MD_CTX ctx; const EVP_MD *type; unsigned char *p,*buf_in=NULL; int ret= -1,i,inl; EVP_MD_CTX_init(&ctx); i=OBJ_obj2nid(a->algorithm); type=EVP_get_digestbyname(OBJ_nid2sn(i)); if (type == NULL) { ASN1err(ASN1_F_ASN1_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } inl=i2d(data,NULL); buf_in=OPENSSL_malloc((unsigned int)inl); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } p=buf_in; i2d(data,&p); ret= EVP_VerifyInit_ex(&ctx,type, NULL) && EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl); OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (!ret) { ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB); goto err; } ret = -1; if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data, (unsigned int)signature->length,pkey) <= 0) { ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); } #endif int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; unsigned char *buf_in=NULL; int ret= -1,inl; int mdnid, pknid; if (!pkey) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER); return -1; } EVP_MD_CTX_init(&ctx); /* Convert signature OID into digest and public key OIDs */ if (!OBJ_find_sigid_algs(OBJ_obj2nid(a->algorithm), &mdnid, &pknid)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } if (mdnid == NID_undef) { if (!pkey->ameth || !pkey->ameth->item_verify) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } ret = pkey->ameth->item_verify(&ctx, it, asn, a, signature, pkey); /* Return value of 2 means carry on, anything else means we * exit straight away: either a fatal error of the underlying * verification routine handles all verification. */ if (ret != 2) goto err; ret = -1; } else { const EVP_MD *type; type=EVP_get_digestbynid(mdnid); if (type == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } /* Check public key OID matches public key type */ if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE); goto err; } if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } ret = EVP_DigestVerifyUpdate(&ctx,buf_in,inl); OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); goto err; } ret = -1; if (EVP_DigestVerifyFinal(&ctx,signature->data, (size_t)signature->length) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); }
./CrossVul/dataset_final_sorted/CWE-310/c/bad_2309_1
crossvul-cpp_data_bad_2309_2
/* dsa_asn1.c */ /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL * project 2000. */ /* ==================================================================== * Copyright (c) 2000-2005 The OpenSSL 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: * * 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. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include <stdio.h> #include "cryptlib.h" #include <openssl/dsa.h> #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/rand.h> /* Override the default new methods */ static int sig_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { if(operation == ASN1_OP_NEW_PRE) { DSA_SIG *sig; sig = OPENSSL_malloc(sizeof(DSA_SIG)); if (!sig) { DSAerr(DSA_F_SIG_CB, ERR_R_MALLOC_FAILURE); return 0; } sig->r = NULL; sig->s = NULL; *pval = (ASN1_VALUE *)sig; return 2; } return 1; } ASN1_SEQUENCE_cb(DSA_SIG, sig_cb) = { ASN1_SIMPLE(DSA_SIG, r, CBIGNUM), ASN1_SIMPLE(DSA_SIG, s, CBIGNUM) } ASN1_SEQUENCE_END_cb(DSA_SIG, DSA_SIG) IMPLEMENT_ASN1_FUNCTIONS_const(DSA_SIG) /* Override the default free and new methods */ static int dsa_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { if(operation == ASN1_OP_NEW_PRE) { *pval = (ASN1_VALUE *)DSA_new(); if(*pval) return 2; return 0; } else if(operation == ASN1_OP_FREE_PRE) { DSA_free((DSA *)*pval); *pval = NULL; return 2; } return 1; } ASN1_SEQUENCE_cb(DSAPrivateKey, dsa_cb) = { ASN1_SIMPLE(DSA, version, LONG), ASN1_SIMPLE(DSA, p, BIGNUM), ASN1_SIMPLE(DSA, q, BIGNUM), ASN1_SIMPLE(DSA, g, BIGNUM), ASN1_SIMPLE(DSA, pub_key, BIGNUM), ASN1_SIMPLE(DSA, priv_key, BIGNUM) } ASN1_SEQUENCE_END_cb(DSA, DSAPrivateKey) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(DSA, DSAPrivateKey, DSAPrivateKey) ASN1_SEQUENCE_cb(DSAparams, dsa_cb) = { ASN1_SIMPLE(DSA, p, BIGNUM), ASN1_SIMPLE(DSA, q, BIGNUM), ASN1_SIMPLE(DSA, g, BIGNUM), } ASN1_SEQUENCE_END_cb(DSA, DSAparams) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(DSA, DSAparams, DSAparams) /* DSA public key is a bit trickier... its effectively a CHOICE type * decided by a field called write_params which can either write out * just the public key as an INTEGER or the parameters and public key * in a SEQUENCE */ ASN1_SEQUENCE(dsa_pub_internal) = { ASN1_SIMPLE(DSA, pub_key, BIGNUM), ASN1_SIMPLE(DSA, p, BIGNUM), ASN1_SIMPLE(DSA, q, BIGNUM), ASN1_SIMPLE(DSA, g, BIGNUM) } ASN1_SEQUENCE_END_name(DSA, dsa_pub_internal) ASN1_CHOICE_cb(DSAPublicKey, dsa_cb) = { ASN1_SIMPLE(DSA, pub_key, BIGNUM), ASN1_EX_COMBINE(0, 0, dsa_pub_internal) } ASN1_CHOICE_END_cb(DSA, DSAPublicKey, write_params) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(DSA, DSAPublicKey, DSAPublicKey) DSA *DSAparams_dup(DSA *dsa) { return ASN1_item_dup(ASN1_ITEM_rptr(DSAparams), dsa); } int DSA_sign(int type, const unsigned char *dgst, int dlen, unsigned char *sig, unsigned int *siglen, DSA *dsa) { DSA_SIG *s; RAND_seed(dgst, dlen); s=DSA_do_sign(dgst,dlen,dsa); if (s == NULL) { *siglen=0; return(0); } *siglen=i2d_DSA_SIG(s,&sig); DSA_SIG_free(s); return(1); } /* data has already been hashed (probably with SHA or SHA-1). */ /*- * returns * 1: correct signature * 0: incorrect signature * -1: error */ int DSA_verify(int type, const unsigned char *dgst, int dgst_len, const unsigned char *sigbuf, int siglen, DSA *dsa) { DSA_SIG *s; int ret=-1; s = DSA_SIG_new(); if (s == NULL) return(ret); if (d2i_DSA_SIG(&s,&sigbuf,siglen) == NULL) goto err; ret=DSA_do_verify(dgst,dgst_len,s,dsa); err: DSA_SIG_free(s); return(ret); }
./CrossVul/dataset_final_sorted/CWE-310/c/bad_2309_2
crossvul-cpp_data_bad_5329_0
/* * 'OpenSSL for Ruby' project * Copyright (C) 2001-2002 Michal Rokos <m.rokos@sh.cvut.cz> * All rights reserved. */ /* * This program is licensed under the same licence as Ruby. * (See the file 'LICENCE'.) */ #include "ossl.h" #define NewCipher(klass) \ TypedData_Wrap_Struct((klass), &ossl_cipher_type, 0) #define AllocCipher(obj, ctx) do { \ (ctx) = EVP_CIPHER_CTX_new(); \ if (!(ctx)) \ ossl_raise(rb_eRuntimeError, NULL); \ RTYPEDDATA_DATA(obj) = (ctx); \ } while (0) #define GetCipherInit(obj, ctx) do { \ TypedData_Get_Struct((obj), EVP_CIPHER_CTX, &ossl_cipher_type, (ctx)); \ } while (0) #define GetCipher(obj, ctx) do { \ GetCipherInit((obj), (ctx)); \ if (!(ctx)) { \ ossl_raise(rb_eRuntimeError, "Cipher not inititalized!"); \ } \ } while (0) #define SafeGetCipher(obj, ctx) do { \ OSSL_Check_Kind((obj), cCipher); \ GetCipher((obj), (ctx)); \ } while (0) /* * Classes */ VALUE cCipher; VALUE eCipherError; static ID id_auth_tag_len; static VALUE ossl_cipher_alloc(VALUE klass); static void ossl_cipher_free(void *ptr); static const rb_data_type_t ossl_cipher_type = { "OpenSSL/Cipher", { 0, ossl_cipher_free, }, 0, 0, RUBY_TYPED_FREE_IMMEDIATELY, }; /* * PUBLIC */ const EVP_CIPHER * GetCipherPtr(VALUE obj) { if (rb_obj_is_kind_of(obj, cCipher)) { EVP_CIPHER_CTX *ctx; GetCipher(obj, ctx); return EVP_CIPHER_CTX_cipher(ctx); } else { const EVP_CIPHER *cipher; StringValueCStr(obj); cipher = EVP_get_cipherbyname(RSTRING_PTR(obj)); if (!cipher) ossl_raise(rb_eArgError, "unsupported cipher algorithm: %"PRIsVALUE, obj); return cipher; } } VALUE ossl_cipher_new(const EVP_CIPHER *cipher) { VALUE ret; EVP_CIPHER_CTX *ctx; ret = ossl_cipher_alloc(cCipher); AllocCipher(ret, ctx); if (EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, -1) != 1) ossl_raise(eCipherError, NULL); return ret; } /* * PRIVATE */ static void ossl_cipher_free(void *ptr) { EVP_CIPHER_CTX_free(ptr); } static VALUE ossl_cipher_alloc(VALUE klass) { return NewCipher(klass); } /* * call-seq: * Cipher.new(string) -> cipher * * The string must contain a valid cipher name like "AES-128-CBC" or "3DES". * * A list of cipher names is available by calling OpenSSL::Cipher.ciphers. */ static VALUE ossl_cipher_initialize(VALUE self, VALUE str) { EVP_CIPHER_CTX *ctx; const EVP_CIPHER *cipher; char *name; unsigned char dummy_key[EVP_MAX_KEY_LENGTH] = { 0 }; name = StringValueCStr(str); GetCipherInit(self, ctx); if (ctx) { ossl_raise(rb_eRuntimeError, "Cipher already inititalized!"); } AllocCipher(self, ctx); if (!(cipher = EVP_get_cipherbyname(name))) { ossl_raise(rb_eRuntimeError, "unsupported cipher algorithm (%"PRIsVALUE")", str); } /* * EVP_CipherInit_ex() allows to specify NULL to key and IV, however some * ciphers don't handle well (OpenSSL's bug). [Bug #2768] * * The EVP which has EVP_CIPH_RAND_KEY flag (such as DES3) allows * uninitialized key, but other EVPs (such as AES) does not allow it. * Calling EVP_CipherUpdate() without initializing key causes SEGV so we * set the data filled with "\0" as the key by default. */ if (EVP_CipherInit_ex(ctx, cipher, NULL, dummy_key, NULL, -1) != 1) ossl_raise(eCipherError, NULL); return self; } static VALUE ossl_cipher_copy(VALUE self, VALUE other) { EVP_CIPHER_CTX *ctx1, *ctx2; rb_check_frozen(self); if (self == other) return self; GetCipherInit(self, ctx1); if (!ctx1) { AllocCipher(self, ctx1); } SafeGetCipher(other, ctx2); if (EVP_CIPHER_CTX_copy(ctx1, ctx2) != 1) ossl_raise(eCipherError, NULL); return self; } static void* add_cipher_name_to_ary(const OBJ_NAME *name, VALUE ary) { rb_ary_push(ary, rb_str_new2(name->name)); return NULL; } /* * call-seq: * OpenSSL::Cipher.ciphers -> array[string...] * * Returns the names of all available ciphers in an array. */ static VALUE ossl_s_ciphers(VALUE self) { VALUE ary; ary = rb_ary_new(); OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, (void(*)(const OBJ_NAME*,void*))add_cipher_name_to_ary, (void*)ary); return ary; } /* * call-seq: * cipher.reset -> self * * Fully resets the internal state of the Cipher. By using this, the same * Cipher instance may be used several times for encryption or decryption tasks. * * Internally calls EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, -1). */ static VALUE ossl_cipher_reset(VALUE self) { EVP_CIPHER_CTX *ctx; GetCipher(self, ctx); if (EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, -1) != 1) ossl_raise(eCipherError, NULL); return self; } static VALUE ossl_cipher_init(int argc, VALUE *argv, VALUE self, int mode) { EVP_CIPHER_CTX *ctx; unsigned char key[EVP_MAX_KEY_LENGTH], *p_key = NULL; unsigned char iv[EVP_MAX_IV_LENGTH], *p_iv = NULL; VALUE pass, init_v; if(rb_scan_args(argc, argv, "02", &pass, &init_v) > 0){ /* * oops. this code mistakes salt for IV. * We deprecated the arguments for this method, but we decided * keeping this behaviour for backward compatibility. */ VALUE cname = rb_class_path(rb_obj_class(self)); rb_warn("arguments for %"PRIsVALUE"#encrypt and %"PRIsVALUE"#decrypt were deprecated; " "use %"PRIsVALUE"#pkcs5_keyivgen to derive key and IV", cname, cname, cname); StringValue(pass); GetCipher(self, ctx); if (NIL_P(init_v)) memcpy(iv, "OpenSSL for Ruby rulez!", sizeof(iv)); else{ StringValue(init_v); if (EVP_MAX_IV_LENGTH > RSTRING_LEN(init_v)) { memset(iv, 0, EVP_MAX_IV_LENGTH); memcpy(iv, RSTRING_PTR(init_v), RSTRING_LEN(init_v)); } else memcpy(iv, RSTRING_PTR(init_v), sizeof(iv)); } EVP_BytesToKey(EVP_CIPHER_CTX_cipher(ctx), EVP_md5(), iv, (unsigned char *)RSTRING_PTR(pass), RSTRING_LENINT(pass), 1, key, NULL); p_key = key; p_iv = iv; } else { GetCipher(self, ctx); } if (EVP_CipherInit_ex(ctx, NULL, NULL, p_key, p_iv, mode) != 1) { ossl_raise(eCipherError, NULL); } return self; } /* * call-seq: * cipher.encrypt -> self * * Initializes the Cipher for encryption. * * Make sure to call Cipher#encrypt or Cipher#decrypt before using any of the * following methods: * * [#key=, #iv=, #random_key, #random_iv, #pkcs5_keyivgen] * * Internally calls EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, 1). */ static VALUE ossl_cipher_encrypt(int argc, VALUE *argv, VALUE self) { return ossl_cipher_init(argc, argv, self, 1); } /* * call-seq: * cipher.decrypt -> self * * Initializes the Cipher for decryption. * * Make sure to call Cipher#encrypt or Cipher#decrypt before using any of the * following methods: * * [#key=, #iv=, #random_key, #random_iv, #pkcs5_keyivgen] * * Internally calls EVP_CipherInit_ex(ctx, NULL, NULL, NULL, NULL, 0). */ static VALUE ossl_cipher_decrypt(int argc, VALUE *argv, VALUE self) { return ossl_cipher_init(argc, argv, self, 0); } /* * call-seq: * cipher.pkcs5_keyivgen(pass, salt = nil, iterations = 2048, digest = "MD5") -> nil * * Generates and sets the key/IV based on a password. * * *WARNING*: This method is only PKCS5 v1.5 compliant when using RC2, RC4-40, * or DES with MD5 or SHA1. Using anything else (like AES) will generate the * key/iv using an OpenSSL specific method. This method is deprecated and * should no longer be used. Use a PKCS5 v2 key generation method from * OpenSSL::PKCS5 instead. * * === Parameters * * +salt+ must be an 8 byte string if provided. * * +iterations+ is a integer with a default of 2048. * * +digest+ is a Digest object that defaults to 'MD5' * * A minimum of 1000 iterations is recommended. * */ static VALUE ossl_cipher_pkcs5_keyivgen(int argc, VALUE *argv, VALUE self) { EVP_CIPHER_CTX *ctx; const EVP_MD *digest; VALUE vpass, vsalt, viter, vdigest; unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH], *salt = NULL; int iter; rb_scan_args(argc, argv, "13", &vpass, &vsalt, &viter, &vdigest); StringValue(vpass); if(!NIL_P(vsalt)){ StringValue(vsalt); if(RSTRING_LEN(vsalt) != PKCS5_SALT_LEN) ossl_raise(eCipherError, "salt must be an 8-octet string"); salt = (unsigned char *)RSTRING_PTR(vsalt); } iter = NIL_P(viter) ? 2048 : NUM2INT(viter); digest = NIL_P(vdigest) ? EVP_md5() : GetDigestPtr(vdigest); GetCipher(self, ctx); EVP_BytesToKey(EVP_CIPHER_CTX_cipher(ctx), digest, salt, (unsigned char *)RSTRING_PTR(vpass), RSTRING_LENINT(vpass), iter, key, iv); if (EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, -1) != 1) ossl_raise(eCipherError, NULL); OPENSSL_cleanse(key, sizeof key); OPENSSL_cleanse(iv, sizeof iv); return Qnil; } static int ossl_cipher_update_long(EVP_CIPHER_CTX *ctx, unsigned char *out, long *out_len_ptr, const unsigned char *in, long in_len) { int out_part_len; int limit = INT_MAX / 2 + 1; long out_len = 0; do { int in_part_len = in_len > limit ? limit : (int)in_len; if (!EVP_CipherUpdate(ctx, out ? (out + out_len) : 0, &out_part_len, in, in_part_len)) return 0; out_len += out_part_len; in += in_part_len; } while ((in_len -= limit) > 0); if (out_len_ptr) *out_len_ptr = out_len; return 1; } /* * call-seq: * cipher.update(data [, buffer]) -> string or buffer * * Encrypts data in a streaming fashion. Hand consecutive blocks of data * to the +update+ method in order to encrypt it. Returns the encrypted * data chunk. When done, the output of Cipher#final should be additionally * added to the result. * * If +buffer+ is given, the encryption/decryption result will be written to * it. +buffer+ will be resized automatically. */ static VALUE ossl_cipher_update(int argc, VALUE *argv, VALUE self) { EVP_CIPHER_CTX *ctx; unsigned char *in; long in_len, out_len; VALUE data, str; rb_scan_args(argc, argv, "11", &data, &str); StringValue(data); in = (unsigned char *)RSTRING_PTR(data); if ((in_len = RSTRING_LEN(data)) == 0) ossl_raise(rb_eArgError, "data must not be empty"); GetCipher(self, ctx); out_len = in_len+EVP_CIPHER_CTX_block_size(ctx); if (out_len <= 0) { ossl_raise(rb_eRangeError, "data too big to make output buffer: %ld bytes", in_len); } if (NIL_P(str)) { str = rb_str_new(0, out_len); } else { StringValue(str); rb_str_resize(str, out_len); } if (!ossl_cipher_update_long(ctx, (unsigned char *)RSTRING_PTR(str), &out_len, in, in_len)) ossl_raise(eCipherError, NULL); assert(out_len < RSTRING_LEN(str)); rb_str_set_len(str, out_len); return str; } /* * call-seq: * cipher.final -> string * * Returns the remaining data held in the cipher object. Further calls to * Cipher#update or Cipher#final will return garbage. This call should always * be made as the last call of an encryption or decryption operation, after * after having fed the entire plaintext or ciphertext to the Cipher instance. * * If an authenticated cipher was used, a CipherError is raised if the tag * could not be authenticated successfully. Only call this method after * setting the authentication tag and passing the entire contents of the * ciphertext into the cipher. */ static VALUE ossl_cipher_final(VALUE self) { EVP_CIPHER_CTX *ctx; int out_len; VALUE str; GetCipher(self, ctx); str = rb_str_new(0, EVP_CIPHER_CTX_block_size(ctx)); if (!EVP_CipherFinal_ex(ctx, (unsigned char *)RSTRING_PTR(str), &out_len)) ossl_raise(eCipherError, NULL); assert(out_len <= RSTRING_LEN(str)); rb_str_set_len(str, out_len); return str; } /* * call-seq: * cipher.name -> string * * Returns the name of the cipher which may differ slightly from the original * name provided. */ static VALUE ossl_cipher_name(VALUE self) { EVP_CIPHER_CTX *ctx; GetCipher(self, ctx); return rb_str_new2(EVP_CIPHER_name(EVP_CIPHER_CTX_cipher(ctx))); } /* * call-seq: * cipher.key = string -> string * * Sets the cipher key. To generate a key, you should either use a secure * random byte string or, if the key is to be derived from a password, you * should rely on PBKDF2 functionality provided by OpenSSL::PKCS5. To * generate a secure random-based key, Cipher#random_key may be used. * * Only call this method after calling Cipher#encrypt or Cipher#decrypt. */ static VALUE ossl_cipher_set_key(VALUE self, VALUE key) { EVP_CIPHER_CTX *ctx; int key_len; StringValue(key); GetCipher(self, ctx); key_len = EVP_CIPHER_CTX_key_length(ctx); if (RSTRING_LEN(key) != key_len) ossl_raise(rb_eArgError, "key must be %d bytes", key_len); if (EVP_CipherInit_ex(ctx, NULL, NULL, (unsigned char *)RSTRING_PTR(key), NULL, -1) != 1) ossl_raise(eCipherError, NULL); return key; } /* * call-seq: * cipher.iv = string -> string * * Sets the cipher IV. Please note that since you should never be using ECB * mode, an IV is always explicitly required and should be set prior to * encryption. The IV itself can be safely transmitted in public, but it * should be unpredictable to prevent certain kinds of attacks. You may use * Cipher#random_iv to create a secure random IV. * * Only call this method after calling Cipher#encrypt or Cipher#decrypt. * * If not explicitly set, the OpenSSL default of an all-zeroes ("\\0") IV is * used. */ static VALUE ossl_cipher_set_iv(VALUE self, VALUE iv) { EVP_CIPHER_CTX *ctx; int iv_len = 0; StringValue(iv); GetCipher(self, ctx); #if defined(HAVE_AUTHENTICATED_ENCRYPTION) if (EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_FLAG_AEAD_CIPHER) iv_len = (int)(VALUE)EVP_CIPHER_CTX_get_app_data(ctx); #endif if (!iv_len) iv_len = EVP_CIPHER_CTX_iv_length(ctx); if (RSTRING_LEN(iv) != iv_len) ossl_raise(rb_eArgError, "iv must be %d bytes", iv_len); if (EVP_CipherInit_ex(ctx, NULL, NULL, NULL, (unsigned char *)RSTRING_PTR(iv), -1) != 1) ossl_raise(eCipherError, NULL); return iv; } #ifdef HAVE_AUTHENTICATED_ENCRYPTION /* * call-seq: * cipher.auth_data = string -> string * * Sets the cipher's additional authenticated data. This field must be * set when using AEAD cipher modes such as GCM or CCM. If no associated * data shall be used, this method must *still* be called with a value of "". * The contents of this field should be non-sensitive data which will be * added to the ciphertext to generate the authentication tag which validates * the contents of the ciphertext. * * The AAD must be set prior to encryption or decryption. In encryption mode, * it must be set after calling Cipher#encrypt and setting Cipher#key= and * Cipher#iv=. When decrypting, the authenticated data must be set after key, * iv and especially *after* the authentication tag has been set. I.e. set it * only after calling Cipher#decrypt, Cipher#key=, Cipher#iv= and * Cipher#auth_tag= first. */ static VALUE ossl_cipher_set_auth_data(VALUE self, VALUE data) { EVP_CIPHER_CTX *ctx; unsigned char *in; long in_len, out_len; StringValue(data); in = (unsigned char *) RSTRING_PTR(data); in_len = RSTRING_LEN(data); GetCipher(self, ctx); if (!ossl_cipher_update_long(ctx, NULL, &out_len, in, in_len)) ossl_raise(eCipherError, "couldn't set additional authenticated data"); return data; } /* * call-seq: * cipher.auth_tag(tag_len = 16) -> String * * Gets the authentication tag generated by Authenticated Encryption Cipher * modes (GCM for example). This tag may be stored along with the ciphertext, * then set on the decryption cipher to authenticate the contents of the * ciphertext against changes. If the optional integer parameter +tag_len+ is * given, the returned tag will be +tag_len+ bytes long. If the parameter is * omitted, the default length of 16 bytes or the length previously set by * #auth_tag_len= will be used. For maximum security, the longest possible * should be chosen. * * The tag may only be retrieved after calling Cipher#final. */ static VALUE ossl_cipher_get_auth_tag(int argc, VALUE *argv, VALUE self) { VALUE vtag_len, ret; EVP_CIPHER_CTX *ctx; int tag_len = 16; rb_scan_args(argc, argv, "01", &vtag_len); if (NIL_P(vtag_len)) vtag_len = rb_attr_get(self, id_auth_tag_len); if (!NIL_P(vtag_len)) tag_len = NUM2INT(vtag_len); GetCipher(self, ctx); if (!(EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_FLAG_AEAD_CIPHER)) ossl_raise(eCipherError, "authentication tag not supported by this cipher"); ret = rb_str_new(NULL, tag_len); if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, tag_len, RSTRING_PTR(ret))) ossl_raise(eCipherError, "retrieving the authentication tag failed"); return ret; } /* * call-seq: * cipher.auth_tag = string -> string * * Sets the authentication tag to verify the contents of the * ciphertext. The tag must be set after calling Cipher#decrypt, * Cipher#key= and Cipher#iv=, but before assigning the associated * authenticated data using Cipher#auth_data= and of course, before * decrypting any of the ciphertext. After all decryption is * performed, the tag is verified automatically in the call to * Cipher#final. * * For OCB mode, the tag length must be supplied with #auth_tag_len= * beforehand. */ static VALUE ossl_cipher_set_auth_tag(VALUE self, VALUE vtag) { EVP_CIPHER_CTX *ctx; unsigned char *tag; int tag_len; StringValue(vtag); tag = (unsigned char *) RSTRING_PTR(vtag); tag_len = RSTRING_LENINT(vtag); GetCipher(self, ctx); if (!(EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_FLAG_AEAD_CIPHER)) ossl_raise(eCipherError, "authentication tag not supported by this cipher"); if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, tag_len, tag)) ossl_raise(eCipherError, "unable to set AEAD tag"); return vtag; } /* * call-seq: * cipher.auth_tag_len = Integer -> Integer * * Sets the length of the authentication tag to be generated or to be given for * AEAD ciphers that requires it as in input parameter. Note that not all AEAD * ciphers support this method. * * In OCB mode, the length must be supplied both when encrypting and when * decrypting, and must be before specifying an IV. */ static VALUE ossl_cipher_set_auth_tag_len(VALUE self, VALUE vlen) { int tag_len = NUM2INT(vlen); EVP_CIPHER_CTX *ctx; GetCipher(self, ctx); if (!(EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_FLAG_AEAD_CIPHER)) ossl_raise(eCipherError, "AEAD not supported by this cipher"); if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, tag_len, NULL)) ossl_raise(eCipherError, "unable to set authentication tag length"); /* for #auth_tag */ rb_ivar_set(self, id_auth_tag_len, INT2NUM(tag_len)); return vlen; } /* * call-seq: * cipher.authenticated? -> boolean * * Indicated whether this Cipher instance uses an Authenticated Encryption * mode. */ static VALUE ossl_cipher_is_authenticated(VALUE self) { EVP_CIPHER_CTX *ctx; GetCipher(self, ctx); return (EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_FLAG_AEAD_CIPHER) ? Qtrue : Qfalse; } /* * call-seq: * cipher.iv_len = integer -> integer * * Sets the IV/nonce length of the Cipher. Normally block ciphers don't allow * changing the IV length, but some make use of IV for 'nonce'. You may need * this for interoperability with other applications. */ static VALUE ossl_cipher_set_iv_length(VALUE self, VALUE iv_length) { int len = NUM2INT(iv_length); EVP_CIPHER_CTX *ctx; GetCipher(self, ctx); if (!(EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_FLAG_AEAD_CIPHER)) ossl_raise(eCipherError, "cipher does not support AEAD"); if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, len, NULL)) ossl_raise(eCipherError, "unable to set IV length"); /* * EVP_CIPHER_CTX_iv_length() returns the default length. So we need to save * the length somewhere. Luckily currently we aren't using app_data. */ EVP_CIPHER_CTX_set_app_data(ctx, (void *)(VALUE)len); return iv_length; } #else #define ossl_cipher_set_auth_data rb_f_notimplement #define ossl_cipher_get_auth_tag rb_f_notimplement #define ossl_cipher_set_auth_tag rb_f_notimplement #define ossl_cipher_set_auth_tag_len rb_f_notimplement #define ossl_cipher_is_authenticated rb_f_notimplement #define ossl_cipher_set_iv_length rb_f_notimplement #endif /* * call-seq: * cipher.key_len = integer -> integer * * Sets the key length of the cipher. If the cipher is a fixed length cipher * then attempting to set the key length to any value other than the fixed * value is an error. * * Under normal circumstances you do not need to call this method (and probably shouldn't). * * See EVP_CIPHER_CTX_set_key_length for further information. */ static VALUE ossl_cipher_set_key_length(VALUE self, VALUE key_length) { int len = NUM2INT(key_length); EVP_CIPHER_CTX *ctx; GetCipher(self, ctx); if (EVP_CIPHER_CTX_set_key_length(ctx, len) != 1) ossl_raise(eCipherError, NULL); return key_length; } /* * call-seq: * cipher.padding = integer -> integer * * Enables or disables padding. By default encryption operations are padded using standard block padding and the * padding is checked and removed when decrypting. If the pad parameter is zero then no padding is performed, the * total amount of data encrypted or decrypted must then be a multiple of the block size or an error will occur. * * See EVP_CIPHER_CTX_set_padding for further information. */ static VALUE ossl_cipher_set_padding(VALUE self, VALUE padding) { EVP_CIPHER_CTX *ctx; int pad = NUM2INT(padding); GetCipher(self, ctx); if (EVP_CIPHER_CTX_set_padding(ctx, pad) != 1) ossl_raise(eCipherError, NULL); return padding; } /* * call-seq: * cipher.key_len -> integer * * Returns the key length in bytes of the Cipher. */ static VALUE ossl_cipher_key_length(VALUE self) { EVP_CIPHER_CTX *ctx; GetCipher(self, ctx); return INT2NUM(EVP_CIPHER_CTX_key_length(ctx)); } /* * call-seq: * cipher.iv_len -> integer * * Returns the expected length in bytes for an IV for this Cipher. */ static VALUE ossl_cipher_iv_length(VALUE self) { EVP_CIPHER_CTX *ctx; int len = 0; GetCipher(self, ctx); #if defined(HAVE_AUTHENTICATED_ENCRYPTION) if (EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_FLAG_AEAD_CIPHER) len = (int)(VALUE)EVP_CIPHER_CTX_get_app_data(ctx); #endif if (!len) len = EVP_CIPHER_CTX_iv_length(ctx); return INT2NUM(len); } /* * call-seq: * cipher.block_size -> integer * * Returns the size in bytes of the blocks on which this Cipher operates on. */ static VALUE ossl_cipher_block_size(VALUE self) { EVP_CIPHER_CTX *ctx; GetCipher(self, ctx); return INT2NUM(EVP_CIPHER_CTX_block_size(ctx)); } /* * INIT */ void Init_ossl_cipher(void) { #if 0 mOSSL = rb_define_module("OpenSSL"); eOSSLError = rb_define_class_under(mOSSL, "OpenSSLError", rb_eStandardError); #endif /* Document-class: OpenSSL::Cipher * * Provides symmetric algorithms for encryption and decryption. The * algorithms that are available depend on the particular version * of OpenSSL that is installed. * * === Listing all supported algorithms * * A list of supported algorithms can be obtained by * * puts OpenSSL::Cipher.ciphers * * === Instantiating a Cipher * * There are several ways to create a Cipher instance. Generally, a * Cipher algorithm is categorized by its name, the key length in bits * and the cipher mode to be used. The most generic way to create a * Cipher is the following * * cipher = OpenSSL::Cipher.new('<name>-<key length>-<mode>') * * That is, a string consisting of the hyphenated concatenation of the * individual components name, key length and mode. Either all uppercase * or all lowercase strings may be used, for example: * * cipher = OpenSSL::Cipher.new('AES-128-CBC') * * For each algorithm supported, there is a class defined under the * Cipher class that goes by the name of the cipher, e.g. to obtain an * instance of AES, you could also use * * # these are equivalent * cipher = OpenSSL::Cipher::AES.new(128, :CBC) * cipher = OpenSSL::Cipher::AES.new(128, 'CBC') * cipher = OpenSSL::Cipher::AES.new('128-CBC') * * Finally, due to its wide-spread use, there are also extra classes * defined for the different key sizes of AES * * cipher = OpenSSL::Cipher::AES128.new(:CBC) * cipher = OpenSSL::Cipher::AES192.new(:CBC) * cipher = OpenSSL::Cipher::AES256.new(:CBC) * * === Choosing either encryption or decryption mode * * Encryption and decryption are often very similar operations for * symmetric algorithms, this is reflected by not having to choose * different classes for either operation, both can be done using the * same class. Still, after obtaining a Cipher instance, we need to * tell the instance what it is that we intend to do with it, so we * need to call either * * cipher.encrypt * * or * * cipher.decrypt * * on the Cipher instance. This should be the first call after creating * the instance, otherwise configuration that has already been set could * get lost in the process. * * === Choosing a key * * Symmetric encryption requires a key that is the same for the encrypting * and for the decrypting party and after initial key establishment should * be kept as private information. There are a lot of ways to create * insecure keys, the most notable is to simply take a password as the key * without processing the password further. A simple and secure way to * create a key for a particular Cipher is * * cipher = OpenSSL::AES256.new(:CFB) * cipher.encrypt * key = cipher.random_key # also sets the generated key on the Cipher * * If you absolutely need to use passwords as encryption keys, you * should use Password-Based Key Derivation Function 2 (PBKDF2) by * generating the key with the help of the functionality provided by * OpenSSL::PKCS5.pbkdf2_hmac_sha1 or OpenSSL::PKCS5.pbkdf2_hmac. * * Although there is Cipher#pkcs5_keyivgen, its use is deprecated and * it should only be used in legacy applications because it does not use * the newer PKCS#5 v2 algorithms. * * === Choosing an IV * * The cipher modes CBC, CFB, OFB and CTR all need an "initialization * vector", or short, IV. ECB mode is the only mode that does not require * an IV, but there is almost no legitimate use case for this mode * because of the fact that it does not sufficiently hide plaintext * patterns. Therefore * * <b>You should never use ECB mode unless you are absolutely sure that * you absolutely need it</b> * * Because of this, you will end up with a mode that explicitly requires * an IV in any case. Note that for backwards compatibility reasons, * setting an IV is not explicitly mandated by the Cipher API. If not * set, OpenSSL itself defaults to an all-zeroes IV ("\\0", not the * character). Although the IV can be seen as public information, i.e. * it may be transmitted in public once generated, it should still stay * unpredictable to prevent certain kinds of attacks. Therefore, ideally * * <b>Always create a secure random IV for every encryption of your * Cipher</b> * * A new, random IV should be created for every encryption of data. Think * of the IV as a nonce (number used once) - it's public but random and * unpredictable. A secure random IV can be created as follows * * cipher = ... * cipher.encrypt * key = cipher.random_key * iv = cipher.random_iv # also sets the generated IV on the Cipher * * Although the key is generally a random value, too, it is a bad choice * as an IV. There are elaborate ways how an attacker can take advantage * of such an IV. As a general rule of thumb, exposing the key directly * or indirectly should be avoided at all cost and exceptions only be * made with good reason. * * === Calling Cipher#final * * ECB (which should not be used) and CBC are both block-based modes. * This means that unlike for the other streaming-based modes, they * operate on fixed-size blocks of data, and therefore they require a * "finalization" step to produce or correctly decrypt the last block of * data by appropriately handling some form of padding. Therefore it is * essential to add the output of OpenSSL::Cipher#final to your * encryption/decryption buffer or you will end up with decryption errors * or truncated data. * * Although this is not really necessary for streaming-mode ciphers, it is * still recommended to apply the same pattern of adding the output of * Cipher#final there as well - it also enables you to switch between * modes more easily in the future. * * === Encrypting and decrypting some data * * data = "Very, very confidential data" * * cipher = OpenSSL::Cipher::AES.new(128, :CBC) * cipher.encrypt * key = cipher.random_key * iv = cipher.random_iv * * encrypted = cipher.update(data) + cipher.final * ... * decipher = OpenSSL::Cipher::AES.new(128, :CBC) * decipher.decrypt * decipher.key = key * decipher.iv = iv * * plain = decipher.update(encrypted) + decipher.final * * puts data == plain #=> true * * === Authenticated Encryption and Associated Data (AEAD) * * If the OpenSSL version used supports it, an Authenticated Encryption * mode (such as GCM or CCM) should always be preferred over any * unauthenticated mode. Currently, OpenSSL supports AE only in combination * with Associated Data (AEAD) where additional associated data is included * in the encryption process to compute a tag at the end of the encryption. * This tag will also be used in the decryption process and by verifying * its validity, the authenticity of a given ciphertext is established. * * This is superior to unauthenticated modes in that it allows to detect * if somebody effectively changed the ciphertext after it had been * encrypted. This prevents malicious modifications of the ciphertext that * could otherwise be exploited to modify ciphertexts in ways beneficial to * potential attackers. * * An associated data is used where there is additional information, such as * headers or some metadata, that must be also authenticated but not * necessarily need to be encrypted. If no associated data is needed for * encryption and later decryption, the OpenSSL library still requires a * value to be set - "" may be used in case none is available. * * An example using the GCM (Galois/Counter Mode). You have 16 bytes +key+, * 12 bytes (96 bits) +nonce+ and the associated data +auth_data+. Be sure * not to reuse the +key+ and +nonce+ pair. Reusing an nonce ruins the * security gurantees of GCM mode. * * cipher = OpenSSL::Cipher::AES.new(128, :GCM).encrypt * cipher.key = key * cipher.iv = nonce * cipher.auth_data = auth_data * * encrypted = cipher.update(data) + cipher.final * tag = cipher.auth_tag # produces 16 bytes tag by default * * Now you are the receiver. You know the +key+ and have received +nonce+, * +auth_data+, +encrypted+ and +tag+ through an untrusted network. Note * that GCM accepts an arbitrary length tag between 1 and 16 bytes. You may * additionally need to check that the received tag has the correct length, * or you allow attackers to forge a valid single byte tag for the tampered * ciphertext with a probability of 1/256. * * raise "tag is truncated!" unless tag.bytesize == 16 * decipher = OpenSSL::Cipher::AES.new(128, :GCM).decrypt * decipher.key = key * decipher.iv = nonce * decipher.auth_tag = tag * decipher.auth_data = auth_data * * decrypted = decipher.update(encrypted) + decipher.final * * puts data == decrypted #=> true */ cCipher = rb_define_class_under(mOSSL, "Cipher", rb_cObject); eCipherError = rb_define_class_under(cCipher, "CipherError", eOSSLError); rb_define_alloc_func(cCipher, ossl_cipher_alloc); rb_define_copy_func(cCipher, ossl_cipher_copy); rb_define_module_function(cCipher, "ciphers", ossl_s_ciphers, 0); rb_define_method(cCipher, "initialize", ossl_cipher_initialize, 1); rb_define_method(cCipher, "reset", ossl_cipher_reset, 0); rb_define_method(cCipher, "encrypt", ossl_cipher_encrypt, -1); rb_define_method(cCipher, "decrypt", ossl_cipher_decrypt, -1); rb_define_method(cCipher, "pkcs5_keyivgen", ossl_cipher_pkcs5_keyivgen, -1); rb_define_method(cCipher, "update", ossl_cipher_update, -1); rb_define_method(cCipher, "final", ossl_cipher_final, 0); rb_define_method(cCipher, "name", ossl_cipher_name, 0); rb_define_method(cCipher, "key=", ossl_cipher_set_key, 1); rb_define_method(cCipher, "auth_data=", ossl_cipher_set_auth_data, 1); rb_define_method(cCipher, "auth_tag=", ossl_cipher_set_auth_tag, 1); rb_define_method(cCipher, "auth_tag", ossl_cipher_get_auth_tag, -1); rb_define_method(cCipher, "auth_tag_len=", ossl_cipher_set_auth_tag_len, 1); rb_define_method(cCipher, "authenticated?", ossl_cipher_is_authenticated, 0); rb_define_method(cCipher, "key_len=", ossl_cipher_set_key_length, 1); rb_define_method(cCipher, "key_len", ossl_cipher_key_length, 0); rb_define_method(cCipher, "iv=", ossl_cipher_set_iv, 1); rb_define_method(cCipher, "iv_len=", ossl_cipher_set_iv_length, 1); rb_define_method(cCipher, "iv_len", ossl_cipher_iv_length, 0); rb_define_method(cCipher, "block_size", ossl_cipher_block_size, 0); rb_define_method(cCipher, "padding=", ossl_cipher_set_padding, 1); id_auth_tag_len = rb_intern_const("auth_tag_len"); }
./CrossVul/dataset_final_sorted/CWE-310/c/bad_5329_0
crossvul-cpp_data_bad_5666_3
/* * Block chaining cipher operations. * * Generic encrypt/decrypt wrapper for ciphers, handles operations across * multiple page boundaries by using temporary blocks. In user context, * the kernel is given a chance to schedule us once per page. * * Copyright (c) 2006 Herbert Xu <herbert@gondor.apana.org.au> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include <crypto/internal/skcipher.h> #include <crypto/scatterwalk.h> #include <linux/errno.h> #include <linux/hardirq.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/scatterlist.h> #include <linux/seq_file.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/cryptouser.h> #include <net/netlink.h> #include "internal.h" enum { BLKCIPHER_WALK_PHYS = 1 << 0, BLKCIPHER_WALK_SLOW = 1 << 1, BLKCIPHER_WALK_COPY = 1 << 2, BLKCIPHER_WALK_DIFF = 1 << 3, }; static int blkcipher_walk_next(struct blkcipher_desc *desc, struct blkcipher_walk *walk); static int blkcipher_walk_first(struct blkcipher_desc *desc, struct blkcipher_walk *walk); static inline void blkcipher_map_src(struct blkcipher_walk *walk) { walk->src.virt.addr = scatterwalk_map(&walk->in); } static inline void blkcipher_map_dst(struct blkcipher_walk *walk) { walk->dst.virt.addr = scatterwalk_map(&walk->out); } static inline void blkcipher_unmap_src(struct blkcipher_walk *walk) { scatterwalk_unmap(walk->src.virt.addr); } static inline void blkcipher_unmap_dst(struct blkcipher_walk *walk) { scatterwalk_unmap(walk->dst.virt.addr); } /* Get a spot of the specified length that does not straddle a page. * The caller needs to ensure that there is enough space for this operation. */ static inline u8 *blkcipher_get_spot(u8 *start, unsigned int len) { u8 *end_page = (u8 *)(((unsigned long)(start + len - 1)) & PAGE_MASK); return max(start, end_page); } static inline unsigned int blkcipher_done_slow(struct crypto_blkcipher *tfm, struct blkcipher_walk *walk, unsigned int bsize) { u8 *addr; unsigned int alignmask = crypto_blkcipher_alignmask(tfm); addr = (u8 *)ALIGN((unsigned long)walk->buffer, alignmask + 1); addr = blkcipher_get_spot(addr, bsize); scatterwalk_copychunks(addr, &walk->out, bsize, 1); return bsize; } static inline unsigned int blkcipher_done_fast(struct blkcipher_walk *walk, unsigned int n) { if (walk->flags & BLKCIPHER_WALK_COPY) { blkcipher_map_dst(walk); memcpy(walk->dst.virt.addr, walk->page, n); blkcipher_unmap_dst(walk); } else if (!(walk->flags & BLKCIPHER_WALK_PHYS)) { if (walk->flags & BLKCIPHER_WALK_DIFF) blkcipher_unmap_dst(walk); blkcipher_unmap_src(walk); } scatterwalk_advance(&walk->in, n); scatterwalk_advance(&walk->out, n); return n; } int blkcipher_walk_done(struct blkcipher_desc *desc, struct blkcipher_walk *walk, int err) { struct crypto_blkcipher *tfm = desc->tfm; unsigned int nbytes = 0; if (likely(err >= 0)) { unsigned int n = walk->nbytes - err; if (likely(!(walk->flags & BLKCIPHER_WALK_SLOW))) n = blkcipher_done_fast(walk, n); else if (WARN_ON(err)) { err = -EINVAL; goto err; } else n = blkcipher_done_slow(tfm, walk, n); nbytes = walk->total - n; err = 0; } scatterwalk_done(&walk->in, 0, nbytes); scatterwalk_done(&walk->out, 1, nbytes); err: walk->total = nbytes; walk->nbytes = nbytes; if (nbytes) { crypto_yield(desc->flags); return blkcipher_walk_next(desc, walk); } if (walk->iv != desc->info) memcpy(desc->info, walk->iv, crypto_blkcipher_ivsize(tfm)); if (walk->buffer != walk->page) kfree(walk->buffer); if (walk->page) free_page((unsigned long)walk->page); return err; } EXPORT_SYMBOL_GPL(blkcipher_walk_done); static inline int blkcipher_next_slow(struct blkcipher_desc *desc, struct blkcipher_walk *walk, unsigned int bsize, unsigned int alignmask) { unsigned int n; unsigned aligned_bsize = ALIGN(bsize, alignmask + 1); if (walk->buffer) goto ok; walk->buffer = walk->page; if (walk->buffer) goto ok; n = aligned_bsize * 3 - (alignmask + 1) + (alignmask & ~(crypto_tfm_ctx_alignment() - 1)); walk->buffer = kmalloc(n, GFP_ATOMIC); if (!walk->buffer) return blkcipher_walk_done(desc, walk, -ENOMEM); ok: walk->dst.virt.addr = (u8 *)ALIGN((unsigned long)walk->buffer, alignmask + 1); walk->dst.virt.addr = blkcipher_get_spot(walk->dst.virt.addr, bsize); walk->src.virt.addr = blkcipher_get_spot(walk->dst.virt.addr + aligned_bsize, bsize); scatterwalk_copychunks(walk->src.virt.addr, &walk->in, bsize, 0); walk->nbytes = bsize; walk->flags |= BLKCIPHER_WALK_SLOW; return 0; } static inline int blkcipher_next_copy(struct blkcipher_walk *walk) { u8 *tmp = walk->page; blkcipher_map_src(walk); memcpy(tmp, walk->src.virt.addr, walk->nbytes); blkcipher_unmap_src(walk); walk->src.virt.addr = tmp; walk->dst.virt.addr = tmp; return 0; } static inline int blkcipher_next_fast(struct blkcipher_desc *desc, struct blkcipher_walk *walk) { unsigned long diff; walk->src.phys.page = scatterwalk_page(&walk->in); walk->src.phys.offset = offset_in_page(walk->in.offset); walk->dst.phys.page = scatterwalk_page(&walk->out); walk->dst.phys.offset = offset_in_page(walk->out.offset); if (walk->flags & BLKCIPHER_WALK_PHYS) return 0; diff = walk->src.phys.offset - walk->dst.phys.offset; diff |= walk->src.virt.page - walk->dst.virt.page; blkcipher_map_src(walk); walk->dst.virt.addr = walk->src.virt.addr; if (diff) { walk->flags |= BLKCIPHER_WALK_DIFF; blkcipher_map_dst(walk); } return 0; } static int blkcipher_walk_next(struct blkcipher_desc *desc, struct blkcipher_walk *walk) { struct crypto_blkcipher *tfm = desc->tfm; unsigned int alignmask = crypto_blkcipher_alignmask(tfm); unsigned int bsize; unsigned int n; int err; n = walk->total; if (unlikely(n < crypto_blkcipher_blocksize(tfm))) { desc->flags |= CRYPTO_TFM_RES_BAD_BLOCK_LEN; return blkcipher_walk_done(desc, walk, -EINVAL); } walk->flags &= ~(BLKCIPHER_WALK_SLOW | BLKCIPHER_WALK_COPY | BLKCIPHER_WALK_DIFF); if (!scatterwalk_aligned(&walk->in, alignmask) || !scatterwalk_aligned(&walk->out, alignmask)) { walk->flags |= BLKCIPHER_WALK_COPY; if (!walk->page) { walk->page = (void *)__get_free_page(GFP_ATOMIC); if (!walk->page) n = 0; } } bsize = min(walk->blocksize, n); n = scatterwalk_clamp(&walk->in, n); n = scatterwalk_clamp(&walk->out, n); if (unlikely(n < bsize)) { err = blkcipher_next_slow(desc, walk, bsize, alignmask); goto set_phys_lowmem; } walk->nbytes = n; if (walk->flags & BLKCIPHER_WALK_COPY) { err = blkcipher_next_copy(walk); goto set_phys_lowmem; } return blkcipher_next_fast(desc, walk); set_phys_lowmem: if (walk->flags & BLKCIPHER_WALK_PHYS) { walk->src.phys.page = virt_to_page(walk->src.virt.addr); walk->dst.phys.page = virt_to_page(walk->dst.virt.addr); walk->src.phys.offset &= PAGE_SIZE - 1; walk->dst.phys.offset &= PAGE_SIZE - 1; } return err; } static inline int blkcipher_copy_iv(struct blkcipher_walk *walk, struct crypto_blkcipher *tfm, unsigned int alignmask) { unsigned bs = walk->blocksize; unsigned int ivsize = crypto_blkcipher_ivsize(tfm); unsigned aligned_bs = ALIGN(bs, alignmask + 1); unsigned int size = aligned_bs * 2 + ivsize + max(aligned_bs, ivsize) - (alignmask + 1); u8 *iv; size += alignmask & ~(crypto_tfm_ctx_alignment() - 1); walk->buffer = kmalloc(size, GFP_ATOMIC); if (!walk->buffer) return -ENOMEM; iv = (u8 *)ALIGN((unsigned long)walk->buffer, alignmask + 1); iv = blkcipher_get_spot(iv, bs) + aligned_bs; iv = blkcipher_get_spot(iv, bs) + aligned_bs; iv = blkcipher_get_spot(iv, ivsize); walk->iv = memcpy(iv, walk->iv, ivsize); return 0; } int blkcipher_walk_virt(struct blkcipher_desc *desc, struct blkcipher_walk *walk) { walk->flags &= ~BLKCIPHER_WALK_PHYS; walk->blocksize = crypto_blkcipher_blocksize(desc->tfm); return blkcipher_walk_first(desc, walk); } EXPORT_SYMBOL_GPL(blkcipher_walk_virt); int blkcipher_walk_phys(struct blkcipher_desc *desc, struct blkcipher_walk *walk) { walk->flags |= BLKCIPHER_WALK_PHYS; walk->blocksize = crypto_blkcipher_blocksize(desc->tfm); return blkcipher_walk_first(desc, walk); } EXPORT_SYMBOL_GPL(blkcipher_walk_phys); static int blkcipher_walk_first(struct blkcipher_desc *desc, struct blkcipher_walk *walk) { struct crypto_blkcipher *tfm = desc->tfm; unsigned int alignmask = crypto_blkcipher_alignmask(tfm); if (WARN_ON_ONCE(in_irq())) return -EDEADLK; walk->nbytes = walk->total; if (unlikely(!walk->total)) return 0; walk->buffer = NULL; walk->iv = desc->info; if (unlikely(((unsigned long)walk->iv & alignmask))) { int err = blkcipher_copy_iv(walk, tfm, alignmask); if (err) return err; } scatterwalk_start(&walk->in, walk->in.sg); scatterwalk_start(&walk->out, walk->out.sg); walk->page = NULL; return blkcipher_walk_next(desc, walk); } int blkcipher_walk_virt_block(struct blkcipher_desc *desc, struct blkcipher_walk *walk, unsigned int blocksize) { walk->flags &= ~BLKCIPHER_WALK_PHYS; walk->blocksize = blocksize; return blkcipher_walk_first(desc, walk); } EXPORT_SYMBOL_GPL(blkcipher_walk_virt_block); static int setkey_unaligned(struct crypto_tfm *tfm, const u8 *key, unsigned int keylen) { struct blkcipher_alg *cipher = &tfm->__crt_alg->cra_blkcipher; unsigned long alignmask = crypto_tfm_alg_alignmask(tfm); int ret; u8 *buffer, *alignbuffer; unsigned long absize; absize = keylen + alignmask; buffer = kmalloc(absize, GFP_ATOMIC); if (!buffer) return -ENOMEM; alignbuffer = (u8 *)ALIGN((unsigned long)buffer, alignmask + 1); memcpy(alignbuffer, key, keylen); ret = cipher->setkey(tfm, alignbuffer, keylen); memset(alignbuffer, 0, keylen); kfree(buffer); return ret; } static int setkey(struct crypto_tfm *tfm, const u8 *key, unsigned int keylen) { struct blkcipher_alg *cipher = &tfm->__crt_alg->cra_blkcipher; unsigned long alignmask = crypto_tfm_alg_alignmask(tfm); if (keylen < cipher->min_keysize || keylen > cipher->max_keysize) { tfm->crt_flags |= CRYPTO_TFM_RES_BAD_KEY_LEN; return -EINVAL; } if ((unsigned long)key & alignmask) return setkey_unaligned(tfm, key, keylen); return cipher->setkey(tfm, key, keylen); } static int async_setkey(struct crypto_ablkcipher *tfm, const u8 *key, unsigned int keylen) { return setkey(crypto_ablkcipher_tfm(tfm), key, keylen); } static int async_encrypt(struct ablkcipher_request *req) { struct crypto_tfm *tfm = req->base.tfm; struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher; struct blkcipher_desc desc = { .tfm = __crypto_blkcipher_cast(tfm), .info = req->info, .flags = req->base.flags, }; return alg->encrypt(&desc, req->dst, req->src, req->nbytes); } static int async_decrypt(struct ablkcipher_request *req) { struct crypto_tfm *tfm = req->base.tfm; struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher; struct blkcipher_desc desc = { .tfm = __crypto_blkcipher_cast(tfm), .info = req->info, .flags = req->base.flags, }; return alg->decrypt(&desc, req->dst, req->src, req->nbytes); } static unsigned int crypto_blkcipher_ctxsize(struct crypto_alg *alg, u32 type, u32 mask) { struct blkcipher_alg *cipher = &alg->cra_blkcipher; unsigned int len = alg->cra_ctxsize; if ((mask & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_MASK && cipher->ivsize) { len = ALIGN(len, (unsigned long)alg->cra_alignmask + 1); len += cipher->ivsize; } return len; } static int crypto_init_blkcipher_ops_async(struct crypto_tfm *tfm) { struct ablkcipher_tfm *crt = &tfm->crt_ablkcipher; struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher; crt->setkey = async_setkey; crt->encrypt = async_encrypt; crt->decrypt = async_decrypt; if (!alg->ivsize) { crt->givencrypt = skcipher_null_givencrypt; crt->givdecrypt = skcipher_null_givdecrypt; } crt->base = __crypto_ablkcipher_cast(tfm); crt->ivsize = alg->ivsize; return 0; } static int crypto_init_blkcipher_ops_sync(struct crypto_tfm *tfm) { struct blkcipher_tfm *crt = &tfm->crt_blkcipher; struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher; unsigned long align = crypto_tfm_alg_alignmask(tfm) + 1; unsigned long addr; crt->setkey = setkey; crt->encrypt = alg->encrypt; crt->decrypt = alg->decrypt; addr = (unsigned long)crypto_tfm_ctx(tfm); addr = ALIGN(addr, align); addr += ALIGN(tfm->__crt_alg->cra_ctxsize, align); crt->iv = (void *)addr; return 0; } static int crypto_init_blkcipher_ops(struct crypto_tfm *tfm, u32 type, u32 mask) { struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher; if (alg->ivsize > PAGE_SIZE / 8) return -EINVAL; if ((mask & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_MASK) return crypto_init_blkcipher_ops_sync(tfm); else return crypto_init_blkcipher_ops_async(tfm); } #ifdef CONFIG_NET static int crypto_blkcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_blkcipher rblkcipher; snprintf(rblkcipher.type, CRYPTO_MAX_ALG_NAME, "%s", "blkcipher"); snprintf(rblkcipher.geniv, CRYPTO_MAX_ALG_NAME, "%s", alg->cra_blkcipher.geniv ?: "<default>"); rblkcipher.blocksize = alg->cra_blocksize; rblkcipher.min_keysize = alg->cra_blkcipher.min_keysize; rblkcipher.max_keysize = alg->cra_blkcipher.max_keysize; rblkcipher.ivsize = alg->cra_blkcipher.ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER, sizeof(struct crypto_report_blkcipher), &rblkcipher)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } #else static int crypto_blkcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { return -ENOSYS; } #endif static void crypto_blkcipher_show(struct seq_file *m, struct crypto_alg *alg) __attribute__ ((unused)); static void crypto_blkcipher_show(struct seq_file *m, struct crypto_alg *alg) { seq_printf(m, "type : blkcipher\n"); seq_printf(m, "blocksize : %u\n", alg->cra_blocksize); seq_printf(m, "min keysize : %u\n", alg->cra_blkcipher.min_keysize); seq_printf(m, "max keysize : %u\n", alg->cra_blkcipher.max_keysize); seq_printf(m, "ivsize : %u\n", alg->cra_blkcipher.ivsize); seq_printf(m, "geniv : %s\n", alg->cra_blkcipher.geniv ?: "<default>"); } const struct crypto_type crypto_blkcipher_type = { .ctxsize = crypto_blkcipher_ctxsize, .init = crypto_init_blkcipher_ops, #ifdef CONFIG_PROC_FS .show = crypto_blkcipher_show, #endif .report = crypto_blkcipher_report, }; EXPORT_SYMBOL_GPL(crypto_blkcipher_type); static int crypto_grab_nivcipher(struct crypto_skcipher_spawn *spawn, const char *name, u32 type, u32 mask) { struct crypto_alg *alg; int err; type = crypto_skcipher_type(type); mask = crypto_skcipher_mask(mask)| CRYPTO_ALG_GENIV; alg = crypto_alg_mod_lookup(name, type, mask); if (IS_ERR(alg)) return PTR_ERR(alg); err = crypto_init_spawn(&spawn->base, alg, spawn->base.inst, mask); crypto_mod_put(alg); return err; } struct crypto_instance *skcipher_geniv_alloc(struct crypto_template *tmpl, struct rtattr **tb, u32 type, u32 mask) { struct { int (*setkey)(struct crypto_ablkcipher *tfm, const u8 *key, unsigned int keylen); int (*encrypt)(struct ablkcipher_request *req); int (*decrypt)(struct ablkcipher_request *req); unsigned int min_keysize; unsigned int max_keysize; unsigned int ivsize; const char *geniv; } balg; const char *name; struct crypto_skcipher_spawn *spawn; struct crypto_attr_type *algt; struct crypto_instance *inst; struct crypto_alg *alg; int err; algt = crypto_get_attr_type(tb); if (IS_ERR(algt)) return ERR_CAST(algt); if ((algt->type ^ (CRYPTO_ALG_TYPE_GIVCIPHER | CRYPTO_ALG_GENIV)) & algt->mask) return ERR_PTR(-EINVAL); name = crypto_attr_alg_name(tb[1]); if (IS_ERR(name)) return ERR_CAST(name); inst = kzalloc(sizeof(*inst) + sizeof(*spawn), GFP_KERNEL); if (!inst) return ERR_PTR(-ENOMEM); spawn = crypto_instance_ctx(inst); /* Ignore async algorithms if necessary. */ mask |= crypto_requires_sync(algt->type, algt->mask); crypto_set_skcipher_spawn(spawn, inst); err = crypto_grab_nivcipher(spawn, name, type, mask); if (err) goto err_free_inst; alg = crypto_skcipher_spawn_alg(spawn); if ((alg->cra_flags & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_BLKCIPHER) { balg.ivsize = alg->cra_blkcipher.ivsize; balg.min_keysize = alg->cra_blkcipher.min_keysize; balg.max_keysize = alg->cra_blkcipher.max_keysize; balg.setkey = async_setkey; balg.encrypt = async_encrypt; balg.decrypt = async_decrypt; balg.geniv = alg->cra_blkcipher.geniv; } else { balg.ivsize = alg->cra_ablkcipher.ivsize; balg.min_keysize = alg->cra_ablkcipher.min_keysize; balg.max_keysize = alg->cra_ablkcipher.max_keysize; balg.setkey = alg->cra_ablkcipher.setkey; balg.encrypt = alg->cra_ablkcipher.encrypt; balg.decrypt = alg->cra_ablkcipher.decrypt; balg.geniv = alg->cra_ablkcipher.geniv; } err = -EINVAL; if (!balg.ivsize) goto err_drop_alg; /* * This is only true if we're constructing an algorithm with its * default IV generator. For the default generator we elide the * template name and double-check the IV generator. */ if (algt->mask & CRYPTO_ALG_GENIV) { if (!balg.geniv) balg.geniv = crypto_default_geniv(alg); err = -EAGAIN; if (strcmp(tmpl->name, balg.geniv)) goto err_drop_alg; memcpy(inst->alg.cra_name, alg->cra_name, CRYPTO_MAX_ALG_NAME); memcpy(inst->alg.cra_driver_name, alg->cra_driver_name, CRYPTO_MAX_ALG_NAME); } else { err = -ENAMETOOLONG; if (snprintf(inst->alg.cra_name, CRYPTO_MAX_ALG_NAME, "%s(%s)", tmpl->name, alg->cra_name) >= CRYPTO_MAX_ALG_NAME) goto err_drop_alg; if (snprintf(inst->alg.cra_driver_name, CRYPTO_MAX_ALG_NAME, "%s(%s)", tmpl->name, alg->cra_driver_name) >= CRYPTO_MAX_ALG_NAME) goto err_drop_alg; } inst->alg.cra_flags = CRYPTO_ALG_TYPE_GIVCIPHER | CRYPTO_ALG_GENIV; inst->alg.cra_flags |= alg->cra_flags & CRYPTO_ALG_ASYNC; inst->alg.cra_priority = alg->cra_priority; inst->alg.cra_blocksize = alg->cra_blocksize; inst->alg.cra_alignmask = alg->cra_alignmask; inst->alg.cra_type = &crypto_givcipher_type; inst->alg.cra_ablkcipher.ivsize = balg.ivsize; inst->alg.cra_ablkcipher.min_keysize = balg.min_keysize; inst->alg.cra_ablkcipher.max_keysize = balg.max_keysize; inst->alg.cra_ablkcipher.geniv = balg.geniv; inst->alg.cra_ablkcipher.setkey = balg.setkey; inst->alg.cra_ablkcipher.encrypt = balg.encrypt; inst->alg.cra_ablkcipher.decrypt = balg.decrypt; out: return inst; err_drop_alg: crypto_drop_skcipher(spawn); err_free_inst: kfree(inst); inst = ERR_PTR(err); goto out; } EXPORT_SYMBOL_GPL(skcipher_geniv_alloc); void skcipher_geniv_free(struct crypto_instance *inst) { crypto_drop_skcipher(crypto_instance_ctx(inst)); kfree(inst); } EXPORT_SYMBOL_GPL(skcipher_geniv_free); int skcipher_geniv_init(struct crypto_tfm *tfm) { struct crypto_instance *inst = (void *)tfm->__crt_alg; struct crypto_ablkcipher *cipher; cipher = crypto_spawn_skcipher(crypto_instance_ctx(inst)); if (IS_ERR(cipher)) return PTR_ERR(cipher); tfm->crt_ablkcipher.base = cipher; tfm->crt_ablkcipher.reqsize += crypto_ablkcipher_reqsize(cipher); return 0; } EXPORT_SYMBOL_GPL(skcipher_geniv_init); void skcipher_geniv_exit(struct crypto_tfm *tfm) { crypto_free_ablkcipher(tfm->crt_ablkcipher.base); } EXPORT_SYMBOL_GPL(skcipher_geniv_exit); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Generic block chaining cipher type");
./CrossVul/dataset_final_sorted/CWE-310/c/bad_5666_3
crossvul-cpp_data_good_5666_6
/* * Cryptographic API. * * RNG operations. * * Copyright (c) 2008 Neil Horman <nhorman@tuxdriver.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/atomic.h> #include <crypto/internal/rng.h> #include <linux/err.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/random.h> #include <linux/seq_file.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/cryptouser.h> #include <net/netlink.h> static DEFINE_MUTEX(crypto_default_rng_lock); struct crypto_rng *crypto_default_rng; EXPORT_SYMBOL_GPL(crypto_default_rng); static int crypto_default_rng_refcnt; static int rngapi_reset(struct crypto_rng *tfm, u8 *seed, unsigned int slen) { u8 *buf = NULL; int err; if (!seed && slen) { buf = kmalloc(slen, GFP_KERNEL); if (!buf) return -ENOMEM; get_random_bytes(buf, slen); seed = buf; } err = crypto_rng_alg(tfm)->rng_reset(tfm, seed, slen); kfree(buf); return err; } static int crypto_init_rng_ops(struct crypto_tfm *tfm, u32 type, u32 mask) { struct rng_alg *alg = &tfm->__crt_alg->cra_rng; struct rng_tfm *ops = &tfm->crt_rng; ops->rng_gen_random = alg->rng_make_random; ops->rng_reset = rngapi_reset; return 0; } #ifdef CONFIG_NET static int crypto_rng_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_rng rrng; strncpy(rrng.type, "rng", sizeof(rrng.type)); rrng.seedsize = alg->cra_rng.seedsize; if (nla_put(skb, CRYPTOCFGA_REPORT_RNG, sizeof(struct crypto_report_rng), &rrng)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } #else static int crypto_rng_report(struct sk_buff *skb, struct crypto_alg *alg) { return -ENOSYS; } #endif static void crypto_rng_show(struct seq_file *m, struct crypto_alg *alg) __attribute__ ((unused)); static void crypto_rng_show(struct seq_file *m, struct crypto_alg *alg) { seq_printf(m, "type : rng\n"); seq_printf(m, "seedsize : %u\n", alg->cra_rng.seedsize); } static unsigned int crypto_rng_ctxsize(struct crypto_alg *alg, u32 type, u32 mask) { return alg->cra_ctxsize; } const struct crypto_type crypto_rng_type = { .ctxsize = crypto_rng_ctxsize, .init = crypto_init_rng_ops, #ifdef CONFIG_PROC_FS .show = crypto_rng_show, #endif .report = crypto_rng_report, }; EXPORT_SYMBOL_GPL(crypto_rng_type); int crypto_get_default_rng(void) { struct crypto_rng *rng; int err; mutex_lock(&crypto_default_rng_lock); if (!crypto_default_rng) { rng = crypto_alloc_rng("stdrng", 0, 0); err = PTR_ERR(rng); if (IS_ERR(rng)) goto unlock; err = crypto_rng_reset(rng, NULL, crypto_rng_seedsize(rng)); if (err) { crypto_free_rng(rng); goto unlock; } crypto_default_rng = rng; } crypto_default_rng_refcnt++; err = 0; unlock: mutex_unlock(&crypto_default_rng_lock); return err; } EXPORT_SYMBOL_GPL(crypto_get_default_rng); void crypto_put_default_rng(void) { mutex_lock(&crypto_default_rng_lock); if (!--crypto_default_rng_refcnt) { crypto_free_rng(crypto_default_rng); crypto_default_rng = NULL; } mutex_unlock(&crypto_default_rng_lock); } EXPORT_SYMBOL_GPL(crypto_put_default_rng); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Random Number Generator");
./CrossVul/dataset_final_sorted/CWE-310/c/good_5666_6
crossvul-cpp_data_good_3783_1
/* * Copyright (C) 2007 Oracle. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License v2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 021110-1307, USA. */ #include "ctree.h" #include "disk-io.h" #include "hash.h" #include "transaction.h" /* * insert a name into a directory, doing overflow properly if there is a hash * collision. data_size indicates how big the item inserted should be. On * success a struct btrfs_dir_item pointer is returned, otherwise it is * an ERR_PTR. * * The name is not copied into the dir item, you have to do that yourself. */ static struct btrfs_dir_item *insert_with_overflow(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, struct btrfs_key *cpu_key, u32 data_size, const char *name, int name_len) { int ret; char *ptr; struct btrfs_item *item; struct extent_buffer *leaf; ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size); if (ret == -EEXIST) { struct btrfs_dir_item *di; di = btrfs_match_dir_item_name(root, path, name, name_len); if (di) return ERR_PTR(-EEXIST); btrfs_extend_item(trans, root, path, data_size); } else if (ret < 0) return ERR_PTR(ret); WARN_ON(ret > 0); leaf = path->nodes[0]; item = btrfs_item_nr(leaf, path->slots[0]); ptr = btrfs_item_ptr(leaf, path->slots[0], char); BUG_ON(data_size > btrfs_item_size(leaf, item)); ptr += btrfs_item_size(leaf, item) - data_size; return (struct btrfs_dir_item *)ptr; } /* * xattrs work a lot like directories, this inserts an xattr item * into the tree */ int btrfs_insert_xattr_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, u64 objectid, const char *name, u16 name_len, const void *data, u16 data_len) { int ret = 0; struct btrfs_dir_item *dir_item; unsigned long name_ptr, data_ptr; struct btrfs_key key, location; struct btrfs_disk_key disk_key; struct extent_buffer *leaf; u32 data_size; BUG_ON(name_len + data_len > BTRFS_MAX_XATTR_SIZE(root)); key.objectid = objectid; btrfs_set_key_type(&key, BTRFS_XATTR_ITEM_KEY); key.offset = btrfs_name_hash(name, name_len); data_size = sizeof(*dir_item) + name_len + data_len; dir_item = insert_with_overflow(trans, root, path, &key, data_size, name, name_len); if (IS_ERR(dir_item)) return PTR_ERR(dir_item); memset(&location, 0, sizeof(location)); leaf = path->nodes[0]; btrfs_cpu_key_to_disk(&disk_key, &location); btrfs_set_dir_item_key(leaf, dir_item, &disk_key); btrfs_set_dir_type(leaf, dir_item, BTRFS_FT_XATTR); btrfs_set_dir_name_len(leaf, dir_item, name_len); btrfs_set_dir_transid(leaf, dir_item, trans->transid); btrfs_set_dir_data_len(leaf, dir_item, data_len); name_ptr = (unsigned long)(dir_item + 1); data_ptr = (unsigned long)((char *)name_ptr + name_len); write_extent_buffer(leaf, name, name_ptr, name_len); write_extent_buffer(leaf, data, data_ptr, data_len); btrfs_mark_buffer_dirty(path->nodes[0]); return ret; } /* * insert a directory item in the tree, doing all the magic for * both indexes. 'dir' indicates which objectid to insert it into, * 'location' is the key to stuff into the directory item, 'type' is the * type of the inode we're pointing to, and 'index' is the sequence number * to use for the second index (if one is created). * Will return 0 or -ENOMEM */ int btrfs_insert_dir_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, const char *name, int name_len, struct inode *dir, struct btrfs_key *location, u8 type, u64 index) { int ret = 0; int ret2 = 0; struct btrfs_path *path; struct btrfs_dir_item *dir_item; struct extent_buffer *leaf; unsigned long name_ptr; struct btrfs_key key; struct btrfs_disk_key disk_key; u32 data_size; key.objectid = btrfs_ino(dir); btrfs_set_key_type(&key, BTRFS_DIR_ITEM_KEY); key.offset = btrfs_name_hash(name, name_len); path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->leave_spinning = 1; btrfs_cpu_key_to_disk(&disk_key, location); data_size = sizeof(*dir_item) + name_len; dir_item = insert_with_overflow(trans, root, path, &key, data_size, name, name_len); if (IS_ERR(dir_item)) { ret = PTR_ERR(dir_item); if (ret == -EEXIST) goto second_insert; goto out_free; } leaf = path->nodes[0]; btrfs_set_dir_item_key(leaf, dir_item, &disk_key); btrfs_set_dir_type(leaf, dir_item, type); btrfs_set_dir_data_len(leaf, dir_item, 0); btrfs_set_dir_name_len(leaf, dir_item, name_len); btrfs_set_dir_transid(leaf, dir_item, trans->transid); name_ptr = (unsigned long)(dir_item + 1); write_extent_buffer(leaf, name, name_ptr, name_len); btrfs_mark_buffer_dirty(leaf); second_insert: /* FIXME, use some real flag for selecting the extra index */ if (root == root->fs_info->tree_root) { ret = 0; goto out_free; } btrfs_release_path(path); ret2 = btrfs_insert_delayed_dir_index(trans, root, name, name_len, dir, &disk_key, type, index); out_free: btrfs_free_path(path); if (ret) return ret; if (ret2) return ret2; return 0; } /* * lookup a directory item based on name. 'dir' is the objectid * we're searching in, and 'mod' tells us if you plan on deleting the * item (use mod < 0) or changing the options (use mod > 0) */ struct btrfs_dir_item *btrfs_lookup_dir_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, u64 dir, const char *name, int name_len, int mod) { int ret; struct btrfs_key key; int ins_len = mod < 0 ? -1 : 0; int cow = mod != 0; key.objectid = dir; btrfs_set_key_type(&key, BTRFS_DIR_ITEM_KEY); key.offset = btrfs_name_hash(name, name_len); ret = btrfs_search_slot(trans, root, &key, path, ins_len, cow); if (ret < 0) return ERR_PTR(ret); if (ret > 0) return NULL; return btrfs_match_dir_item_name(root, path, name, name_len); } int btrfs_check_dir_item_collision(struct btrfs_root *root, u64 dir, const char *name, int name_len) { int ret; struct btrfs_key key; struct btrfs_dir_item *di; int data_size; struct extent_buffer *leaf; int slot; struct btrfs_path *path; path = btrfs_alloc_path(); if (!path) return -ENOMEM; key.objectid = dir; btrfs_set_key_type(&key, BTRFS_DIR_ITEM_KEY); key.offset = btrfs_name_hash(name, name_len); ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); /* return back any errors */ if (ret < 0) goto out; /* nothing found, we're safe */ if (ret > 0) { ret = 0; goto out; } /* we found an item, look for our name in the item */ di = btrfs_match_dir_item_name(root, path, name, name_len); if (di) { /* our exact name was found */ ret = -EEXIST; goto out; } /* * see if there is room in the item to insert this * name */ data_size = sizeof(*di) + name_len + sizeof(struct btrfs_item); leaf = path->nodes[0]; slot = path->slots[0]; if (data_size + btrfs_item_size_nr(leaf, slot) + sizeof(struct btrfs_item) > BTRFS_LEAF_DATA_SIZE(root)) { ret = -EOVERFLOW; } else { /* plenty of insertion room */ ret = 0; } out: btrfs_free_path(path); return ret; } /* * lookup a directory item based on index. 'dir' is the objectid * we're searching in, and 'mod' tells us if you plan on deleting the * item (use mod < 0) or changing the options (use mod > 0) * * The name is used to make sure the index really points to the name you were * looking for. */ struct btrfs_dir_item * btrfs_lookup_dir_index_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, u64 dir, u64 objectid, const char *name, int name_len, int mod) { int ret; struct btrfs_key key; int ins_len = mod < 0 ? -1 : 0; int cow = mod != 0; key.objectid = dir; btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY); key.offset = objectid; ret = btrfs_search_slot(trans, root, &key, path, ins_len, cow); if (ret < 0) return ERR_PTR(ret); if (ret > 0) return ERR_PTR(-ENOENT); return btrfs_match_dir_item_name(root, path, name, name_len); } struct btrfs_dir_item * btrfs_search_dir_index_item(struct btrfs_root *root, struct btrfs_path *path, u64 dirid, const char *name, int name_len) { struct extent_buffer *leaf; struct btrfs_dir_item *di; struct btrfs_key key; u32 nritems; int ret; key.objectid = dirid; key.type = BTRFS_DIR_INDEX_KEY; key.offset = 0; ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) return ERR_PTR(ret); leaf = path->nodes[0]; nritems = btrfs_header_nritems(leaf); while (1) { if (path->slots[0] >= nritems) { ret = btrfs_next_leaf(root, path); if (ret < 0) return ERR_PTR(ret); if (ret > 0) break; leaf = path->nodes[0]; nritems = btrfs_header_nritems(leaf); continue; } btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); if (key.objectid != dirid || key.type != BTRFS_DIR_INDEX_KEY) break; di = btrfs_match_dir_item_name(root, path, name, name_len); if (di) return di; path->slots[0]++; } return NULL; } struct btrfs_dir_item *btrfs_lookup_xattr(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, u64 dir, const char *name, u16 name_len, int mod) { int ret; struct btrfs_key key; int ins_len = mod < 0 ? -1 : 0; int cow = mod != 0; key.objectid = dir; btrfs_set_key_type(&key, BTRFS_XATTR_ITEM_KEY); key.offset = btrfs_name_hash(name, name_len); ret = btrfs_search_slot(trans, root, &key, path, ins_len, cow); if (ret < 0) return ERR_PTR(ret); if (ret > 0) return NULL; return btrfs_match_dir_item_name(root, path, name, name_len); } /* * helper function to look at the directory item pointed to by 'path' * this walks through all the entries in a dir item and finds one * for a specific name. */ struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_root *root, struct btrfs_path *path, const char *name, int name_len) { struct btrfs_dir_item *dir_item; unsigned long name_ptr; u32 total_len; u32 cur = 0; u32 this_len; struct extent_buffer *leaf; leaf = path->nodes[0]; dir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item); if (verify_dir_item(root, leaf, dir_item)) return NULL; total_len = btrfs_item_size_nr(leaf, path->slots[0]); while (cur < total_len) { this_len = sizeof(*dir_item) + btrfs_dir_name_len(leaf, dir_item) + btrfs_dir_data_len(leaf, dir_item); name_ptr = (unsigned long)(dir_item + 1); if (btrfs_dir_name_len(leaf, dir_item) == name_len && memcmp_extent_buffer(leaf, name, name_ptr, name_len) == 0) return dir_item; cur += this_len; dir_item = (struct btrfs_dir_item *)((char *)dir_item + this_len); } return NULL; } /* * given a pointer into a directory item, delete it. This * handles items that have more than one entry in them. */ int btrfs_delete_one_dir_name(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, struct btrfs_dir_item *di) { struct extent_buffer *leaf; u32 sub_item_len; u32 item_len; int ret = 0; leaf = path->nodes[0]; sub_item_len = sizeof(*di) + btrfs_dir_name_len(leaf, di) + btrfs_dir_data_len(leaf, di); item_len = btrfs_item_size_nr(leaf, path->slots[0]); if (sub_item_len == item_len) { ret = btrfs_del_item(trans, root, path); } else { /* MARKER */ unsigned long ptr = (unsigned long)di; unsigned long start; start = btrfs_item_ptr_offset(leaf, path->slots[0]); memmove_extent_buffer(leaf, ptr, ptr + sub_item_len, item_len - (ptr + sub_item_len - start)); btrfs_truncate_item(trans, root, path, item_len - sub_item_len, 1); } return ret; } int verify_dir_item(struct btrfs_root *root, struct extent_buffer *leaf, struct btrfs_dir_item *dir_item) { u16 namelen = BTRFS_NAME_LEN; u8 type = btrfs_dir_type(leaf, dir_item); if (type >= BTRFS_FT_MAX) { printk(KERN_CRIT "btrfs: invalid dir item type: %d\n", (int)type); return 1; } if (type == BTRFS_FT_XATTR) namelen = XATTR_NAME_MAX; if (btrfs_dir_name_len(leaf, dir_item) > namelen) { printk(KERN_CRIT "btrfs: invalid dir item name len: %u\n", (unsigned)btrfs_dir_data_len(leaf, dir_item)); return 1; } /* BTRFS_MAX_XATTR_SIZE is the same for all dir items */ if (btrfs_dir_data_len(leaf, dir_item) > BTRFS_MAX_XATTR_SIZE(root)) { printk(KERN_CRIT "btrfs: invalid dir item data len: %u\n", (unsigned)btrfs_dir_data_len(leaf, dir_item)); return 1; } return 0; }
./CrossVul/dataset_final_sorted/CWE-310/c/good_3783_1
crossvul-cpp_data_good_893_2
/* Rijndael (AES) for GnuPG * Copyright (C) 2000, 2001, 2002, 2003, 2007, * 2008, 2011, 2012 Free Software Foundation, Inc. * * This file is part of Libgcrypt. * * Libgcrypt 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. * * Libgcrypt 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 program; if not, see <http://www.gnu.org/licenses/>. ******************************************************************* * The code here is based on the optimized implementation taken from * http://www.esat.kuleuven.ac.be/~rijmen/rijndael/ on Oct 2, 2000, * which carries this notice: *------------------------------------------ * rijndael-alg-fst.c v2.3 April '2000 * * Optimised ANSI C code * * authors: v1.0: Antoon Bosselaers * v2.0: Vincent Rijmen * v2.3: Paulo Barreto * * This code is placed in the public domain. *------------------------------------------ * * The SP800-38a document is available at: * http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf * */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* for memcmp() */ #include "types.h" /* for byte and u32 typedefs */ #include "g10lib.h" #include "cipher.h" #include "bufhelp.h" #include "cipher-selftest.h" #include "rijndael-internal.h" #include "./cipher-internal.h" #ifdef USE_AMD64_ASM /* AMD64 assembly implementations of AES */ extern unsigned int _gcry_aes_amd64_encrypt_block(const void *keysched_enc, unsigned char *out, const unsigned char *in, int rounds, const void *encT); extern unsigned int _gcry_aes_amd64_decrypt_block(const void *keysched_dec, unsigned char *out, const unsigned char *in, int rounds, const void *decT); #endif /*USE_AMD64_ASM*/ #ifdef USE_AESNI /* AES-NI (AMD64 & i386) accelerated implementations of AES */ extern void _gcry_aes_aesni_do_setkey(RIJNDAEL_context *ctx, const byte *key); extern void _gcry_aes_aesni_prepare_decryption(RIJNDAEL_context *ctx); extern unsigned int _gcry_aes_aesni_encrypt (const RIJNDAEL_context *ctx, unsigned char *dst, const unsigned char *src); extern unsigned int _gcry_aes_aesni_decrypt (const RIJNDAEL_context *ctx, unsigned char *dst, const unsigned char *src); extern void _gcry_aes_aesni_cfb_enc (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern void _gcry_aes_aesni_cbc_enc (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int cbc_mac); extern void _gcry_aes_aesni_ctr_enc (void *context, unsigned char *ctr, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern void _gcry_aes_aesni_cfb_dec (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern void _gcry_aes_aesni_cbc_dec (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern size_t _gcry_aes_aesni_ocb_crypt (gcry_cipher_hd_t c, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int encrypt); extern size_t _gcry_aes_aesni_ocb_auth (gcry_cipher_hd_t c, const void *abuf_arg, size_t nblocks); extern void _gcry_aes_aesni_xts_crypt (void *context, unsigned char *tweak, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int encrypt); #endif #ifdef USE_SSSE3 /* SSSE3 (AMD64) vector permutation implementation of AES */ extern void _gcry_aes_ssse3_do_setkey(RIJNDAEL_context *ctx, const byte *key); extern void _gcry_aes_ssse3_prepare_decryption(RIJNDAEL_context *ctx); extern unsigned int _gcry_aes_ssse3_encrypt (const RIJNDAEL_context *ctx, unsigned char *dst, const unsigned char *src); extern unsigned int _gcry_aes_ssse3_decrypt (const RIJNDAEL_context *ctx, unsigned char *dst, const unsigned char *src); extern void _gcry_aes_ssse3_cfb_enc (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern void _gcry_aes_ssse3_cbc_enc (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int cbc_mac); extern void _gcry_aes_ssse3_ctr_enc (void *context, unsigned char *ctr, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern void _gcry_aes_ssse3_cfb_dec (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern void _gcry_aes_ssse3_cbc_dec (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern size_t _gcry_aes_ssse3_ocb_crypt (gcry_cipher_hd_t c, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int encrypt); extern size_t _gcry_aes_ssse3_ocb_auth (gcry_cipher_hd_t c, const void *abuf_arg, size_t nblocks); #endif #ifdef USE_PADLOCK extern unsigned int _gcry_aes_padlock_encrypt (const RIJNDAEL_context *ctx, unsigned char *bx, const unsigned char *ax); extern unsigned int _gcry_aes_padlock_decrypt (const RIJNDAEL_context *ctx, unsigned char *bx, const unsigned char *ax); #endif #ifdef USE_ARM_ASM /* ARM assembly implementations of AES */ extern unsigned int _gcry_aes_arm_encrypt_block(const void *keysched_enc, unsigned char *out, const unsigned char *in, int rounds, const void *encT); extern unsigned int _gcry_aes_arm_decrypt_block(const void *keysched_dec, unsigned char *out, const unsigned char *in, int rounds, const void *decT); #endif /*USE_ARM_ASM*/ #ifdef USE_ARM_CE /* ARMv8 Crypto Extension implementations of AES */ extern void _gcry_aes_armv8_ce_setkey(RIJNDAEL_context *ctx, const byte *key); extern void _gcry_aes_armv8_ce_prepare_decryption(RIJNDAEL_context *ctx); extern unsigned int _gcry_aes_armv8_ce_encrypt(const RIJNDAEL_context *ctx, unsigned char *dst, const unsigned char *src); extern unsigned int _gcry_aes_armv8_ce_decrypt(const RIJNDAEL_context *ctx, unsigned char *dst, const unsigned char *src); extern void _gcry_aes_armv8_ce_cfb_enc (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern void _gcry_aes_armv8_ce_cbc_enc (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int cbc_mac); extern void _gcry_aes_armv8_ce_ctr_enc (void *context, unsigned char *ctr, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern void _gcry_aes_armv8_ce_cfb_dec (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern void _gcry_aes_armv8_ce_cbc_dec (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern size_t _gcry_aes_armv8_ce_ocb_crypt (gcry_cipher_hd_t c, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int encrypt); extern size_t _gcry_aes_armv8_ce_ocb_auth (gcry_cipher_hd_t c, const void *abuf_arg, size_t nblocks); extern void _gcry_aes_armv8_ce_xts_crypt (void *context, unsigned char *tweak, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int encrypt); #endif /*USE_ARM_ASM*/ static unsigned int do_encrypt (const RIJNDAEL_context *ctx, unsigned char *bx, const unsigned char *ax); static unsigned int do_decrypt (const RIJNDAEL_context *ctx, unsigned char *bx, const unsigned char *ax); /* All the numbers. */ #include "rijndael-tables.h" /* Function prototypes. */ static const char *selftest(void); /* Prefetching for encryption/decryption tables. */ static inline void prefetch_table(const volatile byte *tab, size_t len) { size_t i; for (i = 0; len - i >= 8 * 32; i += 8 * 32) { (void)tab[i + 0 * 32]; (void)tab[i + 1 * 32]; (void)tab[i + 2 * 32]; (void)tab[i + 3 * 32]; (void)tab[i + 4 * 32]; (void)tab[i + 5 * 32]; (void)tab[i + 6 * 32]; (void)tab[i + 7 * 32]; } for (; i < len; i += 32) { (void)tab[i]; } (void)tab[len - 1]; } static void prefetch_enc(void) { /* Modify counters to trigger copy-on-write and unsharing if physical pages * of look-up table are shared between processes. Modifying counters also * causes checksums for pages to change and hint same-page merging algorithm * that these pages are frequently changing. */ enc_tables.counter_head++; enc_tables.counter_tail++; /* Prefetch look-up tables to cache. */ prefetch_table((const void *)&enc_tables, sizeof(enc_tables)); } static void prefetch_dec(void) { /* Modify counters to trigger copy-on-write and unsharing if physical pages * of look-up table are shared between processes. Modifying counters also * causes checksums for pages to change and hint same-page merging algorithm * that these pages are frequently changing. */ dec_tables.counter_head++; dec_tables.counter_tail++; /* Prefetch look-up tables to cache. */ prefetch_table((const void *)&dec_tables, sizeof(dec_tables)); } /* Perform the key setup. */ static gcry_err_code_t do_setkey (RIJNDAEL_context *ctx, const byte *key, const unsigned keylen, gcry_cipher_hd_t hd) { static int initialized = 0; static const char *selftest_failed = 0; int rounds; int i,j, r, t, rconpointer = 0; int KC; #if defined(USE_AESNI) || defined(USE_PADLOCK) || defined(USE_SSSE3) \ || defined(USE_ARM_CE) unsigned int hwfeatures; #endif (void)hd; /* The on-the-fly self tests are only run in non-fips mode. In fips mode explicit self-tests are required. Actually the on-the-fly self-tests are not fully thread-safe and it might happen that a failed self-test won't get noticed in another thread. FIXME: We might want to have a central registry of succeeded self-tests. */ if (!fips_mode () && !initialized) { initialized = 1; selftest_failed = selftest (); if (selftest_failed) log_error ("%s\n", selftest_failed ); } if (selftest_failed) return GPG_ERR_SELFTEST_FAILED; if( keylen == 128/8 ) { rounds = 10; KC = 4; } else if ( keylen == 192/8 ) { rounds = 12; KC = 6; } else if ( keylen == 256/8 ) { rounds = 14; KC = 8; } else return GPG_ERR_INV_KEYLEN; ctx->rounds = rounds; #if defined(USE_AESNI) || defined(USE_PADLOCK) || defined(USE_SSSE3) \ || defined(USE_ARM_CE) hwfeatures = _gcry_get_hw_features (); #endif ctx->decryption_prepared = 0; #ifdef USE_PADLOCK ctx->use_padlock = 0; #endif #ifdef USE_AESNI ctx->use_aesni = 0; #endif #ifdef USE_SSSE3 ctx->use_ssse3 = 0; #endif #ifdef USE_ARM_CE ctx->use_arm_ce = 0; #endif if (0) { ; } #ifdef USE_AESNI else if (hwfeatures & HWF_INTEL_AESNI) { ctx->encrypt_fn = _gcry_aes_aesni_encrypt; ctx->decrypt_fn = _gcry_aes_aesni_decrypt; ctx->prefetch_enc_fn = NULL; ctx->prefetch_dec_fn = NULL; ctx->use_aesni = 1; ctx->use_avx = !!(hwfeatures & HWF_INTEL_AVX); ctx->use_avx2 = !!(hwfeatures & HWF_INTEL_AVX2); if (hd) { hd->bulk.cfb_enc = _gcry_aes_aesni_cfb_enc; hd->bulk.cfb_dec = _gcry_aes_aesni_cfb_dec; hd->bulk.cbc_enc = _gcry_aes_aesni_cbc_enc; hd->bulk.cbc_dec = _gcry_aes_aesni_cbc_dec; hd->bulk.ctr_enc = _gcry_aes_aesni_ctr_enc; hd->bulk.ocb_crypt = _gcry_aes_aesni_ocb_crypt; hd->bulk.ocb_auth = _gcry_aes_aesni_ocb_auth; hd->bulk.xts_crypt = _gcry_aes_aesni_xts_crypt; } } #endif #ifdef USE_PADLOCK else if (hwfeatures & HWF_PADLOCK_AES && keylen == 128/8) { ctx->encrypt_fn = _gcry_aes_padlock_encrypt; ctx->decrypt_fn = _gcry_aes_padlock_decrypt; ctx->prefetch_enc_fn = NULL; ctx->prefetch_dec_fn = NULL; ctx->use_padlock = 1; memcpy (ctx->padlockkey, key, keylen); } #endif #ifdef USE_SSSE3 else if (hwfeatures & HWF_INTEL_SSSE3) { ctx->encrypt_fn = _gcry_aes_ssse3_encrypt; ctx->decrypt_fn = _gcry_aes_ssse3_decrypt; ctx->prefetch_enc_fn = NULL; ctx->prefetch_dec_fn = NULL; ctx->use_ssse3 = 1; if (hd) { hd->bulk.cfb_enc = _gcry_aes_ssse3_cfb_enc; hd->bulk.cfb_dec = _gcry_aes_ssse3_cfb_dec; hd->bulk.cbc_enc = _gcry_aes_ssse3_cbc_enc; hd->bulk.cbc_dec = _gcry_aes_ssse3_cbc_dec; hd->bulk.ctr_enc = _gcry_aes_ssse3_ctr_enc; hd->bulk.ocb_crypt = _gcry_aes_ssse3_ocb_crypt; hd->bulk.ocb_auth = _gcry_aes_ssse3_ocb_auth; } } #endif #ifdef USE_ARM_CE else if (hwfeatures & HWF_ARM_AES) { ctx->encrypt_fn = _gcry_aes_armv8_ce_encrypt; ctx->decrypt_fn = _gcry_aes_armv8_ce_decrypt; ctx->prefetch_enc_fn = NULL; ctx->prefetch_dec_fn = NULL; ctx->use_arm_ce = 1; if (hd) { hd->bulk.cfb_enc = _gcry_aes_armv8_ce_cfb_enc; hd->bulk.cfb_dec = _gcry_aes_armv8_ce_cfb_dec; hd->bulk.cbc_enc = _gcry_aes_armv8_ce_cbc_enc; hd->bulk.cbc_dec = _gcry_aes_armv8_ce_cbc_dec; hd->bulk.ctr_enc = _gcry_aes_armv8_ce_ctr_enc; hd->bulk.ocb_crypt = _gcry_aes_armv8_ce_ocb_crypt; hd->bulk.ocb_auth = _gcry_aes_armv8_ce_ocb_auth; hd->bulk.xts_crypt = _gcry_aes_armv8_ce_xts_crypt; } } #endif else { ctx->encrypt_fn = do_encrypt; ctx->decrypt_fn = do_decrypt; ctx->prefetch_enc_fn = prefetch_enc; ctx->prefetch_dec_fn = prefetch_dec; } /* NB: We don't yet support Padlock hardware key generation. */ if (0) { ; } #ifdef USE_AESNI else if (ctx->use_aesni) _gcry_aes_aesni_do_setkey (ctx, key); #endif #ifdef USE_SSSE3 else if (ctx->use_ssse3) _gcry_aes_ssse3_do_setkey (ctx, key); #endif #ifdef USE_ARM_CE else if (ctx->use_arm_ce) _gcry_aes_armv8_ce_setkey (ctx, key); #endif else { const byte *sbox = ((const byte *)encT) + 1; union { PROPERLY_ALIGNED_TYPE dummy; byte data[MAXKC][4]; u32 data32[MAXKC]; } tkk[2]; #define k tkk[0].data #define k_u32 tkk[0].data32 #define tk tkk[1].data #define tk_u32 tkk[1].data32 #define W (ctx->keyschenc) #define W_u32 (ctx->keyschenc32) prefetch_enc(); for (i = 0; i < keylen; i++) { k[i >> 2][i & 3] = key[i]; } for (j = KC-1; j >= 0; j--) { tk_u32[j] = k_u32[j]; } r = 0; t = 0; /* Copy values into round key array. */ for (j = 0; (j < KC) && (r < rounds + 1); ) { for (; (j < KC) && (t < 4); j++, t++) { W_u32[r][t] = le_bswap32(tk_u32[j]); } if (t == 4) { r++; t = 0; } } while (r < rounds + 1) { /* While not enough round key material calculated calculate new values. */ tk[0][0] ^= sbox[tk[KC-1][1] * 4]; tk[0][1] ^= sbox[tk[KC-1][2] * 4]; tk[0][2] ^= sbox[tk[KC-1][3] * 4]; tk[0][3] ^= sbox[tk[KC-1][0] * 4]; tk[0][0] ^= rcon[rconpointer++]; if (KC != 8) { for (j = 1; j < KC; j++) { tk_u32[j] ^= tk_u32[j-1]; } } else { for (j = 1; j < KC/2; j++) { tk_u32[j] ^= tk_u32[j-1]; } tk[KC/2][0] ^= sbox[tk[KC/2 - 1][0] * 4]; tk[KC/2][1] ^= sbox[tk[KC/2 - 1][1] * 4]; tk[KC/2][2] ^= sbox[tk[KC/2 - 1][2] * 4]; tk[KC/2][3] ^= sbox[tk[KC/2 - 1][3] * 4]; for (j = KC/2 + 1; j < KC; j++) { tk_u32[j] ^= tk_u32[j-1]; } } /* Copy values into round key array. */ for (j = 0; (j < KC) && (r < rounds + 1); ) { for (; (j < KC) && (t < 4); j++, t++) { W_u32[r][t] = le_bswap32(tk_u32[j]); } if (t == 4) { r++; t = 0; } } } #undef W #undef tk #undef k #undef W_u32 #undef tk_u32 #undef k_u32 wipememory(&tkk, sizeof(tkk)); } return 0; } static gcry_err_code_t rijndael_setkey (void *context, const byte *key, const unsigned keylen, gcry_cipher_hd_t hd) { RIJNDAEL_context *ctx = context; return do_setkey (ctx, key, keylen, hd); } /* Make a decryption key from an encryption key. */ static void prepare_decryption( RIJNDAEL_context *ctx ) { int r; if (0) ; #ifdef USE_AESNI else if (ctx->use_aesni) { _gcry_aes_aesni_prepare_decryption (ctx); } #endif /*USE_AESNI*/ #ifdef USE_SSSE3 else if (ctx->use_ssse3) { _gcry_aes_ssse3_prepare_decryption (ctx); } #endif /*USE_SSSE3*/ #ifdef USE_ARM_CE else if (ctx->use_arm_ce) { _gcry_aes_armv8_ce_prepare_decryption (ctx); } #endif /*USE_SSSE3*/ #ifdef USE_PADLOCK else if (ctx->use_padlock) { /* Padlock does not need decryption subkeys. */ } #endif /*USE_PADLOCK*/ else { const byte *sbox = ((const byte *)encT) + 1; prefetch_enc(); prefetch_dec(); ctx->keyschdec32[0][0] = ctx->keyschenc32[0][0]; ctx->keyschdec32[0][1] = ctx->keyschenc32[0][1]; ctx->keyschdec32[0][2] = ctx->keyschenc32[0][2]; ctx->keyschdec32[0][3] = ctx->keyschenc32[0][3]; for (r = 1; r < ctx->rounds; r++) { u32 *wi = ctx->keyschenc32[r]; u32 *wo = ctx->keyschdec32[r]; u32 wt; wt = wi[0]; wo[0] = rol(decT[sbox[(byte)(wt >> 0) * 4]], 8 * 0) ^ rol(decT[sbox[(byte)(wt >> 8) * 4]], 8 * 1) ^ rol(decT[sbox[(byte)(wt >> 16) * 4]], 8 * 2) ^ rol(decT[sbox[(byte)(wt >> 24) * 4]], 8 * 3); wt = wi[1]; wo[1] = rol(decT[sbox[(byte)(wt >> 0) * 4]], 8 * 0) ^ rol(decT[sbox[(byte)(wt >> 8) * 4]], 8 * 1) ^ rol(decT[sbox[(byte)(wt >> 16) * 4]], 8 * 2) ^ rol(decT[sbox[(byte)(wt >> 24) * 4]], 8 * 3); wt = wi[2]; wo[2] = rol(decT[sbox[(byte)(wt >> 0) * 4]], 8 * 0) ^ rol(decT[sbox[(byte)(wt >> 8) * 4]], 8 * 1) ^ rol(decT[sbox[(byte)(wt >> 16) * 4]], 8 * 2) ^ rol(decT[sbox[(byte)(wt >> 24) * 4]], 8 * 3); wt = wi[3]; wo[3] = rol(decT[sbox[(byte)(wt >> 0) * 4]], 8 * 0) ^ rol(decT[sbox[(byte)(wt >> 8) * 4]], 8 * 1) ^ rol(decT[sbox[(byte)(wt >> 16) * 4]], 8 * 2) ^ rol(decT[sbox[(byte)(wt >> 24) * 4]], 8 * 3); } ctx->keyschdec32[r][0] = ctx->keyschenc32[r][0]; ctx->keyschdec32[r][1] = ctx->keyschenc32[r][1]; ctx->keyschdec32[r][2] = ctx->keyschenc32[r][2]; ctx->keyschdec32[r][3] = ctx->keyschenc32[r][3]; } } #if !defined(USE_ARM_ASM) && !defined(USE_AMD64_ASM) /* Encrypt one block. A and B may be the same. */ static unsigned int do_encrypt_fn (const RIJNDAEL_context *ctx, unsigned char *b, const unsigned char *a) { #define rk (ctx->keyschenc32) const byte *sbox = ((const byte *)encT) + 1; int rounds = ctx->rounds; int r; u32 sa[4]; u32 sb[4]; sb[0] = buf_get_le32(a + 0); sb[1] = buf_get_le32(a + 4); sb[2] = buf_get_le32(a + 8); sb[3] = buf_get_le32(a + 12); sa[0] = sb[0] ^ rk[0][0]; sa[1] = sb[1] ^ rk[0][1]; sa[2] = sb[2] ^ rk[0][2]; sa[3] = sb[3] ^ rk[0][3]; sb[0] = rol(encT[(byte)(sa[0] >> (0 * 8))], (0 * 8)); sb[3] = rol(encT[(byte)(sa[0] >> (1 * 8))], (1 * 8)); sb[2] = rol(encT[(byte)(sa[0] >> (2 * 8))], (2 * 8)); sb[1] = rol(encT[(byte)(sa[0] >> (3 * 8))], (3 * 8)); sa[0] = rk[1][0] ^ sb[0]; sb[1] ^= rol(encT[(byte)(sa[1] >> (0 * 8))], (0 * 8)); sa[0] ^= rol(encT[(byte)(sa[1] >> (1 * 8))], (1 * 8)); sb[3] ^= rol(encT[(byte)(sa[1] >> (2 * 8))], (2 * 8)); sb[2] ^= rol(encT[(byte)(sa[1] >> (3 * 8))], (3 * 8)); sa[1] = rk[1][1] ^ sb[1]; sb[2] ^= rol(encT[(byte)(sa[2] >> (0 * 8))], (0 * 8)); sa[1] ^= rol(encT[(byte)(sa[2] >> (1 * 8))], (1 * 8)); sa[0] ^= rol(encT[(byte)(sa[2] >> (2 * 8))], (2 * 8)); sb[3] ^= rol(encT[(byte)(sa[2] >> (3 * 8))], (3 * 8)); sa[2] = rk[1][2] ^ sb[2]; sb[3] ^= rol(encT[(byte)(sa[3] >> (0 * 8))], (0 * 8)); sa[2] ^= rol(encT[(byte)(sa[3] >> (1 * 8))], (1 * 8)); sa[1] ^= rol(encT[(byte)(sa[3] >> (2 * 8))], (2 * 8)); sa[0] ^= rol(encT[(byte)(sa[3] >> (3 * 8))], (3 * 8)); sa[3] = rk[1][3] ^ sb[3]; for (r = 2; r < rounds; r++) { sb[0] = rol(encT[(byte)(sa[0] >> (0 * 8))], (0 * 8)); sb[3] = rol(encT[(byte)(sa[0] >> (1 * 8))], (1 * 8)); sb[2] = rol(encT[(byte)(sa[0] >> (2 * 8))], (2 * 8)); sb[1] = rol(encT[(byte)(sa[0] >> (3 * 8))], (3 * 8)); sa[0] = rk[r][0] ^ sb[0]; sb[1] ^= rol(encT[(byte)(sa[1] >> (0 * 8))], (0 * 8)); sa[0] ^= rol(encT[(byte)(sa[1] >> (1 * 8))], (1 * 8)); sb[3] ^= rol(encT[(byte)(sa[1] >> (2 * 8))], (2 * 8)); sb[2] ^= rol(encT[(byte)(sa[1] >> (3 * 8))], (3 * 8)); sa[1] = rk[r][1] ^ sb[1]; sb[2] ^= rol(encT[(byte)(sa[2] >> (0 * 8))], (0 * 8)); sa[1] ^= rol(encT[(byte)(sa[2] >> (1 * 8))], (1 * 8)); sa[0] ^= rol(encT[(byte)(sa[2] >> (2 * 8))], (2 * 8)); sb[3] ^= rol(encT[(byte)(sa[2] >> (3 * 8))], (3 * 8)); sa[2] = rk[r][2] ^ sb[2]; sb[3] ^= rol(encT[(byte)(sa[3] >> (0 * 8))], (0 * 8)); sa[2] ^= rol(encT[(byte)(sa[3] >> (1 * 8))], (1 * 8)); sa[1] ^= rol(encT[(byte)(sa[3] >> (2 * 8))], (2 * 8)); sa[0] ^= rol(encT[(byte)(sa[3] >> (3 * 8))], (3 * 8)); sa[3] = rk[r][3] ^ sb[3]; r++; sb[0] = rol(encT[(byte)(sa[0] >> (0 * 8))], (0 * 8)); sb[3] = rol(encT[(byte)(sa[0] >> (1 * 8))], (1 * 8)); sb[2] = rol(encT[(byte)(sa[0] >> (2 * 8))], (2 * 8)); sb[1] = rol(encT[(byte)(sa[0] >> (3 * 8))], (3 * 8)); sa[0] = rk[r][0] ^ sb[0]; sb[1] ^= rol(encT[(byte)(sa[1] >> (0 * 8))], (0 * 8)); sa[0] ^= rol(encT[(byte)(sa[1] >> (1 * 8))], (1 * 8)); sb[3] ^= rol(encT[(byte)(sa[1] >> (2 * 8))], (2 * 8)); sb[2] ^= rol(encT[(byte)(sa[1] >> (3 * 8))], (3 * 8)); sa[1] = rk[r][1] ^ sb[1]; sb[2] ^= rol(encT[(byte)(sa[2] >> (0 * 8))], (0 * 8)); sa[1] ^= rol(encT[(byte)(sa[2] >> (1 * 8))], (1 * 8)); sa[0] ^= rol(encT[(byte)(sa[2] >> (2 * 8))], (2 * 8)); sb[3] ^= rol(encT[(byte)(sa[2] >> (3 * 8))], (3 * 8)); sa[2] = rk[r][2] ^ sb[2]; sb[3] ^= rol(encT[(byte)(sa[3] >> (0 * 8))], (0 * 8)); sa[2] ^= rol(encT[(byte)(sa[3] >> (1 * 8))], (1 * 8)); sa[1] ^= rol(encT[(byte)(sa[3] >> (2 * 8))], (2 * 8)); sa[0] ^= rol(encT[(byte)(sa[3] >> (3 * 8))], (3 * 8)); sa[3] = rk[r][3] ^ sb[3]; } /* Last round is special. */ sb[0] = (sbox[(byte)(sa[0] >> (0 * 8)) * 4]) << (0 * 8); sb[3] = (sbox[(byte)(sa[0] >> (1 * 8)) * 4]) << (1 * 8); sb[2] = (sbox[(byte)(sa[0] >> (2 * 8)) * 4]) << (2 * 8); sb[1] = (sbox[(byte)(sa[0] >> (3 * 8)) * 4]) << (3 * 8); sa[0] = rk[r][0] ^ sb[0]; sb[1] ^= (sbox[(byte)(sa[1] >> (0 * 8)) * 4]) << (0 * 8); sa[0] ^= (sbox[(byte)(sa[1] >> (1 * 8)) * 4]) << (1 * 8); sb[3] ^= (sbox[(byte)(sa[1] >> (2 * 8)) * 4]) << (2 * 8); sb[2] ^= (sbox[(byte)(sa[1] >> (3 * 8)) * 4]) << (3 * 8); sa[1] = rk[r][1] ^ sb[1]; sb[2] ^= (sbox[(byte)(sa[2] >> (0 * 8)) * 4]) << (0 * 8); sa[1] ^= (sbox[(byte)(sa[2] >> (1 * 8)) * 4]) << (1 * 8); sa[0] ^= (sbox[(byte)(sa[2] >> (2 * 8)) * 4]) << (2 * 8); sb[3] ^= (sbox[(byte)(sa[2] >> (3 * 8)) * 4]) << (3 * 8); sa[2] = rk[r][2] ^ sb[2]; sb[3] ^= (sbox[(byte)(sa[3] >> (0 * 8)) * 4]) << (0 * 8); sa[2] ^= (sbox[(byte)(sa[3] >> (1 * 8)) * 4]) << (1 * 8); sa[1] ^= (sbox[(byte)(sa[3] >> (2 * 8)) * 4]) << (2 * 8); sa[0] ^= (sbox[(byte)(sa[3] >> (3 * 8)) * 4]) << (3 * 8); sa[3] = rk[r][3] ^ sb[3]; buf_put_le32(b + 0, sa[0]); buf_put_le32(b + 4, sa[1]); buf_put_le32(b + 8, sa[2]); buf_put_le32(b + 12, sa[3]); #undef rk return (56 + 2*sizeof(int)); } #endif /*!USE_ARM_ASM && !USE_AMD64_ASM*/ static unsigned int do_encrypt (const RIJNDAEL_context *ctx, unsigned char *bx, const unsigned char *ax) { #ifdef USE_AMD64_ASM return _gcry_aes_amd64_encrypt_block(ctx->keyschenc, bx, ax, ctx->rounds, enc_tables.T); #elif defined(USE_ARM_ASM) return _gcry_aes_arm_encrypt_block(ctx->keyschenc, bx, ax, ctx->rounds, enc_tables.T); #else return do_encrypt_fn (ctx, bx, ax); #endif /* !USE_ARM_ASM && !USE_AMD64_ASM*/ } static unsigned int rijndael_encrypt (void *context, byte *b, const byte *a) { RIJNDAEL_context *ctx = context; if (ctx->prefetch_enc_fn) ctx->prefetch_enc_fn(); return ctx->encrypt_fn (ctx, b, a); } /* Bulk encryption of complete blocks in CFB mode. Caller needs to make sure that IV is aligned on an unsigned long boundary. This function is only intended for the bulk encryption feature of cipher.c. */ void _gcry_aes_cfb_enc (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks) { RIJNDAEL_context *ctx = context; unsigned char *outbuf = outbuf_arg; const unsigned char *inbuf = inbuf_arg; unsigned int burn_depth = 0; if (0) ; #ifdef USE_AESNI else if (ctx->use_aesni) { _gcry_aes_aesni_cfb_enc (ctx, iv, outbuf, inbuf, nblocks); return; } #endif /*USE_AESNI*/ #ifdef USE_SSSE3 else if (ctx->use_ssse3) { _gcry_aes_ssse3_cfb_enc (ctx, iv, outbuf, inbuf, nblocks); return; } #endif /*USE_SSSE3*/ #ifdef USE_ARM_CE else if (ctx->use_arm_ce) { _gcry_aes_armv8_ce_cfb_enc (ctx, iv, outbuf, inbuf, nblocks); return; } #endif /*USE_ARM_CE*/ else { rijndael_cryptfn_t encrypt_fn = ctx->encrypt_fn; if (ctx->prefetch_enc_fn) ctx->prefetch_enc_fn(); for ( ;nblocks; nblocks-- ) { /* Encrypt the IV. */ burn_depth = encrypt_fn (ctx, iv, iv); /* XOR the input with the IV and store input into IV. */ cipher_block_xor_2dst(outbuf, iv, inbuf, BLOCKSIZE); outbuf += BLOCKSIZE; inbuf += BLOCKSIZE; } } if (burn_depth) _gcry_burn_stack (burn_depth + 4 * sizeof(void *)); } /* Bulk encryption of complete blocks in CBC mode. Caller needs to make sure that IV is aligned on an unsigned long boundary. This function is only intended for the bulk encryption feature of cipher.c. */ void _gcry_aes_cbc_enc (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int cbc_mac) { RIJNDAEL_context *ctx = context; unsigned char *outbuf = outbuf_arg; const unsigned char *inbuf = inbuf_arg; unsigned char *last_iv; unsigned int burn_depth = 0; if (0) ; #ifdef USE_AESNI else if (ctx->use_aesni) { _gcry_aes_aesni_cbc_enc (ctx, iv, outbuf, inbuf, nblocks, cbc_mac); return; } #endif /*USE_AESNI*/ #ifdef USE_SSSE3 else if (ctx->use_ssse3) { _gcry_aes_ssse3_cbc_enc (ctx, iv, outbuf, inbuf, nblocks, cbc_mac); return; } #endif /*USE_SSSE3*/ #ifdef USE_ARM_CE else if (ctx->use_arm_ce) { _gcry_aes_armv8_ce_cbc_enc (ctx, iv, outbuf, inbuf, nblocks, cbc_mac); return; } #endif /*USE_ARM_CE*/ else { rijndael_cryptfn_t encrypt_fn = ctx->encrypt_fn; if (ctx->prefetch_enc_fn) ctx->prefetch_enc_fn(); last_iv = iv; for ( ;nblocks; nblocks-- ) { cipher_block_xor(outbuf, inbuf, last_iv, BLOCKSIZE); burn_depth = encrypt_fn (ctx, outbuf, outbuf); last_iv = outbuf; inbuf += BLOCKSIZE; if (!cbc_mac) outbuf += BLOCKSIZE; } if (last_iv != iv) cipher_block_cpy (iv, last_iv, BLOCKSIZE); } if (burn_depth) _gcry_burn_stack (burn_depth + 4 * sizeof(void *)); } /* Bulk encryption of complete blocks in CTR mode. Caller needs to make sure that CTR is aligned on a 16 byte boundary if AESNI; the minimum alignment is for an u32. This function is only intended for the bulk encryption feature of cipher.c. CTR is expected to be of size BLOCKSIZE. */ void _gcry_aes_ctr_enc (void *context, unsigned char *ctr, void *outbuf_arg, const void *inbuf_arg, size_t nblocks) { RIJNDAEL_context *ctx = context; unsigned char *outbuf = outbuf_arg; const unsigned char *inbuf = inbuf_arg; unsigned int burn_depth = 0; if (0) ; #ifdef USE_AESNI else if (ctx->use_aesni) { _gcry_aes_aesni_ctr_enc (ctx, ctr, outbuf, inbuf, nblocks); return; } #endif /*USE_AESNI*/ #ifdef USE_SSSE3 else if (ctx->use_ssse3) { _gcry_aes_ssse3_ctr_enc (ctx, ctr, outbuf, inbuf, nblocks); return; } #endif /*USE_SSSE3*/ #ifdef USE_ARM_CE else if (ctx->use_arm_ce) { _gcry_aes_armv8_ce_ctr_enc (ctx, ctr, outbuf, inbuf, nblocks); return; } #endif /*USE_ARM_CE*/ else { union { unsigned char x1[16] ATTR_ALIGNED_16; u32 x32[4]; } tmp; rijndael_cryptfn_t encrypt_fn = ctx->encrypt_fn; if (ctx->prefetch_enc_fn) ctx->prefetch_enc_fn(); for ( ;nblocks; nblocks-- ) { /* Encrypt the counter. */ burn_depth = encrypt_fn (ctx, tmp.x1, ctr); /* XOR the input with the encrypted counter and store in output. */ cipher_block_xor(outbuf, tmp.x1, inbuf, BLOCKSIZE); outbuf += BLOCKSIZE; inbuf += BLOCKSIZE; /* Increment the counter. */ cipher_block_add(ctr, 1, BLOCKSIZE); } wipememory(&tmp, sizeof(tmp)); } if (burn_depth) _gcry_burn_stack (burn_depth + 4 * sizeof(void *)); } #if !defined(USE_ARM_ASM) && !defined(USE_AMD64_ASM) /* Decrypt one block. A and B may be the same. */ static unsigned int do_decrypt_fn (const RIJNDAEL_context *ctx, unsigned char *b, const unsigned char *a) { #define rk (ctx->keyschdec32) int rounds = ctx->rounds; int r; u32 sa[4]; u32 sb[4]; sb[0] = buf_get_le32(a + 0); sb[1] = buf_get_le32(a + 4); sb[2] = buf_get_le32(a + 8); sb[3] = buf_get_le32(a + 12); sa[0] = sb[0] ^ rk[rounds][0]; sa[1] = sb[1] ^ rk[rounds][1]; sa[2] = sb[2] ^ rk[rounds][2]; sa[3] = sb[3] ^ rk[rounds][3]; for (r = rounds - 1; r > 1; r--) { sb[0] = rol(decT[(byte)(sa[0] >> (0 * 8))], (0 * 8)); sb[1] = rol(decT[(byte)(sa[0] >> (1 * 8))], (1 * 8)); sb[2] = rol(decT[(byte)(sa[0] >> (2 * 8))], (2 * 8)); sb[3] = rol(decT[(byte)(sa[0] >> (3 * 8))], (3 * 8)); sa[0] = rk[r][0] ^ sb[0]; sb[1] ^= rol(decT[(byte)(sa[1] >> (0 * 8))], (0 * 8)); sb[2] ^= rol(decT[(byte)(sa[1] >> (1 * 8))], (1 * 8)); sb[3] ^= rol(decT[(byte)(sa[1] >> (2 * 8))], (2 * 8)); sa[0] ^= rol(decT[(byte)(sa[1] >> (3 * 8))], (3 * 8)); sa[1] = rk[r][1] ^ sb[1]; sb[2] ^= rol(decT[(byte)(sa[2] >> (0 * 8))], (0 * 8)); sb[3] ^= rol(decT[(byte)(sa[2] >> (1 * 8))], (1 * 8)); sa[0] ^= rol(decT[(byte)(sa[2] >> (2 * 8))], (2 * 8)); sa[1] ^= rol(decT[(byte)(sa[2] >> (3 * 8))], (3 * 8)); sa[2] = rk[r][2] ^ sb[2]; sb[3] ^= rol(decT[(byte)(sa[3] >> (0 * 8))], (0 * 8)); sa[0] ^= rol(decT[(byte)(sa[3] >> (1 * 8))], (1 * 8)); sa[1] ^= rol(decT[(byte)(sa[3] >> (2 * 8))], (2 * 8)); sa[2] ^= rol(decT[(byte)(sa[3] >> (3 * 8))], (3 * 8)); sa[3] = rk[r][3] ^ sb[3]; r--; sb[0] = rol(decT[(byte)(sa[0] >> (0 * 8))], (0 * 8)); sb[1] = rol(decT[(byte)(sa[0] >> (1 * 8))], (1 * 8)); sb[2] = rol(decT[(byte)(sa[0] >> (2 * 8))], (2 * 8)); sb[3] = rol(decT[(byte)(sa[0] >> (3 * 8))], (3 * 8)); sa[0] = rk[r][0] ^ sb[0]; sb[1] ^= rol(decT[(byte)(sa[1] >> (0 * 8))], (0 * 8)); sb[2] ^= rol(decT[(byte)(sa[1] >> (1 * 8))], (1 * 8)); sb[3] ^= rol(decT[(byte)(sa[1] >> (2 * 8))], (2 * 8)); sa[0] ^= rol(decT[(byte)(sa[1] >> (3 * 8))], (3 * 8)); sa[1] = rk[r][1] ^ sb[1]; sb[2] ^= rol(decT[(byte)(sa[2] >> (0 * 8))], (0 * 8)); sb[3] ^= rol(decT[(byte)(sa[2] >> (1 * 8))], (1 * 8)); sa[0] ^= rol(decT[(byte)(sa[2] >> (2 * 8))], (2 * 8)); sa[1] ^= rol(decT[(byte)(sa[2] >> (3 * 8))], (3 * 8)); sa[2] = rk[r][2] ^ sb[2]; sb[3] ^= rol(decT[(byte)(sa[3] >> (0 * 8))], (0 * 8)); sa[0] ^= rol(decT[(byte)(sa[3] >> (1 * 8))], (1 * 8)); sa[1] ^= rol(decT[(byte)(sa[3] >> (2 * 8))], (2 * 8)); sa[2] ^= rol(decT[(byte)(sa[3] >> (3 * 8))], (3 * 8)); sa[3] = rk[r][3] ^ sb[3]; } sb[0] = rol(decT[(byte)(sa[0] >> (0 * 8))], (0 * 8)); sb[1] = rol(decT[(byte)(sa[0] >> (1 * 8))], (1 * 8)); sb[2] = rol(decT[(byte)(sa[0] >> (2 * 8))], (2 * 8)); sb[3] = rol(decT[(byte)(sa[0] >> (3 * 8))], (3 * 8)); sa[0] = rk[1][0] ^ sb[0]; sb[1] ^= rol(decT[(byte)(sa[1] >> (0 * 8))], (0 * 8)); sb[2] ^= rol(decT[(byte)(sa[1] >> (1 * 8))], (1 * 8)); sb[3] ^= rol(decT[(byte)(sa[1] >> (2 * 8))], (2 * 8)); sa[0] ^= rol(decT[(byte)(sa[1] >> (3 * 8))], (3 * 8)); sa[1] = rk[1][1] ^ sb[1]; sb[2] ^= rol(decT[(byte)(sa[2] >> (0 * 8))], (0 * 8)); sb[3] ^= rol(decT[(byte)(sa[2] >> (1 * 8))], (1 * 8)); sa[0] ^= rol(decT[(byte)(sa[2] >> (2 * 8))], (2 * 8)); sa[1] ^= rol(decT[(byte)(sa[2] >> (3 * 8))], (3 * 8)); sa[2] = rk[1][2] ^ sb[2]; sb[3] ^= rol(decT[(byte)(sa[3] >> (0 * 8))], (0 * 8)); sa[0] ^= rol(decT[(byte)(sa[3] >> (1 * 8))], (1 * 8)); sa[1] ^= rol(decT[(byte)(sa[3] >> (2 * 8))], (2 * 8)); sa[2] ^= rol(decT[(byte)(sa[3] >> (3 * 8))], (3 * 8)); sa[3] = rk[1][3] ^ sb[3]; /* Last round is special. */ sb[0] = inv_sbox[(byte)(sa[0] >> (0 * 8))] << (0 * 8); sb[1] = inv_sbox[(byte)(sa[0] >> (1 * 8))] << (1 * 8); sb[2] = inv_sbox[(byte)(sa[0] >> (2 * 8))] << (2 * 8); sb[3] = inv_sbox[(byte)(sa[0] >> (3 * 8))] << (3 * 8); sa[0] = sb[0] ^ rk[0][0]; sb[1] ^= inv_sbox[(byte)(sa[1] >> (0 * 8))] << (0 * 8); sb[2] ^= inv_sbox[(byte)(sa[1] >> (1 * 8))] << (1 * 8); sb[3] ^= inv_sbox[(byte)(sa[1] >> (2 * 8))] << (2 * 8); sa[0] ^= inv_sbox[(byte)(sa[1] >> (3 * 8))] << (3 * 8); sa[1] = sb[1] ^ rk[0][1]; sb[2] ^= inv_sbox[(byte)(sa[2] >> (0 * 8))] << (0 * 8); sb[3] ^= inv_sbox[(byte)(sa[2] >> (1 * 8))] << (1 * 8); sa[0] ^= inv_sbox[(byte)(sa[2] >> (2 * 8))] << (2 * 8); sa[1] ^= inv_sbox[(byte)(sa[2] >> (3 * 8))] << (3 * 8); sa[2] = sb[2] ^ rk[0][2]; sb[3] ^= inv_sbox[(byte)(sa[3] >> (0 * 8))] << (0 * 8); sa[0] ^= inv_sbox[(byte)(sa[3] >> (1 * 8))] << (1 * 8); sa[1] ^= inv_sbox[(byte)(sa[3] >> (2 * 8))] << (2 * 8); sa[2] ^= inv_sbox[(byte)(sa[3] >> (3 * 8))] << (3 * 8); sa[3] = sb[3] ^ rk[0][3]; buf_put_le32(b + 0, sa[0]); buf_put_le32(b + 4, sa[1]); buf_put_le32(b + 8, sa[2]); buf_put_le32(b + 12, sa[3]); #undef rk return (56+2*sizeof(int)); } #endif /*!USE_ARM_ASM && !USE_AMD64_ASM*/ /* Decrypt one block. AX and BX may be the same. */ static unsigned int do_decrypt (const RIJNDAEL_context *ctx, unsigned char *bx, const unsigned char *ax) { #ifdef USE_AMD64_ASM return _gcry_aes_amd64_decrypt_block(ctx->keyschdec, bx, ax, ctx->rounds, dec_tables.T); #elif defined(USE_ARM_ASM) return _gcry_aes_arm_decrypt_block(ctx->keyschdec, bx, ax, ctx->rounds, dec_tables.T); #else return do_decrypt_fn (ctx, bx, ax); #endif /*!USE_ARM_ASM && !USE_AMD64_ASM*/ } static inline void check_decryption_preparation (RIJNDAEL_context *ctx) { if ( !ctx->decryption_prepared ) { prepare_decryption ( ctx ); ctx->decryption_prepared = 1; } } static unsigned int rijndael_decrypt (void *context, byte *b, const byte *a) { RIJNDAEL_context *ctx = context; check_decryption_preparation (ctx); if (ctx->prefetch_dec_fn) ctx->prefetch_dec_fn(); return ctx->decrypt_fn (ctx, b, a); } /* Bulk decryption of complete blocks in CFB mode. Caller needs to make sure that IV is aligned on an unsigned long boundary. This function is only intended for the bulk encryption feature of cipher.c. */ void _gcry_aes_cfb_dec (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks) { RIJNDAEL_context *ctx = context; unsigned char *outbuf = outbuf_arg; const unsigned char *inbuf = inbuf_arg; unsigned int burn_depth = 0; if (0) ; #ifdef USE_AESNI else if (ctx->use_aesni) { _gcry_aes_aesni_cfb_dec (ctx, iv, outbuf, inbuf, nblocks); return; } #endif /*USE_AESNI*/ #ifdef USE_SSSE3 else if (ctx->use_ssse3) { _gcry_aes_ssse3_cfb_dec (ctx, iv, outbuf, inbuf, nblocks); return; } #endif /*USE_SSSE3*/ #ifdef USE_ARM_CE else if (ctx->use_arm_ce) { _gcry_aes_armv8_ce_cfb_dec (ctx, iv, outbuf, inbuf, nblocks); return; } #endif /*USE_ARM_CE*/ else { rijndael_cryptfn_t encrypt_fn = ctx->encrypt_fn; if (ctx->prefetch_enc_fn) ctx->prefetch_enc_fn(); for ( ;nblocks; nblocks-- ) { burn_depth = encrypt_fn (ctx, iv, iv); cipher_block_xor_n_copy(outbuf, iv, inbuf, BLOCKSIZE); outbuf += BLOCKSIZE; inbuf += BLOCKSIZE; } } if (burn_depth) _gcry_burn_stack (burn_depth + 4 * sizeof(void *)); } /* Bulk decryption of complete blocks in CBC mode. Caller needs to make sure that IV is aligned on an unsigned long boundary. This function is only intended for the bulk encryption feature of cipher.c. */ void _gcry_aes_cbc_dec (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks) { RIJNDAEL_context *ctx = context; unsigned char *outbuf = outbuf_arg; const unsigned char *inbuf = inbuf_arg; unsigned int burn_depth = 0; if (0) ; #ifdef USE_AESNI else if (ctx->use_aesni) { _gcry_aes_aesni_cbc_dec (ctx, iv, outbuf, inbuf, nblocks); return; } #endif /*USE_AESNI*/ #ifdef USE_SSSE3 else if (ctx->use_ssse3) { _gcry_aes_ssse3_cbc_dec (ctx, iv, outbuf, inbuf, nblocks); return; } #endif /*USE_SSSE3*/ #ifdef USE_ARM_CE else if (ctx->use_arm_ce) { _gcry_aes_armv8_ce_cbc_dec (ctx, iv, outbuf, inbuf, nblocks); return; } #endif /*USE_ARM_CE*/ else { unsigned char savebuf[BLOCKSIZE] ATTR_ALIGNED_16; rijndael_cryptfn_t decrypt_fn = ctx->decrypt_fn; check_decryption_preparation (ctx); if (ctx->prefetch_dec_fn) ctx->prefetch_dec_fn(); for ( ;nblocks; nblocks-- ) { /* INBUF is needed later and it may be identical to OUTBUF, so store the intermediate result to SAVEBUF. */ burn_depth = decrypt_fn (ctx, savebuf, inbuf); cipher_block_xor_n_copy_2(outbuf, savebuf, iv, inbuf, BLOCKSIZE); inbuf += BLOCKSIZE; outbuf += BLOCKSIZE; } wipememory(savebuf, sizeof(savebuf)); } if (burn_depth) _gcry_burn_stack (burn_depth + 4 * sizeof(void *)); } /* Bulk encryption/decryption of complete blocks in OCB mode. */ size_t _gcry_aes_ocb_crypt (gcry_cipher_hd_t c, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int encrypt) { RIJNDAEL_context *ctx = (void *)&c->context.c; unsigned char *outbuf = outbuf_arg; const unsigned char *inbuf = inbuf_arg; unsigned int burn_depth = 0; if (0) ; #ifdef USE_AESNI else if (ctx->use_aesni) { return _gcry_aes_aesni_ocb_crypt (c, outbuf, inbuf, nblocks, encrypt); } #endif /*USE_AESNI*/ #ifdef USE_SSSE3 else if (ctx->use_ssse3) { return _gcry_aes_ssse3_ocb_crypt (c, outbuf, inbuf, nblocks, encrypt); } #endif /*USE_SSSE3*/ #ifdef USE_ARM_CE else if (ctx->use_arm_ce) { return _gcry_aes_armv8_ce_ocb_crypt (c, outbuf, inbuf, nblocks, encrypt); } #endif /*USE_ARM_CE*/ else if (encrypt) { union { unsigned char x1[16] ATTR_ALIGNED_16; u32 x32[4]; } l_tmp; rijndael_cryptfn_t encrypt_fn = ctx->encrypt_fn; if (ctx->prefetch_enc_fn) ctx->prefetch_enc_fn(); for ( ;nblocks; nblocks-- ) { u64 i = ++c->u_mode.ocb.data_nblocks; const unsigned char *l = ocb_get_l(c, i); /* Offset_i = Offset_{i-1} xor L_{ntz(i)} */ cipher_block_xor_1 (c->u_iv.iv, l, BLOCKSIZE); cipher_block_cpy (l_tmp.x1, inbuf, BLOCKSIZE); /* Checksum_i = Checksum_{i-1} xor P_i */ cipher_block_xor_1 (c->u_ctr.ctr, l_tmp.x1, BLOCKSIZE); /* C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) */ cipher_block_xor_1 (l_tmp.x1, c->u_iv.iv, BLOCKSIZE); burn_depth = encrypt_fn (ctx, l_tmp.x1, l_tmp.x1); cipher_block_xor_1 (l_tmp.x1, c->u_iv.iv, BLOCKSIZE); cipher_block_cpy (outbuf, l_tmp.x1, BLOCKSIZE); inbuf += BLOCKSIZE; outbuf += BLOCKSIZE; } } else { union { unsigned char x1[16] ATTR_ALIGNED_16; u32 x32[4]; } l_tmp; rijndael_cryptfn_t decrypt_fn = ctx->decrypt_fn; check_decryption_preparation (ctx); if (ctx->prefetch_dec_fn) ctx->prefetch_dec_fn(); for ( ;nblocks; nblocks-- ) { u64 i = ++c->u_mode.ocb.data_nblocks; const unsigned char *l = ocb_get_l(c, i); /* Offset_i = Offset_{i-1} xor L_{ntz(i)} */ cipher_block_xor_1 (c->u_iv.iv, l, BLOCKSIZE); cipher_block_cpy (l_tmp.x1, inbuf, BLOCKSIZE); /* C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) */ cipher_block_xor_1 (l_tmp.x1, c->u_iv.iv, BLOCKSIZE); burn_depth = decrypt_fn (ctx, l_tmp.x1, l_tmp.x1); cipher_block_xor_1 (l_tmp.x1, c->u_iv.iv, BLOCKSIZE); /* Checksum_i = Checksum_{i-1} xor P_i */ cipher_block_xor_1 (c->u_ctr.ctr, l_tmp.x1, BLOCKSIZE); cipher_block_cpy (outbuf, l_tmp.x1, BLOCKSIZE); inbuf += BLOCKSIZE; outbuf += BLOCKSIZE; } } if (burn_depth) _gcry_burn_stack (burn_depth + 4 * sizeof(void *)); return 0; } /* Bulk authentication of complete blocks in OCB mode. */ size_t _gcry_aes_ocb_auth (gcry_cipher_hd_t c, const void *abuf_arg, size_t nblocks) { RIJNDAEL_context *ctx = (void *)&c->context.c; const unsigned char *abuf = abuf_arg; unsigned int burn_depth = 0; if (0) ; #ifdef USE_AESNI else if (ctx->use_aesni) { return _gcry_aes_aesni_ocb_auth (c, abuf, nblocks); } #endif /*USE_AESNI*/ #ifdef USE_SSSE3 else if (ctx->use_ssse3) { return _gcry_aes_ssse3_ocb_auth (c, abuf, nblocks); } #endif /*USE_SSSE3*/ #ifdef USE_ARM_CE else if (ctx->use_arm_ce) { return _gcry_aes_armv8_ce_ocb_auth (c, abuf, nblocks); } #endif /*USE_ARM_CE*/ else { union { unsigned char x1[16] ATTR_ALIGNED_16; u32 x32[4]; } l_tmp; rijndael_cryptfn_t encrypt_fn = ctx->encrypt_fn; if (ctx->prefetch_enc_fn) ctx->prefetch_enc_fn(); for ( ;nblocks; nblocks-- ) { u64 i = ++c->u_mode.ocb.aad_nblocks; const unsigned char *l = ocb_get_l(c, i); /* Offset_i = Offset_{i-1} xor L_{ntz(i)} */ cipher_block_xor_1 (c->u_mode.ocb.aad_offset, l, BLOCKSIZE); /* Sum_i = Sum_{i-1} xor ENCIPHER(K, A_i xor Offset_i) */ cipher_block_xor (l_tmp.x1, c->u_mode.ocb.aad_offset, abuf, BLOCKSIZE); burn_depth = encrypt_fn (ctx, l_tmp.x1, l_tmp.x1); cipher_block_xor_1 (c->u_mode.ocb.aad_sum, l_tmp.x1, BLOCKSIZE); abuf += BLOCKSIZE; } wipememory(&l_tmp, sizeof(l_tmp)); } if (burn_depth) _gcry_burn_stack (burn_depth + 4 * sizeof(void *)); return 0; } /* Bulk encryption/decryption of complete blocks in XTS mode. */ void _gcry_aes_xts_crypt (void *context, unsigned char *tweak, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int encrypt) { RIJNDAEL_context *ctx = context; unsigned char *outbuf = outbuf_arg; const unsigned char *inbuf = inbuf_arg; unsigned int burn_depth = 0; rijndael_cryptfn_t crypt_fn; u64 tweak_lo, tweak_hi, tweak_next_lo, tweak_next_hi, tmp_lo, tmp_hi, carry; if (0) ; #ifdef USE_AESNI else if (ctx->use_aesni) { _gcry_aes_aesni_xts_crypt (ctx, tweak, outbuf, inbuf, nblocks, encrypt); return; } #endif /*USE_AESNI*/ #ifdef USE_ARM_CE else if (ctx->use_arm_ce) { _gcry_aes_armv8_ce_xts_crypt (ctx, tweak, outbuf, inbuf, nblocks, encrypt); return; } #endif /*USE_ARM_CE*/ else { if (encrypt) { if (ctx->prefetch_enc_fn) ctx->prefetch_enc_fn(); crypt_fn = ctx->encrypt_fn; } else { check_decryption_preparation (ctx); if (ctx->prefetch_dec_fn) ctx->prefetch_dec_fn(); crypt_fn = ctx->decrypt_fn; } tweak_next_lo = buf_get_le64 (tweak + 0); tweak_next_hi = buf_get_le64 (tweak + 8); while (nblocks) { tweak_lo = tweak_next_lo; tweak_hi = tweak_next_hi; /* Xor-Encrypt/Decrypt-Xor block. */ tmp_lo = buf_get_le64 (inbuf + 0) ^ tweak_lo; tmp_hi = buf_get_le64 (inbuf + 8) ^ tweak_hi; buf_put_le64 (outbuf + 0, tmp_lo); buf_put_le64 (outbuf + 8, tmp_hi); /* Generate next tweak. */ carry = -(tweak_next_hi >> 63) & 0x87; tweak_next_hi = (tweak_next_hi << 1) + (tweak_next_lo >> 63); tweak_next_lo = (tweak_next_lo << 1) ^ carry; burn_depth = crypt_fn (ctx, outbuf, outbuf); buf_put_le64 (outbuf + 0, buf_get_le64 (outbuf + 0) ^ tweak_lo); buf_put_le64 (outbuf + 8, buf_get_le64 (outbuf + 8) ^ tweak_hi); outbuf += GCRY_XTS_BLOCK_LEN; inbuf += GCRY_XTS_BLOCK_LEN; nblocks--; } buf_put_le64 (tweak + 0, tweak_next_lo); buf_put_le64 (tweak + 8, tweak_next_hi); } if (burn_depth) _gcry_burn_stack (burn_depth + 5 * sizeof(void *)); } /* Run the self-tests for AES 128. Returns NULL on success. */ static const char* selftest_basic_128 (void) { RIJNDAEL_context *ctx; unsigned char *ctxmem; unsigned char scratch[16]; /* The test vectors are from the AES supplied ones; more or less randomly taken from ecb_tbl.txt (I=42,81,14) */ #if 1 static const unsigned char plaintext_128[16] = { 0x01,0x4B,0xAF,0x22,0x78,0xA6,0x9D,0x33, 0x1D,0x51,0x80,0x10,0x36,0x43,0xE9,0x9A }; static const unsigned char key_128[16] = { 0xE8,0xE9,0xEA,0xEB,0xED,0xEE,0xEF,0xF0, 0xF2,0xF3,0xF4,0xF5,0xF7,0xF8,0xF9,0xFA }; static const unsigned char ciphertext_128[16] = { 0x67,0x43,0xC3,0xD1,0x51,0x9A,0xB4,0xF2, 0xCD,0x9A,0x78,0xAB,0x09,0xA5,0x11,0xBD }; #else /* Test vectors from fips-197, appendix C. */ # warning debug test vectors in use static const unsigned char plaintext_128[16] = { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77, 0x88,0x99,0xaa,0xbb,0xcc,0xdd,0xee,0xff }; static const unsigned char key_128[16] = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07, 0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f /* 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, */ /* 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c */ }; static const unsigned char ciphertext_128[16] = { 0x69,0xc4,0xe0,0xd8,0x6a,0x7b,0x04,0x30, 0xd8,0xcd,0xb7,0x80,0x70,0xb4,0xc5,0x5a }; #endif /* Because gcc/ld can only align the CTX struct on 8 bytes on the stack, we need to allocate that context on the heap. */ ctx = _gcry_cipher_selftest_alloc_ctx (sizeof *ctx, &ctxmem); if (!ctx) return "failed to allocate memory"; rijndael_setkey (ctx, key_128, sizeof (key_128), NULL); rijndael_encrypt (ctx, scratch, plaintext_128); if (memcmp (scratch, ciphertext_128, sizeof (ciphertext_128))) { xfree (ctxmem); return "AES-128 test encryption failed."; } rijndael_decrypt (ctx, scratch, scratch); xfree (ctxmem); if (memcmp (scratch, plaintext_128, sizeof (plaintext_128))) return "AES-128 test decryption failed."; return NULL; } /* Run the self-tests for AES 192. Returns NULL on success. */ static const char* selftest_basic_192 (void) { RIJNDAEL_context *ctx; unsigned char *ctxmem; unsigned char scratch[16]; static unsigned char plaintext_192[16] = { 0x76,0x77,0x74,0x75,0xF1,0xF2,0xF3,0xF4, 0xF8,0xF9,0xE6,0xE7,0x77,0x70,0x71,0x72 }; static unsigned char key_192[24] = { 0x04,0x05,0x06,0x07,0x09,0x0A,0x0B,0x0C, 0x0E,0x0F,0x10,0x11,0x13,0x14,0x15,0x16, 0x18,0x19,0x1A,0x1B,0x1D,0x1E,0x1F,0x20 }; static const unsigned char ciphertext_192[16] = { 0x5D,0x1E,0xF2,0x0D,0xCE,0xD6,0xBC,0xBC, 0x12,0x13,0x1A,0xC7,0xC5,0x47,0x88,0xAA }; ctx = _gcry_cipher_selftest_alloc_ctx (sizeof *ctx, &ctxmem); if (!ctx) return "failed to allocate memory"; rijndael_setkey (ctx, key_192, sizeof(key_192), NULL); rijndael_encrypt (ctx, scratch, plaintext_192); if (memcmp (scratch, ciphertext_192, sizeof (ciphertext_192))) { xfree (ctxmem); return "AES-192 test encryption failed."; } rijndael_decrypt (ctx, scratch, scratch); xfree (ctxmem); if (memcmp (scratch, plaintext_192, sizeof (plaintext_192))) return "AES-192 test decryption failed."; return NULL; } /* Run the self-tests for AES 256. Returns NULL on success. */ static const char* selftest_basic_256 (void) { RIJNDAEL_context *ctx; unsigned char *ctxmem; unsigned char scratch[16]; static unsigned char plaintext_256[16] = { 0x06,0x9A,0x00,0x7F,0xC7,0x6A,0x45,0x9F, 0x98,0xBA,0xF9,0x17,0xFE,0xDF,0x95,0x21 }; static unsigned char key_256[32] = { 0x08,0x09,0x0A,0x0B,0x0D,0x0E,0x0F,0x10, 0x12,0x13,0x14,0x15,0x17,0x18,0x19,0x1A, 0x1C,0x1D,0x1E,0x1F,0x21,0x22,0x23,0x24, 0x26,0x27,0x28,0x29,0x2B,0x2C,0x2D,0x2E }; static const unsigned char ciphertext_256[16] = { 0x08,0x0E,0x95,0x17,0xEB,0x16,0x77,0x71, 0x9A,0xCF,0x72,0x80,0x86,0x04,0x0A,0xE3 }; ctx = _gcry_cipher_selftest_alloc_ctx (sizeof *ctx, &ctxmem); if (!ctx) return "failed to allocate memory"; rijndael_setkey (ctx, key_256, sizeof(key_256), NULL); rijndael_encrypt (ctx, scratch, plaintext_256); if (memcmp (scratch, ciphertext_256, sizeof (ciphertext_256))) { xfree (ctxmem); return "AES-256 test encryption failed."; } rijndael_decrypt (ctx, scratch, scratch); xfree (ctxmem); if (memcmp (scratch, plaintext_256, sizeof (plaintext_256))) return "AES-256 test decryption failed."; return NULL; } /* Run the self-tests for AES-CTR-128, tests IV increment of bulk CTR encryption. Returns NULL on success. */ static const char* selftest_ctr_128 (void) { const int nblocks = 8+1; const int blocksize = BLOCKSIZE; const int context_size = sizeof(RIJNDAEL_context); return _gcry_selftest_helper_ctr("AES", &rijndael_setkey, &rijndael_encrypt, &_gcry_aes_ctr_enc, nblocks, blocksize, context_size); } /* Run the self-tests for AES-CBC-128, tests bulk CBC decryption. Returns NULL on success. */ static const char* selftest_cbc_128 (void) { const int nblocks = 8+2; const int blocksize = BLOCKSIZE; const int context_size = sizeof(RIJNDAEL_context); return _gcry_selftest_helper_cbc("AES", &rijndael_setkey, &rijndael_encrypt, &_gcry_aes_cbc_dec, nblocks, blocksize, context_size); } /* Run the self-tests for AES-CFB-128, tests bulk CFB decryption. Returns NULL on success. */ static const char* selftest_cfb_128 (void) { const int nblocks = 8+2; const int blocksize = BLOCKSIZE; const int context_size = sizeof(RIJNDAEL_context); return _gcry_selftest_helper_cfb("AES", &rijndael_setkey, &rijndael_encrypt, &_gcry_aes_cfb_dec, nblocks, blocksize, context_size); } /* Run all the self-tests and return NULL on success. This function is used for the on-the-fly self-tests. */ static const char * selftest (void) { const char *r; if ( (r = selftest_basic_128 ()) || (r = selftest_basic_192 ()) || (r = selftest_basic_256 ()) ) return r; if ( (r = selftest_ctr_128 ()) ) return r; if ( (r = selftest_cbc_128 ()) ) return r; if ( (r = selftest_cfb_128 ()) ) return r; return r; } /* SP800-38a.pdf for AES-128. */ static const char * selftest_fips_128_38a (int requested_mode) { static const struct tv { int mode; const unsigned char key[16]; const unsigned char iv[16]; struct { const unsigned char input[16]; const unsigned char output[16]; } data[4]; } tv[2] = { { GCRY_CIPHER_MODE_CFB, /* F.3.13, CFB128-AES128 */ { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c }, { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }, { { { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a }, { 0x3b, 0x3f, 0xd9, 0x2e, 0xb7, 0x2d, 0xad, 0x20, 0x33, 0x34, 0x49, 0xf8, 0xe8, 0x3c, 0xfb, 0x4a } }, { { 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51 }, { 0xc8, 0xa6, 0x45, 0x37, 0xa0, 0xb3, 0xa9, 0x3f, 0xcd, 0xe3, 0xcd, 0xad, 0x9f, 0x1c, 0xe5, 0x8b } }, { { 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef }, { 0x26, 0x75, 0x1f, 0x67, 0xa3, 0xcb, 0xb1, 0x40, 0xb1, 0x80, 0x8c, 0xf1, 0x87, 0xa4, 0xf4, 0xdf } }, { { 0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10 }, { 0xc0, 0x4b, 0x05, 0x35, 0x7c, 0x5d, 0x1c, 0x0e, 0xea, 0xc4, 0xc6, 0x6f, 0x9f, 0xf7, 0xf2, 0xe6 } } } }, { GCRY_CIPHER_MODE_OFB, { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c }, { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }, { { { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a }, { 0x3b, 0x3f, 0xd9, 0x2e, 0xb7, 0x2d, 0xad, 0x20, 0x33, 0x34, 0x49, 0xf8, 0xe8, 0x3c, 0xfb, 0x4a } }, { { 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51 }, { 0x77, 0x89, 0x50, 0x8d, 0x16, 0x91, 0x8f, 0x03, 0xf5, 0x3c, 0x52, 0xda, 0xc5, 0x4e, 0xd8, 0x25 } }, { { 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef }, { 0x97, 0x40, 0x05, 0x1e, 0x9c, 0x5f, 0xec, 0xf6, 0x43, 0x44, 0xf7, 0xa8, 0x22, 0x60, 0xed, 0xcc } }, { { 0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10 }, { 0x30, 0x4c, 0x65, 0x28, 0xf6, 0x59, 0xc7, 0x78, 0x66, 0xa5, 0x10, 0xd9, 0xc1, 0xd6, 0xae, 0x5e } }, } } }; unsigned char scratch[16]; gpg_error_t err; int tvi, idx; gcry_cipher_hd_t hdenc = NULL; gcry_cipher_hd_t hddec = NULL; #define Fail(a) do { \ _gcry_cipher_close (hdenc); \ _gcry_cipher_close (hddec); \ return a; \ } while (0) gcry_assert (sizeof tv[0].data[0].input == sizeof scratch); gcry_assert (sizeof tv[0].data[0].output == sizeof scratch); for (tvi=0; tvi < DIM (tv); tvi++) if (tv[tvi].mode == requested_mode) break; if (tvi == DIM (tv)) Fail ("no test data for this mode"); err = _gcry_cipher_open (&hdenc, GCRY_CIPHER_AES, tv[tvi].mode, 0); if (err) Fail ("open"); err = _gcry_cipher_open (&hddec, GCRY_CIPHER_AES, tv[tvi].mode, 0); if (err) Fail ("open"); err = _gcry_cipher_setkey (hdenc, tv[tvi].key, sizeof tv[tvi].key); if (!err) err = _gcry_cipher_setkey (hddec, tv[tvi].key, sizeof tv[tvi].key); if (err) Fail ("set key"); err = _gcry_cipher_setiv (hdenc, tv[tvi].iv, sizeof tv[tvi].iv); if (!err) err = _gcry_cipher_setiv (hddec, tv[tvi].iv, sizeof tv[tvi].iv); if (err) Fail ("set IV"); for (idx=0; idx < DIM (tv[tvi].data); idx++) { err = _gcry_cipher_encrypt (hdenc, scratch, sizeof scratch, tv[tvi].data[idx].input, sizeof tv[tvi].data[idx].input); if (err) Fail ("encrypt command"); if (memcmp (scratch, tv[tvi].data[idx].output, sizeof scratch)) Fail ("encrypt mismatch"); err = _gcry_cipher_decrypt (hddec, scratch, sizeof scratch, tv[tvi].data[idx].output, sizeof tv[tvi].data[idx].output); if (err) Fail ("decrypt command"); if (memcmp (scratch, tv[tvi].data[idx].input, sizeof scratch)) Fail ("decrypt mismatch"); } #undef Fail _gcry_cipher_close (hdenc); _gcry_cipher_close (hddec); return NULL; } /* Complete selftest for AES-128 with all modes and driver code. */ static gpg_err_code_t selftest_fips_128 (int extended, selftest_report_func_t report) { const char *what; const char *errtxt; what = "low-level"; errtxt = selftest_basic_128 (); if (errtxt) goto failed; if (extended) { what = "cfb"; errtxt = selftest_fips_128_38a (GCRY_CIPHER_MODE_CFB); if (errtxt) goto failed; what = "ofb"; errtxt = selftest_fips_128_38a (GCRY_CIPHER_MODE_OFB); if (errtxt) goto failed; } return 0; /* Succeeded. */ failed: if (report) report ("cipher", GCRY_CIPHER_AES128, what, errtxt); return GPG_ERR_SELFTEST_FAILED; } /* Complete selftest for AES-192. */ static gpg_err_code_t selftest_fips_192 (int extended, selftest_report_func_t report) { const char *what; const char *errtxt; (void)extended; /* No extended tests available. */ what = "low-level"; errtxt = selftest_basic_192 (); if (errtxt) goto failed; return 0; /* Succeeded. */ failed: if (report) report ("cipher", GCRY_CIPHER_AES192, what, errtxt); return GPG_ERR_SELFTEST_FAILED; } /* Complete selftest for AES-256. */ static gpg_err_code_t selftest_fips_256 (int extended, selftest_report_func_t report) { const char *what; const char *errtxt; (void)extended; /* No extended tests available. */ what = "low-level"; errtxt = selftest_basic_256 (); if (errtxt) goto failed; return 0; /* Succeeded. */ failed: if (report) report ("cipher", GCRY_CIPHER_AES256, what, errtxt); return GPG_ERR_SELFTEST_FAILED; } /* Run a full self-test for ALGO and return 0 on success. */ static gpg_err_code_t run_selftests (int algo, int extended, selftest_report_func_t report) { gpg_err_code_t ec; switch (algo) { case GCRY_CIPHER_AES128: ec = selftest_fips_128 (extended, report); break; case GCRY_CIPHER_AES192: ec = selftest_fips_192 (extended, report); break; case GCRY_CIPHER_AES256: ec = selftest_fips_256 (extended, report); break; default: ec = GPG_ERR_CIPHER_ALGO; break; } return ec; } static const char *rijndael_names[] = { "RIJNDAEL", "AES128", "AES-128", NULL }; static gcry_cipher_oid_spec_t rijndael_oids[] = { { "2.16.840.1.101.3.4.1.1", GCRY_CIPHER_MODE_ECB }, { "2.16.840.1.101.3.4.1.2", GCRY_CIPHER_MODE_CBC }, { "2.16.840.1.101.3.4.1.3", GCRY_CIPHER_MODE_OFB }, { "2.16.840.1.101.3.4.1.4", GCRY_CIPHER_MODE_CFB }, { NULL } }; gcry_cipher_spec_t _gcry_cipher_spec_aes = { GCRY_CIPHER_AES, {0, 1}, "AES", rijndael_names, rijndael_oids, 16, 128, sizeof (RIJNDAEL_context), rijndael_setkey, rijndael_encrypt, rijndael_decrypt, NULL, NULL, run_selftests }; static const char *rijndael192_names[] = { "RIJNDAEL192", "AES-192", NULL }; static gcry_cipher_oid_spec_t rijndael192_oids[] = { { "2.16.840.1.101.3.4.1.21", GCRY_CIPHER_MODE_ECB }, { "2.16.840.1.101.3.4.1.22", GCRY_CIPHER_MODE_CBC }, { "2.16.840.1.101.3.4.1.23", GCRY_CIPHER_MODE_OFB }, { "2.16.840.1.101.3.4.1.24", GCRY_CIPHER_MODE_CFB }, { NULL } }; gcry_cipher_spec_t _gcry_cipher_spec_aes192 = { GCRY_CIPHER_AES192, {0, 1}, "AES192", rijndael192_names, rijndael192_oids, 16, 192, sizeof (RIJNDAEL_context), rijndael_setkey, rijndael_encrypt, rijndael_decrypt, NULL, NULL, run_selftests }; static const char *rijndael256_names[] = { "RIJNDAEL256", "AES-256", NULL }; static gcry_cipher_oid_spec_t rijndael256_oids[] = { { "2.16.840.1.101.3.4.1.41", GCRY_CIPHER_MODE_ECB }, { "2.16.840.1.101.3.4.1.42", GCRY_CIPHER_MODE_CBC }, { "2.16.840.1.101.3.4.1.43", GCRY_CIPHER_MODE_OFB }, { "2.16.840.1.101.3.4.1.44", GCRY_CIPHER_MODE_CFB }, { NULL } }; gcry_cipher_spec_t _gcry_cipher_spec_aes256 = { GCRY_CIPHER_AES256, {0, 1}, "AES256", rijndael256_names, rijndael256_oids, 16, 256, sizeof (RIJNDAEL_context), rijndael_setkey, rijndael_encrypt, rijndael_decrypt, NULL, NULL, run_selftests };
./CrossVul/dataset_final_sorted/CWE-310/c/good_893_2
crossvul-cpp_data_good_3428_0
/* * %CopyrightBegin% * * Copyright Ericsson AB 2010-2011. All Rights Reserved. * * The contents of this file are subject to the Erlang Public License, * Version 1.1, (the "License"); you may not use this file except in * compliance with the License. You should have received a copy of the * Erlang Public License along with this software. If not, it can be * retrieved online at http://www.erlang.org/. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See * the License for the specific language governing rights and limitations * under the License. * * %CopyrightEnd% */ /* * Purpose: Dynamically loadable NIF library for cryptography. * Based on OpenSSL. */ #ifdef __WIN32__ #include <windows.h> #endif #include <stdlib.h> #include <stdio.h> #include <string.h> #include "erl_nif.h" #define OPENSSL_THREAD_DEFINES #include <openssl/opensslconf.h> #include <openssl/crypto.h> #include <openssl/des.h> /* #include <openssl/idea.h> This is not supported on the openssl OTP requires */ #include <openssl/dsa.h> #include <openssl/rsa.h> #include <openssl/aes.h> #include <openssl/md5.h> #include <openssl/md4.h> #include <openssl/sha.h> #include <openssl/bn.h> #include <openssl/objects.h> #include <openssl/rc4.h> #include <openssl/rc2.h> #include <openssl/blowfish.h> #include <openssl/rand.h> #ifdef VALGRIND # include <valgrind/memcheck.h> /* libcrypto mixes supplied buffer contents into its entropy pool, which makes valgrind complain about the use of uninitialized data. We use this valgrind "request" to make sure that no such seemingly undefined data is returned. */ # define ERL_VALGRIND_MAKE_MEM_DEFINED(ptr,size) \ VALGRIND_MAKE_MEM_DEFINED(ptr,size) # define ERL_VALGRIND_ASSERT_MEM_DEFINED(Ptr,Size) \ do { \ int __erl_valgrind_mem_defined = VALGRIND_CHECK_MEM_IS_DEFINED((Ptr),(Size)); \ if (__erl_valgrind_mem_defined != 0) { \ fprintf(stderr,"\r\n####### VALGRIND_ASSSERT(%p,%ld) failed at %s:%d\r\n", \ (Ptr),(long)(Size), __FILE__, __LINE__); \ abort(); \ } \ } while (0) #else # define ERL_VALGRIND_MAKE_MEM_DEFINED(ptr,size) # define ERL_VALGRIND_ASSERT_MEM_DEFINED(ptr,size) #endif #ifdef DEBUG # define ASSERT(e) \ ((void) ((e) ? 1 : (fprintf(stderr,"Assert '%s' failed at %s:%d\n",\ #e, __FILE__, __LINE__), abort(), 0))) #else # define ASSERT(e) ((void) 1) #endif #ifdef __GNUC__ # define INLINE __inline__ #elif defined(__WIN32__) # define INLINE __forceinline #else # define INLINE #endif #define get_int32(s) ((((unsigned char*) (s))[0] << 24) | \ (((unsigned char*) (s))[1] << 16) | \ (((unsigned char*) (s))[2] << 8) | \ (((unsigned char*) (s))[3])) #define put_int32(s,i) \ { (s)[0] = (char)(((i) >> 24) & 0xff);\ (s)[1] = (char)(((i) >> 16) & 0xff);\ (s)[2] = (char)(((i) >> 8) & 0xff);\ (s)[3] = (char)((i) & 0xff);\ } /* NIF interface declarations */ static int load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info); static int reload(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info); static int upgrade(ErlNifEnv* env, void** priv_data, void** old_priv_data, ERL_NIF_TERM load_info); static void unload(ErlNifEnv* env, void* priv_data); /* The NIFs: */ static ERL_NIF_TERM info_lib(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM md5(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM md5_init(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM md5_update(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM md5_final(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM sha(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM sha_init(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM sha_update(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM sha_final(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM md4(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM md4_init(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM md4_update(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM md4_final(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM md5_mac_n(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM sha_mac_n(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM des_cbc_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM des_ecb_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM des_ede3_cbc_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM aes_cfb_128_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM aes_ctr_encrypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM rand_bytes_1(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM strong_rand_bytes_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM rand_bytes_3(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM strong_rand_mpint_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM rand_uniform_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM mod_exp_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM dss_verify(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM rsa_verify(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM aes_cbc_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM exor(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM rc4_encrypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM rc4_set_key(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM rc4_encrypt_with_state(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM rc2_40_cbc_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM rsa_sign_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM dss_sign_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM rsa_public_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM rsa_private_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM dh_generate_parameters_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM dh_check(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM dh_generate_key_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM dh_compute_key_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM bf_cfb64_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM bf_cbc_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM bf_ecb_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); static ERL_NIF_TERM blowfish_ofb64_encrypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); /* openssl callbacks */ #ifdef OPENSSL_THREADS static void locking_function(int mode, int n, const char *file, int line); static unsigned long id_function(void); static struct CRYPTO_dynlock_value* dyn_create_function(const char *file, int line); static void dyn_lock_function(int mode, struct CRYPTO_dynlock_value* ptr, const char *file, int line); static void dyn_destroy_function(struct CRYPTO_dynlock_value *ptr, const char *file, int line); #endif /* OPENSSL_THREADS */ /* helpers */ static void hmac_md5(unsigned char *key, int klen, unsigned char *dbuf, int dlen, unsigned char *hmacbuf); static void hmac_sha1(unsigned char *key, int klen, unsigned char *dbuf, int dlen, unsigned char *hmacbuf); static int library_refc = 0; /* number of users of this dynamic library */ static ErlNifFunc nif_funcs[] = { {"info_lib", 0, info_lib}, {"md5", 1, md5}, {"md5_init", 0, md5_init}, {"md5_update", 2, md5_update}, {"md5_final", 1, md5_final}, {"sha", 1, sha}, {"sha_init", 0, sha_init}, {"sha_update", 2, sha_update}, {"sha_final", 1, sha_final}, {"md4", 1, md4}, {"md4_init", 0, md4_init}, {"md4_update", 2, md4_update}, {"md4_final", 1, md4_final}, {"md5_mac_n", 3, md5_mac_n}, {"sha_mac_n", 3, sha_mac_n}, {"des_cbc_crypt", 4, des_cbc_crypt}, {"des_ecb_crypt", 3, des_ecb_crypt}, {"des_ede3_cbc_crypt", 6, des_ede3_cbc_crypt}, {"aes_cfb_128_crypt", 4, aes_cfb_128_crypt}, {"aes_ctr_encrypt", 3, aes_ctr_encrypt}, {"aes_ctr_decrypt", 3, aes_ctr_encrypt}, {"rand_bytes", 1, rand_bytes_1}, {"strong_rand_bytes_nif", 1, strong_rand_bytes_nif}, {"rand_bytes", 3, rand_bytes_3}, {"strong_rand_mpint_nif", 3, strong_rand_mpint_nif}, {"rand_uniform_nif", 2, rand_uniform_nif}, {"mod_exp_nif", 3, mod_exp_nif}, {"dss_verify", 4, dss_verify}, {"rsa_verify", 4, rsa_verify}, {"aes_cbc_crypt", 4, aes_cbc_crypt}, {"exor", 2, exor}, {"rc4_encrypt", 2, rc4_encrypt}, {"rc4_set_key", 1, rc4_set_key}, {"rc4_encrypt_with_state", 2, rc4_encrypt_with_state}, {"rc2_40_cbc_crypt", 4, rc2_40_cbc_crypt}, {"rsa_sign_nif", 3, rsa_sign_nif}, {"dss_sign_nif", 3, dss_sign_nif}, {"rsa_public_crypt", 4, rsa_public_crypt}, {"rsa_private_crypt", 4, rsa_private_crypt}, {"dh_generate_parameters_nif", 2, dh_generate_parameters_nif}, {"dh_check", 1, dh_check}, {"dh_generate_key_nif", 2, dh_generate_key_nif}, {"dh_compute_key_nif", 3, dh_compute_key_nif}, {"bf_cfb64_crypt", 4, bf_cfb64_crypt}, {"bf_cbc_crypt", 4, bf_cbc_crypt}, {"bf_ecb_crypt", 3, bf_ecb_crypt}, {"blowfish_ofb64_encrypt", 3, blowfish_ofb64_encrypt} }; ERL_NIF_INIT(crypto,nif_funcs,load,reload,upgrade,unload) #define MD5_CTX_LEN (sizeof(MD5_CTX)) #define MD5_LEN 16 #define MD5_LEN_96 12 #define MD4_CTX_LEN (sizeof(MD4_CTX)) #define MD4_LEN 16 #define SHA_CTX_LEN (sizeof(SHA_CTX)) #define SHA_LEN 20 #define SHA_LEN_96 12 #define HMAC_INT_LEN 64 #define HMAC_IPAD 0x36 #define HMAC_OPAD 0x5c static ErlNifRWLock** lock_vec = NULL; /* Static locks used by openssl */ static ERL_NIF_TERM atom_true; static ERL_NIF_TERM atom_false; static ERL_NIF_TERM atom_sha; static ERL_NIF_TERM atom_md5; static ERL_NIF_TERM atom_error; static ERL_NIF_TERM atom_rsa_pkcs1_padding; static ERL_NIF_TERM atom_rsa_pkcs1_oaep_padding; static ERL_NIF_TERM atom_rsa_no_padding; static ERL_NIF_TERM atom_undefined; static ERL_NIF_TERM atom_ok; static ERL_NIF_TERM atom_not_prime; static ERL_NIF_TERM atom_not_strong_prime; static ERL_NIF_TERM atom_unable_to_check_generator; static ERL_NIF_TERM atom_not_suitable_generator; static ERL_NIF_TERM atom_check_failed; static ERL_NIF_TERM atom_unknown; static ERL_NIF_TERM atom_none; static int is_ok_load_info(ErlNifEnv* env, ERL_NIF_TERM load_info) { int i; return enif_get_int(env,load_info,&i) && i == 101; } static void* crypto_alloc(size_t size) { return enif_alloc(size); } static void* crypto_realloc(void* ptr, size_t size) { return enif_realloc(ptr, size); } static void crypto_free(void* ptr) { enif_free(ptr); } static int load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info) { ErlNifSysInfo sys_info; CRYPTO_set_mem_functions(crypto_alloc, crypto_realloc, crypto_free); if (!is_ok_load_info(env, load_info)) { return -1; } #ifdef OPENSSL_THREADS enif_system_info(&sys_info, sizeof(sys_info)); if (sys_info.scheduler_threads > 1) { int i; lock_vec = enif_alloc(CRYPTO_num_locks()*sizeof(*lock_vec)); if (lock_vec==NULL) return -1; memset(lock_vec,0,CRYPTO_num_locks()*sizeof(*lock_vec)); for (i=CRYPTO_num_locks()-1; i>=0; --i) { lock_vec[i] = enif_rwlock_create("crypto_stat"); if (lock_vec[i]==NULL) return -1; } CRYPTO_set_locking_callback(locking_function); CRYPTO_set_id_callback(id_function); CRYPTO_set_dynlock_create_callback(dyn_create_function); CRYPTO_set_dynlock_lock_callback(dyn_lock_function); CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function); } /* else no need for locks */ #endif /* OPENSSL_THREADS */ atom_true = enif_make_atom(env,"true"); atom_false = enif_make_atom(env,"false"); atom_sha = enif_make_atom(env,"sha"); atom_md5 = enif_make_atom(env,"md5"); atom_error = enif_make_atom(env,"error"); atom_rsa_pkcs1_padding = enif_make_atom(env,"rsa_pkcs1_padding"); atom_rsa_pkcs1_oaep_padding = enif_make_atom(env,"rsa_pkcs1_oaep_padding"); atom_rsa_no_padding = enif_make_atom(env,"rsa_no_padding"); atom_undefined = enif_make_atom(env,"undefined"); atom_ok = enif_make_atom(env,"ok"); atom_not_prime = enif_make_atom(env,"not_prime"); atom_not_strong_prime = enif_make_atom(env,"not_strong_prime"); atom_unable_to_check_generator = enif_make_atom(env,"unable_to_check_generator"); atom_not_suitable_generator = enif_make_atom(env,"not_suitable_generator"); atom_check_failed = enif_make_atom(env,"check_failed"); atom_unknown = enif_make_atom(env,"unknown"); atom_none = enif_make_atom(env,"none"); *priv_data = NULL; library_refc++; return 0; } static int reload(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info) { if (*priv_data != NULL) { return -1; /* Don't know how to do that */ } if (library_refc == 0) { /* No support for real library upgrade. The tricky thing is to know when to (re)set the callbacks for allocation and locking. */ return -2; } if (!is_ok_load_info(env, load_info)) { return -1; } return 0; } static int upgrade(ErlNifEnv* env, void** priv_data, void** old_priv_data, ERL_NIF_TERM load_info) { int i; if (*old_priv_data != NULL) { return -1; /* Don't know how to do that */ } i = reload(env,priv_data,load_info); if (i != 0) { return i; } library_refc++; return 0; } static void unload(ErlNifEnv* env, void* priv_data) { if (--library_refc <= 0) { CRYPTO_cleanup_all_ex_data(); if (lock_vec != NULL) { int i; for (i=CRYPTO_num_locks()-1; i>=0; --i) { if (lock_vec[i] != NULL) { enif_rwlock_destroy(lock_vec[i]); } } enif_free(lock_vec); } } /*else NIF library still used by other (new) module code */ } static ERL_NIF_TERM info_lib(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { /* [{<<"OpenSSL">>,9470143,<<"OpenSSL 0.9.8k 25 Mar 2009">>}] */ static const char libname[] = "OpenSSL"; unsigned name_sz = strlen(libname); const char* ver = SSLeay_version(SSLEAY_VERSION); unsigned ver_sz = strlen(ver); ERL_NIF_TERM name_term, ver_term; memcpy(enif_make_new_binary(env, name_sz, &name_term), libname, name_sz); memcpy(enif_make_new_binary(env, ver_sz, &ver_term), ver, ver_sz); return enif_make_list1(env, enif_make_tuple3(env, name_term, enif_make_int(env, SSLeay()), ver_term)); } static ERL_NIF_TERM md5(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Data) */ ErlNifBinary ibin; ERL_NIF_TERM ret; if (!enif_inspect_iolist_as_binary(env, argv[0], &ibin)) { return enif_make_badarg(env); } MD5((unsigned char *) ibin.data, ibin.size, enif_make_new_binary(env,MD5_LEN, &ret)); return ret; } static ERL_NIF_TERM md5_init(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* () */ ERL_NIF_TERM ret; MD5_Init((MD5_CTX *) enif_make_new_binary(env, MD5_CTX_LEN, &ret)); return ret; } static ERL_NIF_TERM md5_update(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Context, Data) */ MD5_CTX* new_ctx; ErlNifBinary ctx_bin, data_bin; ERL_NIF_TERM ret; if (!enif_inspect_binary(env, argv[0], &ctx_bin) || ctx_bin.size != MD5_CTX_LEN || !enif_inspect_iolist_as_binary(env, argv[1], &data_bin)) { return enif_make_badarg(env); } new_ctx = (MD5_CTX*) enif_make_new_binary(env,MD5_CTX_LEN, &ret); memcpy(new_ctx, ctx_bin.data, MD5_CTX_LEN); MD5_Update(new_ctx, data_bin.data, data_bin.size); return ret; } static ERL_NIF_TERM md5_final(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Context) */ ErlNifBinary ctx_bin; MD5_CTX ctx_clone; ERL_NIF_TERM ret; if (!enif_inspect_binary(env, argv[0], &ctx_bin) || ctx_bin.size != MD5_CTX_LEN) { return enif_make_badarg(env); } memcpy(&ctx_clone, ctx_bin.data, MD5_CTX_LEN); /* writable */ MD5_Final(enif_make_new_binary(env, MD5_LEN, &ret), &ctx_clone); return ret; } static ERL_NIF_TERM sha(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Data) */ ErlNifBinary ibin; ERL_NIF_TERM ret; if (!enif_inspect_iolist_as_binary(env, argv[0], &ibin)) { return enif_make_badarg(env); } SHA1((unsigned char *) ibin.data, ibin.size, enif_make_new_binary(env,SHA_LEN, &ret)); return ret; } static ERL_NIF_TERM sha_init(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* () */ ERL_NIF_TERM ret; SHA1_Init((SHA_CTX *) enif_make_new_binary(env, SHA_CTX_LEN, &ret)); return ret; } static ERL_NIF_TERM sha_update(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Context, Data) */ SHA_CTX* new_ctx; ErlNifBinary ctx_bin, data_bin; ERL_NIF_TERM ret; if (!enif_inspect_binary(env, argv[0], &ctx_bin) || ctx_bin.size != SHA_CTX_LEN || !enif_inspect_iolist_as_binary(env, argv[1], &data_bin)) { return enif_make_badarg(env); } new_ctx = (SHA_CTX*) enif_make_new_binary(env,SHA_CTX_LEN, &ret); memcpy(new_ctx, ctx_bin.data, SHA_CTX_LEN); SHA1_Update(new_ctx, data_bin.data, data_bin.size); return ret; } static ERL_NIF_TERM sha_final(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Context) */ ErlNifBinary ctx_bin; SHA_CTX ctx_clone; ERL_NIF_TERM ret; if (!enif_inspect_binary(env, argv[0], &ctx_bin) || ctx_bin.size != SHA_CTX_LEN) { return enif_make_badarg(env); } memcpy(&ctx_clone, ctx_bin.data, SHA_CTX_LEN); /* writable */ SHA1_Final(enif_make_new_binary(env, SHA_LEN, &ret), &ctx_clone); return ret; } static ERL_NIF_TERM md4(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Data) */ ErlNifBinary ibin; ERL_NIF_TERM ret; if (!enif_inspect_iolist_as_binary(env, argv[0], &ibin)) { return enif_make_badarg(env); } MD4((unsigned char *) ibin.data, ibin.size, enif_make_new_binary(env,MD4_LEN, &ret)); return ret; } static ERL_NIF_TERM md4_init(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* () */ ERL_NIF_TERM ret; MD4_Init((MD4_CTX *) enif_make_new_binary(env, MD4_CTX_LEN, &ret)); return ret; } static ERL_NIF_TERM md4_update(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Context, Data) */ MD4_CTX* new_ctx; ErlNifBinary ctx_bin, data_bin; ERL_NIF_TERM ret; if (!enif_inspect_binary(env, argv[0], &ctx_bin) || ctx_bin.size != MD4_CTX_LEN || !enif_inspect_iolist_as_binary(env, argv[1], &data_bin)) { return enif_make_badarg(env); } new_ctx = (MD4_CTX*) enif_make_new_binary(env,MD4_CTX_LEN, &ret); memcpy(new_ctx, ctx_bin.data, MD4_CTX_LEN); MD4_Update(new_ctx, data_bin.data, data_bin.size); return ret; } static ERL_NIF_TERM md4_final(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Context) */ ErlNifBinary ctx_bin; MD4_CTX ctx_clone; ERL_NIF_TERM ret; if (!enif_inspect_binary(env, argv[0], &ctx_bin) || ctx_bin.size != MD4_CTX_LEN) { return enif_make_badarg(env); } memcpy(&ctx_clone, ctx_bin.data, MD4_CTX_LEN); /* writable */ MD4_Final(enif_make_new_binary(env, MD4_LEN, &ret), &ctx_clone); return ret; } static ERL_NIF_TERM md5_mac_n(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Key, Data, MacSize) */ unsigned char hmacbuf[SHA_DIGEST_LENGTH]; ErlNifBinary key, data; unsigned mac_sz; ERL_NIF_TERM ret; if (!enif_inspect_iolist_as_binary(env, argv[0], &key) || !enif_inspect_iolist_as_binary(env, argv[1], &data) || !enif_get_uint(env,argv[2],&mac_sz) || mac_sz > MD5_LEN) { return enif_make_badarg(env); } hmac_md5(key.data, key.size, data.data, data.size, hmacbuf); memcpy(enif_make_new_binary(env, mac_sz, &ret), hmacbuf, mac_sz); return ret; } static ERL_NIF_TERM sha_mac_n(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Key, Data, MacSize) */ unsigned char hmacbuf[SHA_DIGEST_LENGTH]; ErlNifBinary key, data; unsigned mac_sz; ERL_NIF_TERM ret; if (!enif_inspect_iolist_as_binary(env, argv[0], &key) || !enif_inspect_iolist_as_binary(env, argv[1], &data) || !enif_get_uint(env,argv[2],&mac_sz) || mac_sz > SHA_LEN) { return enif_make_badarg(env); } hmac_sha1(key.data, key.size, data.data, data.size, hmacbuf); memcpy(enif_make_new_binary(env, mac_sz, &ret), hmacbuf, mac_sz); return ret; } static ERL_NIF_TERM des_cbc_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Key, Ivec, Text, IsEncrypt) */ ErlNifBinary key, ivec, text; DES_key_schedule schedule; DES_cblock ivec_clone; /* writable copy */ ERL_NIF_TERM ret; if (!enif_inspect_iolist_as_binary(env, argv[0], &key) || key.size != 8 || !enif_inspect_binary(env, argv[1], &ivec) || ivec.size != 8 || !enif_inspect_iolist_as_binary(env, argv[2], &text) || text.size % 8 != 0) { return enif_make_badarg(env); } memcpy(&ivec_clone, ivec.data, 8); DES_set_key((const_DES_cblock*)key.data, &schedule); DES_ncbc_encrypt(text.data, enif_make_new_binary(env, text.size, &ret), text.size, &schedule, &ivec_clone, (argv[3] == atom_true)); return ret; } static ERL_NIF_TERM des_ecb_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Key, Text/Cipher, IsEncrypt) */ ErlNifBinary key, text; DES_key_schedule schedule; ERL_NIF_TERM ret; if (!enif_inspect_iolist_as_binary(env, argv[0], &key) || key.size != 8 || !enif_inspect_iolist_as_binary(env, argv[1], &text) || text.size != 8) { return enif_make_badarg(env); } DES_set_key((const_DES_cblock*)key.data, &schedule); DES_ecb_encrypt((const_DES_cblock*)text.data, (DES_cblock*)enif_make_new_binary(env, 8, &ret), &schedule, (argv[2] == atom_true)); return ret; } static ERL_NIF_TERM des_ede3_cbc_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Key1, Key2, Key3, IVec, Text/Cipher, IsEncrypt) */ ErlNifBinary key1, key2, key3, ivec, text; DES_key_schedule schedule1, schedule2, schedule3; DES_cblock ivec_clone; /* writable copy */ ERL_NIF_TERM ret; if (!enif_inspect_iolist_as_binary(env, argv[0], &key1) || key1.size != 8 || !enif_inspect_iolist_as_binary(env, argv[1], &key2) || key2.size != 8 || !enif_inspect_iolist_as_binary(env, argv[2], &key3) || key3.size != 8 || !enif_inspect_binary(env, argv[3], &ivec) || ivec.size != 8 || !enif_inspect_iolist_as_binary(env, argv[4], &text) || text.size % 8 != 0) { return enif_make_badarg(env); } memcpy(&ivec_clone, ivec.data, 8); DES_set_key((const_DES_cblock*)key1.data, &schedule1); DES_set_key((const_DES_cblock*)key2.data, &schedule2); DES_set_key((const_DES_cblock*)key3.data, &schedule3); DES_ede3_cbc_encrypt(text.data, enif_make_new_binary(env,text.size,&ret), text.size, &schedule1, &schedule2, &schedule3, &ivec_clone, (argv[5] == atom_true)); return ret; } static ERL_NIF_TERM aes_cfb_128_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Key, IVec, Data, IsEncrypt) */ ErlNifBinary key, ivec, text; AES_KEY aes_key; unsigned char ivec_clone[16]; /* writable copy */ int new_ivlen = 0; ERL_NIF_TERM ret; if (!enif_inspect_iolist_as_binary(env, argv[0], &key) || key.size != 16 || !enif_inspect_binary(env, argv[1], &ivec) || ivec.size != 16 || !enif_inspect_iolist_as_binary(env, argv[2], &text) || text.size % 16 != 0) { return enif_make_badarg(env); } memcpy(ivec_clone, ivec.data, 16); AES_set_encrypt_key(key.data, 128, &aes_key); AES_cfb128_encrypt((unsigned char *) text.data, enif_make_new_binary(env, text.size, &ret), text.size, &aes_key, ivec_clone, &new_ivlen, (argv[3] == atom_true)); return ret; } /* Common for both encrypt and decrypt */ static ERL_NIF_TERM aes_ctr_encrypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Key, IVec, Data) */ ErlNifBinary key, ivec, text; AES_KEY aes_key; unsigned char ivec_clone[16]; /* writable copy */ unsigned char ecount_buf[AES_BLOCK_SIZE]; unsigned int num = 0; ERL_NIF_TERM ret; if (!enif_inspect_iolist_as_binary(env, argv[0], &key) || AES_set_encrypt_key(key.data, key.size*8, &aes_key) != 0 || !enif_inspect_binary(env, argv[1], &ivec) || ivec.size != 16 || !enif_inspect_iolist_as_binary(env, argv[2], &text)) { return enif_make_badarg(env); } memcpy(ivec_clone, ivec.data, 16); memset(ecount_buf, 0, sizeof(ecount_buf)); AES_ctr128_encrypt((unsigned char *) text.data, enif_make_new_binary(env, text.size, &ret), text.size, &aes_key, ivec_clone, ecount_buf, &num); /* To do an incremental {en|de}cryption, the state to to keep between calls must include ivec_clone, ecount_buf and num. */ return ret; } static ERL_NIF_TERM rand_bytes_1(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Bytes) */ unsigned bytes; unsigned char* data; ERL_NIF_TERM ret; if (!enif_get_uint(env, argv[0], &bytes)) { return enif_make_badarg(env); } data = enif_make_new_binary(env, bytes, &ret); RAND_pseudo_bytes(data, bytes); ERL_VALGRIND_MAKE_MEM_DEFINED(data, bytes); return ret; } static ERL_NIF_TERM strong_rand_bytes_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Bytes) */ unsigned bytes; unsigned char* data; ERL_NIF_TERM ret; if (!enif_get_uint(env, argv[0], &bytes)) { return enif_make_badarg(env); } data = enif_make_new_binary(env, bytes, &ret); if ( RAND_bytes(data, bytes) != 1) { return atom_false; } ERL_VALGRIND_MAKE_MEM_DEFINED(data, bytes); return ret; } static ERL_NIF_TERM rand_bytes_3(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Bytes, TopMask, BottomMask) */ unsigned bytes; unsigned char* data; unsigned top_mask, bot_mask; ERL_NIF_TERM ret; if (!enif_get_uint(env, argv[0], &bytes) || !enif_get_uint(env, argv[1], &top_mask) || !enif_get_uint(env, argv[2], &bot_mask)) { return enif_make_badarg(env); } data = enif_make_new_binary(env, bytes, &ret); RAND_pseudo_bytes(data, bytes); ERL_VALGRIND_MAKE_MEM_DEFINED(data, bytes); if (bytes > 0) { data[bytes-1] |= top_mask; data[0] |= bot_mask; } return ret; } static ERL_NIF_TERM strong_rand_mpint_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Bytes, TopMask, BottomMask) */ unsigned bits; BIGNUM *bn_rand; int top, bottom; unsigned char* data; unsigned dlen; ERL_NIF_TERM ret; if (!enif_get_uint(env, argv[0], &bits) || !enif_get_int(env, argv[1], &top) || !enif_get_int(env, argv[2], &bottom)) { return enif_make_badarg(env); } if (! (top == -1 || top == 0 || top == 1) ) { return enif_make_badarg(env); } if (! (bottom == 0 || bottom == 1) ) { return enif_make_badarg(env); } bn_rand = BN_new(); if (! bn_rand ) { return enif_make_badarg(env); } /* Get a (bits) bit random number */ if (!BN_rand(bn_rand, bits, top, bottom)) { ret = atom_false; } else { /* Copy the bignum into an erlang mpint binary. */ dlen = BN_num_bytes(bn_rand); data = enif_make_new_binary(env, dlen+4, &ret); put_int32(data, dlen); BN_bn2bin(bn_rand, data+4); ERL_VALGRIND_MAKE_MEM_DEFINED(data+4, dlen); } BN_free(bn_rand); return ret; } static int get_bn_from_mpint(ErlNifEnv* env, ERL_NIF_TERM term, BIGNUM** bnp) { ErlNifBinary bin; int sz; if (!enif_inspect_binary(env,term,&bin)) { return 0; } ERL_VALGRIND_ASSERT_MEM_DEFINED(bin.data, bin.size); sz = bin.size - 4; if (sz < 0 || get_int32(bin.data) != sz) { return 0; } *bnp = BN_bin2bn(bin.data+4, sz, NULL); return 1; } static ERL_NIF_TERM rand_uniform_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Lo,Hi) */ BIGNUM *bn_from = NULL, *bn_to, *bn_rand; unsigned char* data; unsigned dlen; ERL_NIF_TERM ret; if (!get_bn_from_mpint(env, argv[0], &bn_from) || !get_bn_from_mpint(env, argv[1], &bn_rand)) { if (bn_from) BN_free(bn_from); return enif_make_badarg(env); } bn_to = BN_new(); BN_sub(bn_to, bn_rand, bn_from); BN_pseudo_rand_range(bn_rand, bn_to); BN_add(bn_rand, bn_rand, bn_from); dlen = BN_num_bytes(bn_rand); data = enif_make_new_binary(env, dlen+4, &ret); put_int32(data, dlen); BN_bn2bin(bn_rand, data+4); ERL_VALGRIND_MAKE_MEM_DEFINED(data+4, dlen); BN_free(bn_rand); BN_free(bn_from); BN_free(bn_to); return ret; } static ERL_NIF_TERM mod_exp_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Base,Exponent,Modulo) */ BIGNUM *bn_base=NULL, *bn_exponent=NULL, *bn_modulo, *bn_result; BN_CTX *bn_ctx; unsigned char* ptr; unsigned dlen; ERL_NIF_TERM ret; if (!get_bn_from_mpint(env, argv[0], &bn_base) || !get_bn_from_mpint(env, argv[1], &bn_exponent) || !get_bn_from_mpint(env, argv[2], &bn_modulo)) { if (bn_base) BN_free(bn_base); if (bn_exponent) BN_free(bn_exponent); return enif_make_badarg(env); } bn_result = BN_new(); bn_ctx = BN_CTX_new(); BN_mod_exp(bn_result, bn_base, bn_exponent, bn_modulo, bn_ctx); dlen = BN_num_bytes(bn_result); ptr = enif_make_new_binary(env, dlen+4, &ret); put_int32(ptr, dlen); BN_bn2bin(bn_result, ptr+4); BN_free(bn_result); BN_CTX_free(bn_ctx); BN_free(bn_modulo); BN_free(bn_exponent); BN_free(bn_base); return ret; } static int inspect_mpint(ErlNifEnv* env, ERL_NIF_TERM term, ErlNifBinary* bin) { return enif_inspect_binary(env, term, bin) && bin->size >= 4 && get_int32(bin->data) == bin->size-4; } static ERL_NIF_TERM dss_verify(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (DigestType,Data,Signature,Key=[P, Q, G, Y]) */ ErlNifBinary data_bin, sign_bin; BIGNUM *dsa_p = NULL, *dsa_q = NULL, *dsa_g = NULL, *dsa_y = NULL; unsigned char hmacbuf[SHA_DIGEST_LENGTH]; ERL_NIF_TERM head, tail; DSA *dsa; int i; if (!inspect_mpint(env, argv[2], &sign_bin) || !enif_get_list_cell(env, argv[3], &head, &tail) || !get_bn_from_mpint(env, head, &dsa_p) || !enif_get_list_cell(env, tail, &head, &tail) || !get_bn_from_mpint(env, head, &dsa_q) || !enif_get_list_cell(env, tail, &head, &tail) || !get_bn_from_mpint(env, head, &dsa_g) || !enif_get_list_cell(env, tail, &head, &tail) || !get_bn_from_mpint(env, head, &dsa_y) || !enif_is_empty_list(env,tail)) { badarg: if (dsa_p) BN_free(dsa_p); if (dsa_q) BN_free(dsa_q); if (dsa_g) BN_free(dsa_g); if (dsa_y) BN_free(dsa_y); return enif_make_badarg(env); } if (argv[0] == atom_sha && inspect_mpint(env, argv[1], &data_bin)) { SHA1(data_bin.data+4, data_bin.size-4, hmacbuf); } else if (argv[0] == atom_none && enif_inspect_binary(env, argv[1], &data_bin) && data_bin.size == SHA_DIGEST_LENGTH) { memcpy(hmacbuf, data_bin.data, SHA_DIGEST_LENGTH); } else { goto badarg; } dsa = DSA_new(); dsa->p = dsa_p; dsa->q = dsa_q; dsa->g = dsa_g; dsa->priv_key = NULL; dsa->pub_key = dsa_y; i = DSA_verify(0, hmacbuf, SHA_DIGEST_LENGTH, sign_bin.data+4, sign_bin.size-4, dsa); DSA_free(dsa); return(i > 0) ? atom_true : atom_false; } static ERL_NIF_TERM rsa_verify(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Type, Data, Signature, Key=[E,N]) */ ErlNifBinary data_bin, sign_bin; unsigned char hmacbuf[SHA_DIGEST_LENGTH]; ERL_NIF_TERM head, tail, ret; int i, is_sha; RSA* rsa = RSA_new(); if (argv[0] == atom_sha) is_sha = 1; else if (argv[0] == atom_md5) is_sha = 0; else goto badarg; if (!inspect_mpint(env, argv[1], &data_bin) || !inspect_mpint(env, argv[2], &sign_bin) || !enif_get_list_cell(env, argv[3], &head, &tail) || !get_bn_from_mpint(env, head, &rsa->e) || !enif_get_list_cell(env, tail, &head, &tail) || !get_bn_from_mpint(env, head, &rsa->n) || !enif_is_empty_list(env, tail)) { badarg: ret = enif_make_badarg(env); } else { if (is_sha) { SHA1(data_bin.data+4, data_bin.size-4, hmacbuf); i = RSA_verify(NID_sha1, hmacbuf, SHA_DIGEST_LENGTH, sign_bin.data+4, sign_bin.size-4, rsa); } else { MD5(data_bin.data+4, data_bin.size-4, hmacbuf); i = RSA_verify(NID_md5, hmacbuf, MD5_DIGEST_LENGTH, sign_bin.data+4, sign_bin.size-4, rsa); } ret = (i==1 ? atom_true : atom_false); } RSA_free(rsa); return ret; } static ERL_NIF_TERM aes_cbc_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Key, IVec, Data, IsEncrypt) */ ErlNifBinary key_bin, ivec_bin, data_bin; AES_KEY aes_key; unsigned char ivec[16]; int i; unsigned char* ret_ptr; ERL_NIF_TERM ret; if (!enif_inspect_iolist_as_binary(env, argv[0], &key_bin) || (key_bin.size != 16 && key_bin.size != 32) || !enif_inspect_binary(env, argv[1], &ivec_bin) || ivec_bin.size != 16 || !enif_inspect_iolist_as_binary(env, argv[2], &data_bin) || data_bin.size % 16 != 0) { return enif_make_badarg(env); } if (argv[3] == atom_true) { i = AES_ENCRYPT; AES_set_encrypt_key(key_bin.data, key_bin.size*8, &aes_key); } else { i = AES_DECRYPT; AES_set_decrypt_key(key_bin.data, key_bin.size*8, &aes_key); } ret_ptr = enif_make_new_binary(env, data_bin.size, &ret); memcpy(ivec, ivec_bin.data, 16); /* writable copy */ AES_cbc_encrypt(data_bin.data, ret_ptr, data_bin.size, &aes_key, ivec, i); return ret; } static ERL_NIF_TERM exor(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Data1, Data2) */ ErlNifBinary d1, d2; unsigned char* ret_ptr; int i; ERL_NIF_TERM ret; if (!enif_inspect_iolist_as_binary(env,argv[0], &d1) || !enif_inspect_iolist_as_binary(env,argv[1], &d2) || d1.size != d2.size) { return enif_make_badarg(env); } ret_ptr = enif_make_new_binary(env, d1.size, &ret); for (i=0; i<d1.size; i++) { ret_ptr[i] = d1.data[i] ^ d2.data[i]; } return ret; } static ERL_NIF_TERM rc4_encrypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Key, Data) */ ErlNifBinary key, data; RC4_KEY rc4_key; ERL_NIF_TERM ret; if (!enif_inspect_iolist_as_binary(env,argv[0], &key) || !enif_inspect_iolist_as_binary(env,argv[1], &data)) { return enif_make_badarg(env); } RC4_set_key(&rc4_key, key.size, key.data); RC4(&rc4_key, data.size, data.data, enif_make_new_binary(env, data.size, &ret)); return ret; } static ERL_NIF_TERM rc4_set_key(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Key) */ ErlNifBinary key; ERL_NIF_TERM ret; if (!enif_inspect_iolist_as_binary(env,argv[0], &key)) { return enif_make_badarg(env); } RC4_set_key((RC4_KEY*)enif_make_new_binary(env, sizeof(RC4_KEY), &ret), key.size, key.data); return ret; } static ERL_NIF_TERM rc4_encrypt_with_state(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (State, Data) */ ErlNifBinary state, data; RC4_KEY* rc4_key; ERL_NIF_TERM new_state, new_data; if (!enif_inspect_iolist_as_binary(env,argv[0], &state) || state.size != sizeof(RC4_KEY) || !enif_inspect_iolist_as_binary(env,argv[1], &data)) { return enif_make_badarg(env); } rc4_key = (RC4_KEY*)enif_make_new_binary(env, sizeof(RC4_KEY), &new_state); memcpy(rc4_key, state.data, sizeof(RC4_KEY)); RC4(rc4_key, data.size, data.data, enif_make_new_binary(env, data.size, &new_data)); return enif_make_tuple2(env,new_state,new_data); } static ERL_NIF_TERM rc2_40_cbc_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Key,IVec,Data,IsEncrypt) */ ErlNifBinary key_bin, ivec_bin, data_bin; RC2_KEY rc2_key; ERL_NIF_TERM ret; if (!enif_inspect_iolist_as_binary(env, argv[0], &key_bin) || key_bin.size != 5 || !enif_inspect_binary(env, argv[1], &ivec_bin) || ivec_bin.size != 8 || !enif_inspect_iolist_as_binary(env, argv[2], &data_bin)) { return enif_make_badarg(env); } RC2_set_key(&rc2_key, 5, key_bin.data, 40); RC2_cbc_encrypt(data_bin.data, enif_make_new_binary(env, data_bin.size, &ret), data_bin.size, &rc2_key, ivec_bin.data, (argv[3] == atom_true)); return ret; } static ERL_NIF_TERM rsa_sign_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Type,Data,Key=[E,N,D]) */ ErlNifBinary data_bin, ret_bin; ERL_NIF_TERM head, tail; unsigned char hmacbuf[SHA_DIGEST_LENGTH]; unsigned rsa_s_len; RSA *rsa = RSA_new(); int i, is_sha; if (argv[0] == atom_sha) is_sha = 1; else if (argv[0] == atom_md5) is_sha = 0; else goto badarg; if (!inspect_mpint(env,argv[1],&data_bin) || !enif_get_list_cell(env, argv[2], &head, &tail) || !get_bn_from_mpint(env, head, &rsa->e) || !enif_get_list_cell(env, tail, &head, &tail) || !get_bn_from_mpint(env, head, &rsa->n) || !enif_get_list_cell(env, tail, &head, &tail) || !get_bn_from_mpint(env, head, &rsa->d) || !enif_is_empty_list(env,tail)) { badarg: RSA_free(rsa); return enif_make_badarg(env); } enif_alloc_binary(RSA_size(rsa), &ret_bin); if (is_sha) { SHA1(data_bin.data+4, data_bin.size-4, hmacbuf); ERL_VALGRIND_ASSERT_MEM_DEFINED(hmacbuf, SHA_DIGEST_LENGTH); i = RSA_sign(NID_sha1, hmacbuf, SHA_DIGEST_LENGTH, ret_bin.data, &rsa_s_len, rsa); } else { MD5(data_bin.data+4, data_bin.size-4, hmacbuf); ERL_VALGRIND_ASSERT_MEM_DEFINED(hmacbuf, MD5_DIGEST_LENGTH); i = RSA_sign(NID_md5, hmacbuf,MD5_DIGEST_LENGTH, ret_bin.data, &rsa_s_len, rsa); } RSA_free(rsa); if (i) { ERL_VALGRIND_MAKE_MEM_DEFINED(ret_bin.data, rsa_s_len); if (rsa_s_len != data_bin.size) { enif_realloc_binary(&ret_bin, rsa_s_len); ERL_VALGRIND_ASSERT_MEM_DEFINED(ret_bin.data, rsa_s_len); } return enif_make_binary(env,&ret_bin); } else { enif_release_binary(&ret_bin); return atom_error; } } static ERL_NIF_TERM dss_sign_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (DigesType, Data, Key=[P,Q,G,PrivKey]) */ ErlNifBinary data_bin, ret_bin; ERL_NIF_TERM head, tail; unsigned char hmacbuf[SHA_DIGEST_LENGTH]; unsigned int dsa_s_len; DSA* dsa = DSA_new(); int i; dsa->pub_key = NULL; if (!enif_get_list_cell(env, argv[2], &head, &tail) || !get_bn_from_mpint(env, head, &dsa->p) || !enif_get_list_cell(env, tail, &head, &tail) || !get_bn_from_mpint(env, head, &dsa->q) || !enif_get_list_cell(env, tail, &head, &tail) || !get_bn_from_mpint(env, head, &dsa->g) || !enif_get_list_cell(env, tail, &head, &tail) || !get_bn_from_mpint(env, head, &dsa->priv_key) || !enif_is_empty_list(env,tail)) { goto badarg; } if (argv[0] == atom_sha && inspect_mpint(env, argv[1], &data_bin)) { SHA1(data_bin.data+4, data_bin.size-4, hmacbuf); } else if (argv[0] == atom_none && enif_inspect_binary(env,argv[1],&data_bin) && data_bin.size == SHA_DIGEST_LENGTH) { memcpy(hmacbuf, data_bin.data, SHA_DIGEST_LENGTH); } else { badarg: DSA_free(dsa); return enif_make_badarg(env); } enif_alloc_binary(DSA_size(dsa), &ret_bin); i = DSA_sign(NID_sha1, hmacbuf, SHA_DIGEST_LENGTH, ret_bin.data, &dsa_s_len, dsa); DSA_free(dsa); if (i) { if (dsa_s_len != ret_bin.size) { enif_realloc_binary(&ret_bin, dsa_s_len); } return enif_make_binary(env, &ret_bin); } else { return atom_error; } } static int rsa_pad(ERL_NIF_TERM term, int* padding) { if (term == atom_rsa_pkcs1_padding) { *padding = RSA_PKCS1_PADDING; } else if (term == atom_rsa_pkcs1_oaep_padding) { *padding = RSA_PKCS1_OAEP_PADDING; } else if (term == atom_rsa_no_padding) { *padding = RSA_NO_PADDING; } else { return 0; } return 1; } static ERL_NIF_TERM rsa_public_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Data, PublKey=[E,N], Padding, IsEncrypt) */ ErlNifBinary data_bin, ret_bin; ERL_NIF_TERM head, tail; int padding, i; RSA* rsa = RSA_new(); if (!enif_inspect_binary(env, argv[0], &data_bin) || !enif_get_list_cell(env, argv[1], &head, &tail) || !get_bn_from_mpint(env, head, &rsa->e) || !enif_get_list_cell(env, tail, &head, &tail) || !get_bn_from_mpint(env, head, &rsa->n) || !enif_is_empty_list(env,tail) || !rsa_pad(argv[2], &padding)) { RSA_free(rsa); return enif_make_badarg(env); } enif_alloc_binary(RSA_size(rsa), &ret_bin); if (argv[3] == atom_true) { ERL_VALGRIND_ASSERT_MEM_DEFINED(data_bin.data,data_bin.size); i = RSA_public_encrypt(data_bin.size, data_bin.data, ret_bin.data, rsa, padding); if (i > 0) { ERL_VALGRIND_MAKE_MEM_DEFINED(ret_bin.data, i); } } else { i = RSA_public_decrypt(data_bin.size, data_bin.data, ret_bin.data, rsa, padding); if (i > 0) { ERL_VALGRIND_MAKE_MEM_DEFINED(ret_bin.data, i); enif_realloc_binary(&ret_bin, i); } } RSA_free(rsa); if (i > 0) { return enif_make_binary(env,&ret_bin); } else { enif_release_binary(&ret_bin); return atom_error; } } static ERL_NIF_TERM rsa_private_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Data, PublKey=[E,N,D], Padding, IsEncrypt) */ ErlNifBinary data_bin, ret_bin; ERL_NIF_TERM head, tail; int padding, i; RSA* rsa = RSA_new(); if (!enif_inspect_binary(env, argv[0], &data_bin) || !enif_get_list_cell(env, argv[1], &head, &tail) || !get_bn_from_mpint(env, head, &rsa->e) || !enif_get_list_cell(env, tail, &head, &tail) || !get_bn_from_mpint(env, head, &rsa->n) || !enif_get_list_cell(env, tail, &head, &tail) || !get_bn_from_mpint(env, head, &rsa->d) || !enif_is_empty_list(env,tail) || !rsa_pad(argv[2], &padding)) { RSA_free(rsa); return enif_make_badarg(env); } enif_alloc_binary(RSA_size(rsa), &ret_bin); if (argv[3] == atom_true) { ERL_VALGRIND_ASSERT_MEM_DEFINED(data_bin.data,data_bin.size); i = RSA_private_encrypt(data_bin.size, data_bin.data, ret_bin.data, rsa, padding); if (i > 0) { ERL_VALGRIND_MAKE_MEM_DEFINED(ret_bin.data, i); } } else { i = RSA_private_decrypt(data_bin.size, data_bin.data, ret_bin.data, rsa, padding); if (i > 0) { ERL_VALGRIND_MAKE_MEM_DEFINED(ret_bin.data, i); enif_realloc_binary(&ret_bin, i); } } RSA_free(rsa); if (i > 0) { return enif_make_binary(env,&ret_bin); } else { enif_release_binary(&ret_bin); return atom_error; } } static ERL_NIF_TERM dh_generate_parameters_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (PrimeLen, Generator) */ int prime_len, generator; DH* dh_params; int p_len, g_len; unsigned char *p_ptr, *g_ptr; ERL_NIF_TERM ret_p, ret_g; if (!enif_get_int(env, argv[0], &prime_len) || !enif_get_int(env, argv[1], &generator)) { return enif_make_badarg(env); } dh_params = DH_generate_parameters(prime_len, generator, NULL, NULL); if (dh_params == NULL) { return atom_error; } p_len = BN_num_bytes(dh_params->p); g_len = BN_num_bytes(dh_params->g); p_ptr = enif_make_new_binary(env, p_len+4, &ret_p); g_ptr = enif_make_new_binary(env, g_len+4, &ret_g); put_int32(p_ptr, p_len); put_int32(g_ptr, g_len); BN_bn2bin(dh_params->p, p_ptr+4); BN_bn2bin(dh_params->g, g_ptr+4); ERL_VALGRIND_MAKE_MEM_DEFINED(p_ptr+4, p_len); ERL_VALGRIND_MAKE_MEM_DEFINED(g_ptr+4, g_len); DH_free(dh_params); return enif_make_list2(env, ret_p, ret_g); } static ERL_NIF_TERM dh_check(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* ([PrimeLen, Generator]) */ DH* dh_params = DH_new(); int i; ERL_NIF_TERM ret, head, tail; if (!enif_get_list_cell(env, argv[0], &head, &tail) || !get_bn_from_mpint(env, head, &dh_params->p) || !enif_get_list_cell(env, tail, &head, &tail) || !get_bn_from_mpint(env, head, &dh_params->g) || !enif_is_empty_list(env,tail)) { DH_free(dh_params); return enif_make_badarg(env); } if (DH_check(dh_params, &i)) { if (i == 0) ret = atom_ok; else if (i & DH_CHECK_P_NOT_PRIME) ret = atom_not_prime; else if (i & DH_CHECK_P_NOT_SAFE_PRIME) ret = atom_not_strong_prime; else if (i & DH_UNABLE_TO_CHECK_GENERATOR) ret = atom_unable_to_check_generator; else if (i & DH_NOT_SUITABLE_GENERATOR) ret = atom_not_suitable_generator; else ret = enif_make_tuple2(env, atom_unknown, enif_make_uint(env, i)); } else { /* Check Failed */ ret = enif_make_tuple2(env, atom_error, atom_check_failed); } DH_free(dh_params); return ret; } static ERL_NIF_TERM dh_generate_key_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (PrivKey, DHParams=[P,G]) */ DH* dh_params = DH_new(); int pub_len, prv_len; unsigned char *pub_ptr, *prv_ptr; ERL_NIF_TERM ret, ret_pub, ret_prv, head, tail; if (!(get_bn_from_mpint(env, argv[0], &dh_params->priv_key) || argv[0] == atom_undefined) || !enif_get_list_cell(env, argv[1], &head, &tail) || !get_bn_from_mpint(env, head, &dh_params->p) || !enif_get_list_cell(env, tail, &head, &tail) || !get_bn_from_mpint(env, head, &dh_params->g) || !enif_is_empty_list(env, tail)) { DH_free(dh_params); return enif_make_badarg(env); } if (DH_generate_key(dh_params)) { pub_len = BN_num_bytes(dh_params->pub_key); prv_len = BN_num_bytes(dh_params->priv_key); pub_ptr = enif_make_new_binary(env, pub_len+4, &ret_pub); prv_ptr = enif_make_new_binary(env, prv_len+4, &ret_prv); put_int32(pub_ptr, pub_len); put_int32(prv_ptr, prv_len); BN_bn2bin(dh_params->pub_key, pub_ptr+4); BN_bn2bin(dh_params->priv_key, prv_ptr+4); ERL_VALGRIND_MAKE_MEM_DEFINED(pub_ptr+4, pub_len); ERL_VALGRIND_MAKE_MEM_DEFINED(prv_ptr+4, prv_len); ret = enif_make_tuple2(env, ret_pub, ret_prv); } else { ret = atom_error; } DH_free(dh_params); return ret; } static ERL_NIF_TERM dh_compute_key_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (OthersPublicKey, MyPrivateKey, DHParams=[P,G]) */ DH* dh_params = DH_new(); BIGNUM* pubkey = NULL; int i; ErlNifBinary ret_bin; ERL_NIF_TERM ret, head, tail; if (!get_bn_from_mpint(env, argv[0], &pubkey) || !get_bn_from_mpint(env, argv[1], &dh_params->priv_key) || !enif_get_list_cell(env, argv[2], &head, &tail) || !get_bn_from_mpint(env, head, &dh_params->p) || !enif_get_list_cell(env, tail, &head, &tail) || !get_bn_from_mpint(env, head, &dh_params->g) || !enif_is_empty_list(env, tail)) { ret = enif_make_badarg(env); } else { enif_alloc_binary(DH_size(dh_params), &ret_bin); i = DH_compute_key(ret_bin.data, pubkey, dh_params); if (i > 0) { if (i != ret_bin.size) { enif_realloc_binary(&ret_bin, i); } ret = enif_make_binary(env, &ret_bin); } else { ret = atom_error; } } if (pubkey) BN_free(pubkey); DH_free(dh_params); return ret; } static ERL_NIF_TERM bf_cfb64_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Key, Ivec, Data, IsEncrypt) */ ErlNifBinary key_bin, ivec_bin, data_bin; BF_KEY bf_key; /* blowfish key 8 */ unsigned char bf_tkey[8]; /* blowfish ivec */ int bf_n = 0; /* blowfish ivec pos */ ERL_NIF_TERM ret; if (!enif_inspect_iolist_as_binary(env, argv[0], &key_bin) || !enif_inspect_binary(env, argv[1], &ivec_bin) || ivec_bin.size != 8 || !enif_inspect_iolist_as_binary(env, argv[2], &data_bin)) { return enif_make_badarg(env); } BF_set_key(&bf_key, key_bin.size, key_bin.data); memcpy(bf_tkey, ivec_bin.data, 8); BF_cfb64_encrypt(data_bin.data, enif_make_new_binary(env,data_bin.size,&ret), data_bin.size, &bf_key, bf_tkey, &bf_n, (argv[3] == atom_true ? BF_ENCRYPT : BF_DECRYPT)); return ret; } static ERL_NIF_TERM bf_cbc_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Key, Ivec, Data, IsEncrypt) */ ErlNifBinary key_bin, ivec_bin, data_bin; BF_KEY bf_key; /* blowfish key 8 */ unsigned char bf_tkey[8]; /* blowfish ivec */ ERL_NIF_TERM ret; if (!enif_inspect_iolist_as_binary(env, argv[0], &key_bin) || !enif_inspect_binary(env, argv[1], &ivec_bin) || ivec_bin.size != 8 || !enif_inspect_iolist_as_binary(env, argv[2], &data_bin) || data_bin.size % 8 != 0) { return enif_make_badarg(env); } BF_set_key(&bf_key, key_bin.size, key_bin.data); memcpy(bf_tkey, ivec_bin.data, 8); BF_cbc_encrypt(data_bin.data, enif_make_new_binary(env,data_bin.size,&ret), data_bin.size, &bf_key, bf_tkey, (argv[3] == atom_true ? BF_ENCRYPT : BF_DECRYPT)); return ret; } static ERL_NIF_TERM bf_ecb_crypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Key, Data, IsEncrypt) */ ErlNifBinary key_bin, data_bin; BF_KEY bf_key; /* blowfish key 8 */ ERL_NIF_TERM ret; if (!enif_inspect_iolist_as_binary(env, argv[0], &key_bin) || !enif_inspect_iolist_as_binary(env, argv[1], &data_bin) || data_bin.size < 8) { return enif_make_badarg(env); } BF_set_key(&bf_key, key_bin.size, key_bin.data); BF_ecb_encrypt(data_bin.data, enif_make_new_binary(env,data_bin.size,&ret), &bf_key, (argv[2] == atom_true ? BF_ENCRYPT : BF_DECRYPT)); return ret; } static ERL_NIF_TERM blowfish_ofb64_encrypt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {/* (Key, IVec, Data) */ ErlNifBinary key_bin, ivec_bin, data_bin; BF_KEY bf_key; /* blowfish key 8 */ unsigned char bf_tkey[8]; /* blowfish ivec */ int bf_n = 0; /* blowfish ivec pos */ ERL_NIF_TERM ret; if (!enif_inspect_iolist_as_binary(env, argv[0], &key_bin) || !enif_inspect_binary(env, argv[1], &ivec_bin) || ivec_bin.size != 8 || !enif_inspect_iolist_as_binary(env, argv[2], &data_bin)) { return enif_make_badarg(env); } BF_set_key(&bf_key, key_bin.size, key_bin.data); memcpy(bf_tkey, ivec_bin.data, 8); BF_ofb64_encrypt(data_bin.data, enif_make_new_binary(env,data_bin.size,&ret), data_bin.size, &bf_key, bf_tkey, &bf_n); return ret; } #ifdef OPENSSL_THREADS /* vvvvvvvvvvvvvvv OPENSSL_THREADS vvvvvvvvvvvvvvvv */ static INLINE void locking(int mode, ErlNifRWLock* lock) { switch (mode) { case CRYPTO_LOCK|CRYPTO_READ: enif_rwlock_rlock(lock); break; case CRYPTO_LOCK|CRYPTO_WRITE: enif_rwlock_rwlock(lock); break; case CRYPTO_UNLOCK|CRYPTO_READ: enif_rwlock_runlock(lock); break; case CRYPTO_UNLOCK|CRYPTO_WRITE: enif_rwlock_rwunlock(lock); break; default: ASSERT(!"Invalid lock mode"); } } /* Callback from openssl for static locking */ static void locking_function(int mode, int n, const char *file, int line) { ASSERT(n>=0 && n<CRYPTO_num_locks()); locking(mode, lock_vec[n]); } /* Callback from openssl for thread id */ static unsigned long id_function(void) { return(unsigned long) enif_thread_self(); } /* Callbacks for dynamic locking, not used by current openssl version (0.9.8) */ static struct CRYPTO_dynlock_value* dyn_create_function(const char *file, int line) { return(struct CRYPTO_dynlock_value*) enif_rwlock_create("crypto_dyn"); } static void dyn_lock_function(int mode, struct CRYPTO_dynlock_value* ptr,const char *file, int line) { locking(mode, (ErlNifRWLock*)ptr); } static void dyn_destroy_function(struct CRYPTO_dynlock_value *ptr, const char *file, int line) { enif_rwlock_destroy((ErlNifRWLock*)ptr); } #endif /* ^^^^^^^^^^^^^^^^^^^^^^ OPENSSL_THREADS ^^^^^^^^^^^^^^^^^^^^^^ */ /* HMAC */ static void hmac_md5(unsigned char *key, int klen, unsigned char *dbuf, int dlen, unsigned char *hmacbuf) { MD5_CTX ctx; char ipad[HMAC_INT_LEN]; char opad[HMAC_INT_LEN]; unsigned char nkey[MD5_LEN]; int i; /* Change key if longer than 64 bytes */ if (klen > HMAC_INT_LEN) { MD5(key, klen, nkey); key = nkey; klen = MD5_LEN; } memset(ipad, '\0', sizeof(ipad)); memset(opad, '\0', sizeof(opad)); memcpy(ipad, key, klen); memcpy(opad, key, klen); for (i = 0; i < HMAC_INT_LEN; i++) { ipad[i] ^= HMAC_IPAD; opad[i] ^= HMAC_OPAD; } /* inner MD5 */ MD5_Init(&ctx); MD5_Update(&ctx, ipad, HMAC_INT_LEN); MD5_Update(&ctx, dbuf, dlen); MD5_Final((unsigned char *) hmacbuf, &ctx); /* outer MD5 */ MD5_Init(&ctx); MD5_Update(&ctx, opad, HMAC_INT_LEN); MD5_Update(&ctx, hmacbuf, MD5_LEN); MD5_Final((unsigned char *) hmacbuf, &ctx); } static void hmac_sha1(unsigned char *key, int klen, unsigned char *dbuf, int dlen, unsigned char *hmacbuf) { SHA_CTX ctx; char ipad[HMAC_INT_LEN]; char opad[HMAC_INT_LEN]; unsigned char nkey[SHA_LEN]; int i; /* Change key if longer than 64 bytes */ if (klen > HMAC_INT_LEN) { SHA1(key, klen, nkey); key = nkey; klen = SHA_LEN; } memset(ipad, '\0', sizeof(ipad)); memset(opad, '\0', sizeof(opad)); memcpy(ipad, key, klen); memcpy(opad, key, klen); for (i = 0; i < HMAC_INT_LEN; i++) { ipad[i] ^= HMAC_IPAD; opad[i] ^= HMAC_OPAD; } /* inner SHA */ SHA1_Init(&ctx); SHA1_Update(&ctx, ipad, HMAC_INT_LEN); SHA1_Update(&ctx, dbuf, dlen); SHA1_Final((unsigned char *) hmacbuf, &ctx); /* outer SHA */ SHA1_Init(&ctx); SHA1_Update(&ctx, opad, HMAC_INT_LEN); SHA1_Update(&ctx, hmacbuf, SHA_LEN); SHA1_Final((unsigned char *) hmacbuf, &ctx); }
./CrossVul/dataset_final_sorted/CWE-310/c/good_3428_0
crossvul-cpp_data_good_5666_0
/* * Asynchronous block chaining cipher operations. * * This is the asynchronous version of blkcipher.c indicating completion * via a callback. * * Copyright (c) 2006 Herbert Xu <herbert@gondor.apana.org.au> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include <crypto/internal/skcipher.h> #include <linux/cpumask.h> #include <linux/err.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/rtnetlink.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/seq_file.h> #include <linux/cryptouser.h> #include <net/netlink.h> #include <crypto/scatterwalk.h> #include "internal.h" static const char *skcipher_default_geniv __read_mostly; struct ablkcipher_buffer { struct list_head entry; struct scatter_walk dst; unsigned int len; void *data; }; enum { ABLKCIPHER_WALK_SLOW = 1 << 0, }; static inline void ablkcipher_buffer_write(struct ablkcipher_buffer *p) { scatterwalk_copychunks(p->data, &p->dst, p->len, 1); } void __ablkcipher_walk_complete(struct ablkcipher_walk *walk) { struct ablkcipher_buffer *p, *tmp; list_for_each_entry_safe(p, tmp, &walk->buffers, entry) { ablkcipher_buffer_write(p); list_del(&p->entry); kfree(p); } } EXPORT_SYMBOL_GPL(__ablkcipher_walk_complete); static inline void ablkcipher_queue_write(struct ablkcipher_walk *walk, struct ablkcipher_buffer *p) { p->dst = walk->out; list_add_tail(&p->entry, &walk->buffers); } /* Get a spot of the specified length that does not straddle a page. * The caller needs to ensure that there is enough space for this operation. */ static inline u8 *ablkcipher_get_spot(u8 *start, unsigned int len) { u8 *end_page = (u8 *)(((unsigned long)(start + len - 1)) & PAGE_MASK); return max(start, end_page); } static inline unsigned int ablkcipher_done_slow(struct ablkcipher_walk *walk, unsigned int bsize) { unsigned int n = bsize; for (;;) { unsigned int len_this_page = scatterwalk_pagelen(&walk->out); if (len_this_page > n) len_this_page = n; scatterwalk_advance(&walk->out, n); if (n == len_this_page) break; n -= len_this_page; scatterwalk_start(&walk->out, scatterwalk_sg_next(walk->out.sg)); } return bsize; } static inline unsigned int ablkcipher_done_fast(struct ablkcipher_walk *walk, unsigned int n) { scatterwalk_advance(&walk->in, n); scatterwalk_advance(&walk->out, n); return n; } static int ablkcipher_walk_next(struct ablkcipher_request *req, struct ablkcipher_walk *walk); int ablkcipher_walk_done(struct ablkcipher_request *req, struct ablkcipher_walk *walk, int err) { struct crypto_tfm *tfm = req->base.tfm; unsigned int nbytes = 0; if (likely(err >= 0)) { unsigned int n = walk->nbytes - err; if (likely(!(walk->flags & ABLKCIPHER_WALK_SLOW))) n = ablkcipher_done_fast(walk, n); else if (WARN_ON(err)) { err = -EINVAL; goto err; } else n = ablkcipher_done_slow(walk, n); nbytes = walk->total - n; err = 0; } scatterwalk_done(&walk->in, 0, nbytes); scatterwalk_done(&walk->out, 1, nbytes); err: walk->total = nbytes; walk->nbytes = nbytes; if (nbytes) { crypto_yield(req->base.flags); return ablkcipher_walk_next(req, walk); } if (walk->iv != req->info) memcpy(req->info, walk->iv, tfm->crt_ablkcipher.ivsize); kfree(walk->iv_buffer); return err; } EXPORT_SYMBOL_GPL(ablkcipher_walk_done); static inline int ablkcipher_next_slow(struct ablkcipher_request *req, struct ablkcipher_walk *walk, unsigned int bsize, unsigned int alignmask, void **src_p, void **dst_p) { unsigned aligned_bsize = ALIGN(bsize, alignmask + 1); struct ablkcipher_buffer *p; void *src, *dst, *base; unsigned int n; n = ALIGN(sizeof(struct ablkcipher_buffer), alignmask + 1); n += (aligned_bsize * 3 - (alignmask + 1) + (alignmask & ~(crypto_tfm_ctx_alignment() - 1))); p = kmalloc(n, GFP_ATOMIC); if (!p) return ablkcipher_walk_done(req, walk, -ENOMEM); base = p + 1; dst = (u8 *)ALIGN((unsigned long)base, alignmask + 1); src = dst = ablkcipher_get_spot(dst, bsize); p->len = bsize; p->data = dst; scatterwalk_copychunks(src, &walk->in, bsize, 0); ablkcipher_queue_write(walk, p); walk->nbytes = bsize; walk->flags |= ABLKCIPHER_WALK_SLOW; *src_p = src; *dst_p = dst; return 0; } static inline int ablkcipher_copy_iv(struct ablkcipher_walk *walk, struct crypto_tfm *tfm, unsigned int alignmask) { unsigned bs = walk->blocksize; unsigned int ivsize = tfm->crt_ablkcipher.ivsize; unsigned aligned_bs = ALIGN(bs, alignmask + 1); unsigned int size = aligned_bs * 2 + ivsize + max(aligned_bs, ivsize) - (alignmask + 1); u8 *iv; size += alignmask & ~(crypto_tfm_ctx_alignment() - 1); walk->iv_buffer = kmalloc(size, GFP_ATOMIC); if (!walk->iv_buffer) return -ENOMEM; iv = (u8 *)ALIGN((unsigned long)walk->iv_buffer, alignmask + 1); iv = ablkcipher_get_spot(iv, bs) + aligned_bs; iv = ablkcipher_get_spot(iv, bs) + aligned_bs; iv = ablkcipher_get_spot(iv, ivsize); walk->iv = memcpy(iv, walk->iv, ivsize); return 0; } static inline int ablkcipher_next_fast(struct ablkcipher_request *req, struct ablkcipher_walk *walk) { walk->src.page = scatterwalk_page(&walk->in); walk->src.offset = offset_in_page(walk->in.offset); walk->dst.page = scatterwalk_page(&walk->out); walk->dst.offset = offset_in_page(walk->out.offset); return 0; } static int ablkcipher_walk_next(struct ablkcipher_request *req, struct ablkcipher_walk *walk) { struct crypto_tfm *tfm = req->base.tfm; unsigned int alignmask, bsize, n; void *src, *dst; int err; alignmask = crypto_tfm_alg_alignmask(tfm); n = walk->total; if (unlikely(n < crypto_tfm_alg_blocksize(tfm))) { req->base.flags |= CRYPTO_TFM_RES_BAD_BLOCK_LEN; return ablkcipher_walk_done(req, walk, -EINVAL); } walk->flags &= ~ABLKCIPHER_WALK_SLOW; src = dst = NULL; bsize = min(walk->blocksize, n); n = scatterwalk_clamp(&walk->in, n); n = scatterwalk_clamp(&walk->out, n); if (n < bsize || !scatterwalk_aligned(&walk->in, alignmask) || !scatterwalk_aligned(&walk->out, alignmask)) { err = ablkcipher_next_slow(req, walk, bsize, alignmask, &src, &dst); goto set_phys_lowmem; } walk->nbytes = n; return ablkcipher_next_fast(req, walk); set_phys_lowmem: if (err >= 0) { walk->src.page = virt_to_page(src); walk->dst.page = virt_to_page(dst); walk->src.offset = ((unsigned long)src & (PAGE_SIZE - 1)); walk->dst.offset = ((unsigned long)dst & (PAGE_SIZE - 1)); } return err; } static int ablkcipher_walk_first(struct ablkcipher_request *req, struct ablkcipher_walk *walk) { struct crypto_tfm *tfm = req->base.tfm; unsigned int alignmask; alignmask = crypto_tfm_alg_alignmask(tfm); if (WARN_ON_ONCE(in_irq())) return -EDEADLK; walk->nbytes = walk->total; if (unlikely(!walk->total)) return 0; walk->iv_buffer = NULL; walk->iv = req->info; if (unlikely(((unsigned long)walk->iv & alignmask))) { int err = ablkcipher_copy_iv(walk, tfm, alignmask); if (err) return err; } scatterwalk_start(&walk->in, walk->in.sg); scatterwalk_start(&walk->out, walk->out.sg); return ablkcipher_walk_next(req, walk); } int ablkcipher_walk_phys(struct ablkcipher_request *req, struct ablkcipher_walk *walk) { walk->blocksize = crypto_tfm_alg_blocksize(req->base.tfm); return ablkcipher_walk_first(req, walk); } EXPORT_SYMBOL_GPL(ablkcipher_walk_phys); static int setkey_unaligned(struct crypto_ablkcipher *tfm, const u8 *key, unsigned int keylen) { struct ablkcipher_alg *cipher = crypto_ablkcipher_alg(tfm); unsigned long alignmask = crypto_ablkcipher_alignmask(tfm); int ret; u8 *buffer, *alignbuffer; unsigned long absize; absize = keylen + alignmask; buffer = kmalloc(absize, GFP_ATOMIC); if (!buffer) return -ENOMEM; alignbuffer = (u8 *)ALIGN((unsigned long)buffer, alignmask + 1); memcpy(alignbuffer, key, keylen); ret = cipher->setkey(tfm, alignbuffer, keylen); memset(alignbuffer, 0, keylen); kfree(buffer); return ret; } static int setkey(struct crypto_ablkcipher *tfm, const u8 *key, unsigned int keylen) { struct ablkcipher_alg *cipher = crypto_ablkcipher_alg(tfm); unsigned long alignmask = crypto_ablkcipher_alignmask(tfm); if (keylen < cipher->min_keysize || keylen > cipher->max_keysize) { crypto_ablkcipher_set_flags(tfm, CRYPTO_TFM_RES_BAD_KEY_LEN); return -EINVAL; } if ((unsigned long)key & alignmask) return setkey_unaligned(tfm, key, keylen); return cipher->setkey(tfm, key, keylen); } static unsigned int crypto_ablkcipher_ctxsize(struct crypto_alg *alg, u32 type, u32 mask) { return alg->cra_ctxsize; } int skcipher_null_givencrypt(struct skcipher_givcrypt_request *req) { return crypto_ablkcipher_encrypt(&req->creq); } int skcipher_null_givdecrypt(struct skcipher_givcrypt_request *req) { return crypto_ablkcipher_decrypt(&req->creq); } static int crypto_init_ablkcipher_ops(struct crypto_tfm *tfm, u32 type, u32 mask) { struct ablkcipher_alg *alg = &tfm->__crt_alg->cra_ablkcipher; struct ablkcipher_tfm *crt = &tfm->crt_ablkcipher; if (alg->ivsize > PAGE_SIZE / 8) return -EINVAL; crt->setkey = setkey; crt->encrypt = alg->encrypt; crt->decrypt = alg->decrypt; if (!alg->ivsize) { crt->givencrypt = skcipher_null_givencrypt; crt->givdecrypt = skcipher_null_givdecrypt; } crt->base = __crypto_ablkcipher_cast(tfm); crt->ivsize = alg->ivsize; return 0; } #ifdef CONFIG_NET static int crypto_ablkcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_blkcipher rblkcipher; strncpy(rblkcipher.type, "ablkcipher", sizeof(rblkcipher.type)); strncpy(rblkcipher.geniv, alg->cra_ablkcipher.geniv ?: "<default>", sizeof(rblkcipher.geniv)); rblkcipher.blocksize = alg->cra_blocksize; rblkcipher.min_keysize = alg->cra_ablkcipher.min_keysize; rblkcipher.max_keysize = alg->cra_ablkcipher.max_keysize; rblkcipher.ivsize = alg->cra_ablkcipher.ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER, sizeof(struct crypto_report_blkcipher), &rblkcipher)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } #else static int crypto_ablkcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { return -ENOSYS; } #endif static void crypto_ablkcipher_show(struct seq_file *m, struct crypto_alg *alg) __attribute__ ((unused)); static void crypto_ablkcipher_show(struct seq_file *m, struct crypto_alg *alg) { struct ablkcipher_alg *ablkcipher = &alg->cra_ablkcipher; seq_printf(m, "type : ablkcipher\n"); seq_printf(m, "async : %s\n", alg->cra_flags & CRYPTO_ALG_ASYNC ? "yes" : "no"); seq_printf(m, "blocksize : %u\n", alg->cra_blocksize); seq_printf(m, "min keysize : %u\n", ablkcipher->min_keysize); seq_printf(m, "max keysize : %u\n", ablkcipher->max_keysize); seq_printf(m, "ivsize : %u\n", ablkcipher->ivsize); seq_printf(m, "geniv : %s\n", ablkcipher->geniv ?: "<default>"); } const struct crypto_type crypto_ablkcipher_type = { .ctxsize = crypto_ablkcipher_ctxsize, .init = crypto_init_ablkcipher_ops, #ifdef CONFIG_PROC_FS .show = crypto_ablkcipher_show, #endif .report = crypto_ablkcipher_report, }; EXPORT_SYMBOL_GPL(crypto_ablkcipher_type); static int no_givdecrypt(struct skcipher_givcrypt_request *req) { return -ENOSYS; } static int crypto_init_givcipher_ops(struct crypto_tfm *tfm, u32 type, u32 mask) { struct ablkcipher_alg *alg = &tfm->__crt_alg->cra_ablkcipher; struct ablkcipher_tfm *crt = &tfm->crt_ablkcipher; if (alg->ivsize > PAGE_SIZE / 8) return -EINVAL; crt->setkey = tfm->__crt_alg->cra_flags & CRYPTO_ALG_GENIV ? alg->setkey : setkey; crt->encrypt = alg->encrypt; crt->decrypt = alg->decrypt; crt->givencrypt = alg->givencrypt; crt->givdecrypt = alg->givdecrypt ?: no_givdecrypt; crt->base = __crypto_ablkcipher_cast(tfm); crt->ivsize = alg->ivsize; return 0; } #ifdef CONFIG_NET static int crypto_givcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_blkcipher rblkcipher; strncpy(rblkcipher.type, "givcipher", sizeof(rblkcipher.type)); strncpy(rblkcipher.geniv, alg->cra_ablkcipher.geniv ?: "<built-in>", sizeof(rblkcipher.geniv)); rblkcipher.blocksize = alg->cra_blocksize; rblkcipher.min_keysize = alg->cra_ablkcipher.min_keysize; rblkcipher.max_keysize = alg->cra_ablkcipher.max_keysize; rblkcipher.ivsize = alg->cra_ablkcipher.ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER, sizeof(struct crypto_report_blkcipher), &rblkcipher)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } #else static int crypto_givcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { return -ENOSYS; } #endif static void crypto_givcipher_show(struct seq_file *m, struct crypto_alg *alg) __attribute__ ((unused)); static void crypto_givcipher_show(struct seq_file *m, struct crypto_alg *alg) { struct ablkcipher_alg *ablkcipher = &alg->cra_ablkcipher; seq_printf(m, "type : givcipher\n"); seq_printf(m, "async : %s\n", alg->cra_flags & CRYPTO_ALG_ASYNC ? "yes" : "no"); seq_printf(m, "blocksize : %u\n", alg->cra_blocksize); seq_printf(m, "min keysize : %u\n", ablkcipher->min_keysize); seq_printf(m, "max keysize : %u\n", ablkcipher->max_keysize); seq_printf(m, "ivsize : %u\n", ablkcipher->ivsize); seq_printf(m, "geniv : %s\n", ablkcipher->geniv ?: "<built-in>"); } const struct crypto_type crypto_givcipher_type = { .ctxsize = crypto_ablkcipher_ctxsize, .init = crypto_init_givcipher_ops, #ifdef CONFIG_PROC_FS .show = crypto_givcipher_show, #endif .report = crypto_givcipher_report, }; EXPORT_SYMBOL_GPL(crypto_givcipher_type); const char *crypto_default_geniv(const struct crypto_alg *alg) { if (((alg->cra_flags & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_BLKCIPHER ? alg->cra_blkcipher.ivsize : alg->cra_ablkcipher.ivsize) != alg->cra_blocksize) return "chainiv"; return alg->cra_flags & CRYPTO_ALG_ASYNC ? "eseqiv" : skcipher_default_geniv; } static int crypto_givcipher_default(struct crypto_alg *alg, u32 type, u32 mask) { struct rtattr *tb[3]; struct { struct rtattr attr; struct crypto_attr_type data; } ptype; struct { struct rtattr attr; struct crypto_attr_alg data; } palg; struct crypto_template *tmpl; struct crypto_instance *inst; struct crypto_alg *larval; const char *geniv; int err; larval = crypto_larval_lookup(alg->cra_driver_name, (type & ~CRYPTO_ALG_TYPE_MASK) | CRYPTO_ALG_TYPE_GIVCIPHER, mask | CRYPTO_ALG_TYPE_MASK); err = PTR_ERR(larval); if (IS_ERR(larval)) goto out; err = -EAGAIN; if (!crypto_is_larval(larval)) goto drop_larval; ptype.attr.rta_len = sizeof(ptype); ptype.attr.rta_type = CRYPTOA_TYPE; ptype.data.type = type | CRYPTO_ALG_GENIV; /* GENIV tells the template that we're making a default geniv. */ ptype.data.mask = mask | CRYPTO_ALG_GENIV; tb[0] = &ptype.attr; palg.attr.rta_len = sizeof(palg); palg.attr.rta_type = CRYPTOA_ALG; /* Must use the exact name to locate ourselves. */ memcpy(palg.data.name, alg->cra_driver_name, CRYPTO_MAX_ALG_NAME); tb[1] = &palg.attr; tb[2] = NULL; if ((alg->cra_flags & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_BLKCIPHER) geniv = alg->cra_blkcipher.geniv; else geniv = alg->cra_ablkcipher.geniv; if (!geniv) geniv = crypto_default_geniv(alg); tmpl = crypto_lookup_template(geniv); err = -ENOENT; if (!tmpl) goto kill_larval; inst = tmpl->alloc(tb); err = PTR_ERR(inst); if (IS_ERR(inst)) goto put_tmpl; if ((err = crypto_register_instance(tmpl, inst))) { tmpl->free(inst); goto put_tmpl; } /* Redo the lookup to use the instance we just registered. */ err = -EAGAIN; put_tmpl: crypto_tmpl_put(tmpl); kill_larval: crypto_larval_kill(larval); drop_larval: crypto_mod_put(larval); out: crypto_mod_put(alg); return err; } struct crypto_alg *crypto_lookup_skcipher(const char *name, u32 type, u32 mask) { struct crypto_alg *alg; alg = crypto_alg_mod_lookup(name, type, mask); if (IS_ERR(alg)) return alg; if ((alg->cra_flags & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_GIVCIPHER) return alg; if (!((alg->cra_flags & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_BLKCIPHER ? alg->cra_blkcipher.ivsize : alg->cra_ablkcipher.ivsize)) return alg; crypto_mod_put(alg); alg = crypto_alg_mod_lookup(name, type | CRYPTO_ALG_TESTED, mask & ~CRYPTO_ALG_TESTED); if (IS_ERR(alg)) return alg; if ((alg->cra_flags & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_GIVCIPHER) { if ((alg->cra_flags ^ type ^ ~mask) & CRYPTO_ALG_TESTED) { crypto_mod_put(alg); alg = ERR_PTR(-ENOENT); } return alg; } BUG_ON(!((alg->cra_flags & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_BLKCIPHER ? alg->cra_blkcipher.ivsize : alg->cra_ablkcipher.ivsize)); return ERR_PTR(crypto_givcipher_default(alg, type, mask)); } EXPORT_SYMBOL_GPL(crypto_lookup_skcipher); int crypto_grab_skcipher(struct crypto_skcipher_spawn *spawn, const char *name, u32 type, u32 mask) { struct crypto_alg *alg; int err; type = crypto_skcipher_type(type); mask = crypto_skcipher_mask(mask); alg = crypto_lookup_skcipher(name, type, mask); if (IS_ERR(alg)) return PTR_ERR(alg); err = crypto_init_spawn(&spawn->base, alg, spawn->base.inst, mask); crypto_mod_put(alg); return err; } EXPORT_SYMBOL_GPL(crypto_grab_skcipher); struct crypto_ablkcipher *crypto_alloc_ablkcipher(const char *alg_name, u32 type, u32 mask) { struct crypto_tfm *tfm; int err; type = crypto_skcipher_type(type); mask = crypto_skcipher_mask(mask); for (;;) { struct crypto_alg *alg; alg = crypto_lookup_skcipher(alg_name, type, mask); if (IS_ERR(alg)) { err = PTR_ERR(alg); goto err; } tfm = __crypto_alloc_tfm(alg, type, mask); if (!IS_ERR(tfm)) return __crypto_ablkcipher_cast(tfm); crypto_mod_put(alg); err = PTR_ERR(tfm); err: if (err != -EAGAIN) break; if (signal_pending(current)) { err = -EINTR; break; } } return ERR_PTR(err); } EXPORT_SYMBOL_GPL(crypto_alloc_ablkcipher); static int __init skcipher_module_init(void) { skcipher_default_geniv = num_possible_cpus() > 1 ? "eseqiv" : "chainiv"; return 0; } static void skcipher_module_exit(void) { } module_init(skcipher_module_init); module_exit(skcipher_module_exit);
./CrossVul/dataset_final_sorted/CWE-310/c/good_5666_0
crossvul-cpp_data_good_5867_1
/* * ssl.c v0.0.3 * Copyright (C) 2000 -- DaP <profeta@freemail.c3.hu> * * 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 St, Fifth Floor, Boston, MA 02110-1301, USA */ #ifdef __APPLE__ #define __AVAILABILITYMACROS__ #define DEPRECATED_IN_MAC_OS_X_VERSION_10_7_AND_LATER #endif #include "inet.h" /* make it first to avoid macro redefinitions */ #include <openssl/ssl.h> /* SSL_() */ #include <openssl/err.h> /* ERR_() */ #include <openssl/x509v3.h> #ifdef WIN32 #include <openssl/rand.h> /* RAND_seed() */ #endif #include "../../config.h" #include <time.h> /* asctime() */ #include <string.h> /* strncpy() */ #include "ssl.h" /* struct cert_info */ #include <glib.h> #include <glib/gprintf.h> #include <gio/gio.h> #include "util.h" /* If openssl was built without ec */ #ifndef SSL_OP_SINGLE_ECDH_USE #define SSL_OP_SINGLE_ECDH_USE 0 #endif /* globals */ static struct chiper_info chiper_info; /* static buffer for _SSL_get_cipher_info() */ static char err_buf[256]; /* generic error buffer */ /* +++++ Internal functions +++++ */ static void __SSL_fill_err_buf (char *funcname) { int err; char buf[256]; err = ERR_get_error (); ERR_error_string (err, buf); g_snprintf (err_buf, sizeof (err_buf), "%s: %s (%d)\n", funcname, buf, err); } static void __SSL_critical_error (char *funcname) { __SSL_fill_err_buf (funcname); fprintf (stderr, "%s\n", err_buf); exit (1); } /* +++++ SSL functions +++++ */ SSL_CTX * _SSL_context_init (void (*info_cb_func), int server) { SSL_CTX *ctx; #ifdef WIN32 int i, r; #endif SSLeay_add_ssl_algorithms (); SSL_load_error_strings (); ctx = SSL_CTX_new (server ? SSLv23_server_method() : SSLv23_client_method ()); SSL_CTX_set_session_cache_mode (ctx, SSL_SESS_CACHE_BOTH); SSL_CTX_set_timeout (ctx, 300); SSL_CTX_set_options (ctx, SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3 |SSL_OP_NO_COMPRESSION |SSL_OP_SINGLE_DH_USE|SSL_OP_SINGLE_ECDH_USE |SSL_OP_NO_TICKET |SSL_OP_CIPHER_SERVER_PREFERENCE); /* used in SSL_connect(), SSL_accept() */ SSL_CTX_set_info_callback (ctx, info_cb_func); #ifdef WIN32 /* under win32, OpenSSL needs to be seeded with some randomness */ for (i = 0; i < 128; i++) { r = rand (); RAND_seed ((unsigned char *)&r, sizeof (r)); } #endif return(ctx); } static void ASN1_TIME_snprintf (char *buf, int buf_len, ASN1_TIME * tm) { char *expires = NULL; BIO *inMem = BIO_new (BIO_s_mem ()); ASN1_TIME_print (inMem, tm); BIO_get_mem_data (inMem, &expires); buf[0] = 0; if (expires != NULL) { /* expires is not \0 terminated */ safe_strcpy (buf, expires, MIN(24, buf_len)); } BIO_free (inMem); } static void broke_oneline (char *oneline, char *parray[]) { char *pt, *ppt; int i; i = 0; ppt = pt = oneline + 1; while ((pt = strchr (pt, '/'))) { *pt = 0; parray[i++] = ppt; ppt = ++pt; } parray[i++] = ppt; parray[i] = NULL; } /* FIXME: Master-Key, Extensions, CA bits (openssl x509 -text -in servcert.pem) */ int _SSL_get_cert_info (struct cert_info *cert_info, SSL * ssl) { X509 *peer_cert; EVP_PKEY *peer_pkey; /* EVP_PKEY *ca_pkey; */ /* EVP_PKEY *tmp_pkey; */ char notBefore[64]; char notAfter[64]; int alg; int sign_alg; if (!(peer_cert = SSL_get_peer_certificate (ssl))) return (1); /* FATAL? */ X509_NAME_oneline (X509_get_subject_name (peer_cert), cert_info->subject, sizeof (cert_info->subject)); X509_NAME_oneline (X509_get_issuer_name (peer_cert), cert_info->issuer, sizeof (cert_info->issuer)); broke_oneline (cert_info->subject, cert_info->subject_word); broke_oneline (cert_info->issuer, cert_info->issuer_word); alg = OBJ_obj2nid (peer_cert->cert_info->key->algor->algorithm); sign_alg = OBJ_obj2nid (peer_cert->sig_alg->algorithm); ASN1_TIME_snprintf (notBefore, sizeof (notBefore), X509_get_notBefore (peer_cert)); ASN1_TIME_snprintf (notAfter, sizeof (notAfter), X509_get_notAfter (peer_cert)); peer_pkey = X509_get_pubkey (peer_cert); safe_strcpy (cert_info->algorithm, (alg == NID_undef) ? "Unknown" : OBJ_nid2ln (alg), sizeof (cert_info->algorithm)); cert_info->algorithm_bits = EVP_PKEY_bits (peer_pkey); safe_strcpy (cert_info->sign_algorithm, (sign_alg == NID_undef) ? "Unknown" : OBJ_nid2ln (sign_alg), sizeof (cert_info->sign_algorithm)); /* EVP_PKEY_bits(ca_pkey)); */ cert_info->sign_algorithm_bits = 0; safe_strcpy (cert_info->notbefore, notBefore, sizeof (cert_info->notbefore)); safe_strcpy (cert_info->notafter, notAfter, sizeof (cert_info->notafter)); EVP_PKEY_free (peer_pkey); /* SSL_SESSION_print_fp(stdout, SSL_get_session(ssl)); */ /* if (ssl->session->sess_cert->peer_rsa_tmp) { tmp_pkey = EVP_PKEY_new(); EVP_PKEY_assign_RSA(tmp_pkey, ssl->session->sess_cert->peer_rsa_tmp); cert_info->rsa_tmp_bits = EVP_PKEY_bits (tmp_pkey); EVP_PKEY_free(tmp_pkey); } else fprintf(stderr, "REMOTE SIDE DOESN'T PROVIDES ->peer_rsa_tmp\n"); */ cert_info->rsa_tmp_bits = 0; X509_free (peer_cert); return (0); } struct chiper_info * _SSL_get_cipher_info (SSL * ssl) { const SSL_CIPHER *c; c = SSL_get_current_cipher (ssl); safe_strcpy (chiper_info.version, SSL_CIPHER_get_version (c), sizeof (chiper_info.version)); safe_strcpy (chiper_info.chiper, SSL_CIPHER_get_name (c), sizeof (chiper_info.chiper)); SSL_CIPHER_get_bits (c, &chiper_info.chiper_bits); return (&chiper_info); } int _SSL_send (SSL * ssl, char *buf, int len) { int num; num = SSL_write (ssl, buf, len); switch (SSL_get_error (ssl, num)) { case SSL_ERROR_SSL: /* setup errno! */ /* ??? */ __SSL_fill_err_buf ("SSL_write"); fprintf (stderr, "%s\n", err_buf); break; case SSL_ERROR_SYSCALL: /* ??? */ perror ("SSL_write/write"); break; case SSL_ERROR_ZERO_RETURN: /* fprintf(stderr, "SSL closed on write\n"); */ break; } return (num); } int _SSL_recv (SSL * ssl, char *buf, int len) { int num; num = SSL_read (ssl, buf, len); switch (SSL_get_error (ssl, num)) { case SSL_ERROR_SSL: /* ??? */ __SSL_fill_err_buf ("SSL_read"); fprintf (stderr, "%s\n", err_buf); break; case SSL_ERROR_SYSCALL: /* ??? */ if (!would_block ()) perror ("SSL_read/read"); break; case SSL_ERROR_ZERO_RETURN: /* fprintf(stdeerr, "SSL closed on read\n"); */ break; } return (num); } SSL * _SSL_socket (SSL_CTX *ctx, int sd) { SSL *ssl; if (!(ssl = SSL_new (ctx))) /* FATAL */ __SSL_critical_error ("SSL_new"); SSL_set_fd (ssl, sd); if (ctx->method == SSLv23_client_method()) SSL_set_connect_state (ssl); else SSL_set_accept_state(ssl); return (ssl); } char * _SSL_set_verify (SSL_CTX *ctx, void *verify_callback, char *cacert) { if (!SSL_CTX_set_default_verify_paths (ctx)) { __SSL_fill_err_buf ("SSL_CTX_set_default_verify_paths"); return (err_buf); } /* if (cacert) { if (!SSL_CTX_load_verify_locations (ctx, cacert, NULL)) { __SSL_fill_err_buf ("SSL_CTX_load_verify_locations"); return (err_buf); } } */ SSL_CTX_set_verify (ctx, SSL_VERIFY_PEER, verify_callback); return (NULL); } void _SSL_close (SSL * ssl) { SSL_set_shutdown (ssl, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); SSL_free (ssl); ERR_remove_state (0); /* free state buffer */ } /* Hostname validation code based on OpenBSD's libtls. */ static int _SSL_match_hostname (const char *cert_hostname, const char *hostname) { const char *cert_domain, *domain, *next_dot; if (g_ascii_strcasecmp (cert_hostname, hostname) == 0) return 0; /* Wildcard match? */ if (cert_hostname[0] == '*') { /* * Valid wildcards: * - "*.domain.tld" * - "*.sub.domain.tld" * - etc. * Reject "*.tld". * No attempt to prevent the use of eg. "*.co.uk". */ cert_domain = &cert_hostname[1]; /* Disallow "*" */ if (cert_domain[0] == '\0') return -1; /* Disallow "*foo" */ if (cert_domain[0] != '.') return -1; /* Disallow "*.." */ if (cert_domain[1] == '.') return -1; next_dot = strchr (&cert_domain[1], '.'); /* Disallow "*.bar" */ if (next_dot == NULL) return -1; /* Disallow "*.bar.." */ if (next_dot[1] == '.') return -1; domain = strchr (hostname, '.'); /* No wildcard match against a hostname with no domain part. */ if (domain == NULL || strlen(domain) == 1) return -1; if (g_ascii_strcasecmp (cert_domain, domain) == 0) return 0; } return -1; } static int _SSL_check_subject_altname (X509 *cert, const char *host) { STACK_OF(GENERAL_NAME) *altname_stack = NULL; GInetAddress *addr; GSocketFamily family; int type = GEN_DNS; int count, i; int rv = -1; altname_stack = X509_get_ext_d2i (cert, NID_subject_alt_name, NULL, NULL); if (altname_stack == NULL) return -1; addr = g_inet_address_new_from_string (host); if (addr != NULL) { family = g_inet_address_get_family (addr); if (family == G_SOCKET_FAMILY_IPV4 || family == G_SOCKET_FAMILY_IPV6) type = GEN_IPADD; } count = sk_GENERAL_NAME_num(altname_stack); for (i = 0; i < count; i++) { GENERAL_NAME *altname; altname = sk_GENERAL_NAME_value (altname_stack, i); if (altname->type != type) continue; if (type == GEN_DNS) { unsigned char *data; int format; format = ASN1_STRING_type (altname->d.dNSName); if (format == V_ASN1_IA5STRING) { data = ASN1_STRING_data (altname->d.dNSName); if (ASN1_STRING_length (altname->d.dNSName) != (int)strlen(data)) { g_warning("NUL byte in subjectAltName, probably a malicious certificate.\n"); rv = -2; break; } if (_SSL_match_hostname (data, host) == 0) { rv = 0; break; } } else g_warning ("unhandled subjectAltName dNSName encoding (%d)\n", format); } else if (type == GEN_IPADD) { unsigned char *data; const guint8 *addr_bytes; int datalen, addr_len; datalen = ASN1_STRING_length (altname->d.iPAddress); data = ASN1_STRING_data (altname->d.iPAddress); addr_bytes = g_inet_address_to_bytes (addr); addr_len = (int)g_inet_address_get_native_size (addr); if (datalen == addr_len && memcmp (data, addr_bytes, addr_len) == 0) { rv = 0; break; } } } if (addr != NULL) g_object_unref (addr); sk_GENERAL_NAME_free (altname_stack); return rv; } static int _SSL_check_common_name (X509 *cert, const char *host) { X509_NAME *name; char *common_name = NULL; int common_name_len; int rv = -1; GInetAddress *addr; name = X509_get_subject_name (cert); if (name == NULL) return -1; common_name_len = X509_NAME_get_text_by_NID (name, NID_commonName, NULL, 0); if (common_name_len < 0) return -1; common_name = calloc (common_name_len + 1, 1); if (common_name == NULL) return -1; X509_NAME_get_text_by_NID (name, NID_commonName, common_name, common_name_len + 1); /* NUL bytes in CN? */ if (common_name_len != (int)strlen(common_name)) { g_warning ("NUL byte in Common Name field, probably a malicious certificate.\n"); rv = -2; goto out; } if ((addr = g_inet_address_new_from_string (host)) != NULL) { /* * We don't want to attempt wildcard matching against IP * addresses, so perform a simple comparison here. */ if (g_strcmp0 (common_name, host) == 0) rv = 0; else rv = -1; g_object_unref (addr); } else if (_SSL_match_hostname (common_name, host) == 0) rv = 0; out: free(common_name); return rv; } int _SSL_check_hostname (X509 *cert, const char *host) { int rv; rv = _SSL_check_subject_altname (cert, host); if (rv == 0 || rv == -2) return rv; return _SSL_check_common_name (cert, host); }
./CrossVul/dataset_final_sorted/CWE-310/c/good_5867_1
crossvul-cpp_data_bad_893_2
/* Rijndael (AES) for GnuPG * Copyright (C) 2000, 2001, 2002, 2003, 2007, * 2008, 2011, 2012 Free Software Foundation, Inc. * * This file is part of Libgcrypt. * * Libgcrypt 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. * * Libgcrypt 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 program; if not, see <http://www.gnu.org/licenses/>. ******************************************************************* * The code here is based on the optimized implementation taken from * http://www.esat.kuleuven.ac.be/~rijmen/rijndael/ on Oct 2, 2000, * which carries this notice: *------------------------------------------ * rijndael-alg-fst.c v2.3 April '2000 * * Optimised ANSI C code * * authors: v1.0: Antoon Bosselaers * v2.0: Vincent Rijmen * v2.3: Paulo Barreto * * This code is placed in the public domain. *------------------------------------------ * * The SP800-38a document is available at: * http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf * */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* for memcmp() */ #include "types.h" /* for byte and u32 typedefs */ #include "g10lib.h" #include "cipher.h" #include "bufhelp.h" #include "cipher-selftest.h" #include "rijndael-internal.h" #include "./cipher-internal.h" #ifdef USE_AMD64_ASM /* AMD64 assembly implementations of AES */ extern unsigned int _gcry_aes_amd64_encrypt_block(const void *keysched_enc, unsigned char *out, const unsigned char *in, int rounds, const void *encT); extern unsigned int _gcry_aes_amd64_decrypt_block(const void *keysched_dec, unsigned char *out, const unsigned char *in, int rounds, const void *decT); #endif /*USE_AMD64_ASM*/ #ifdef USE_AESNI /* AES-NI (AMD64 & i386) accelerated implementations of AES */ extern void _gcry_aes_aesni_do_setkey(RIJNDAEL_context *ctx, const byte *key); extern void _gcry_aes_aesni_prepare_decryption(RIJNDAEL_context *ctx); extern unsigned int _gcry_aes_aesni_encrypt (const RIJNDAEL_context *ctx, unsigned char *dst, const unsigned char *src); extern unsigned int _gcry_aes_aesni_decrypt (const RIJNDAEL_context *ctx, unsigned char *dst, const unsigned char *src); extern void _gcry_aes_aesni_cfb_enc (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern void _gcry_aes_aesni_cbc_enc (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int cbc_mac); extern void _gcry_aes_aesni_ctr_enc (void *context, unsigned char *ctr, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern void _gcry_aes_aesni_cfb_dec (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern void _gcry_aes_aesni_cbc_dec (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern size_t _gcry_aes_aesni_ocb_crypt (gcry_cipher_hd_t c, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int encrypt); extern size_t _gcry_aes_aesni_ocb_auth (gcry_cipher_hd_t c, const void *abuf_arg, size_t nblocks); extern void _gcry_aes_aesni_xts_crypt (void *context, unsigned char *tweak, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int encrypt); #endif #ifdef USE_SSSE3 /* SSSE3 (AMD64) vector permutation implementation of AES */ extern void _gcry_aes_ssse3_do_setkey(RIJNDAEL_context *ctx, const byte *key); extern void _gcry_aes_ssse3_prepare_decryption(RIJNDAEL_context *ctx); extern unsigned int _gcry_aes_ssse3_encrypt (const RIJNDAEL_context *ctx, unsigned char *dst, const unsigned char *src); extern unsigned int _gcry_aes_ssse3_decrypt (const RIJNDAEL_context *ctx, unsigned char *dst, const unsigned char *src); extern void _gcry_aes_ssse3_cfb_enc (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern void _gcry_aes_ssse3_cbc_enc (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int cbc_mac); extern void _gcry_aes_ssse3_ctr_enc (void *context, unsigned char *ctr, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern void _gcry_aes_ssse3_cfb_dec (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern void _gcry_aes_ssse3_cbc_dec (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern size_t _gcry_aes_ssse3_ocb_crypt (gcry_cipher_hd_t c, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int encrypt); extern size_t _gcry_aes_ssse3_ocb_auth (gcry_cipher_hd_t c, const void *abuf_arg, size_t nblocks); #endif #ifdef USE_PADLOCK extern unsigned int _gcry_aes_padlock_encrypt (const RIJNDAEL_context *ctx, unsigned char *bx, const unsigned char *ax); extern unsigned int _gcry_aes_padlock_decrypt (const RIJNDAEL_context *ctx, unsigned char *bx, const unsigned char *ax); #endif #ifdef USE_ARM_ASM /* ARM assembly implementations of AES */ extern unsigned int _gcry_aes_arm_encrypt_block(const void *keysched_enc, unsigned char *out, const unsigned char *in, int rounds, const void *encT); extern unsigned int _gcry_aes_arm_decrypt_block(const void *keysched_dec, unsigned char *out, const unsigned char *in, int rounds, const void *decT); #endif /*USE_ARM_ASM*/ #ifdef USE_ARM_CE /* ARMv8 Crypto Extension implementations of AES */ extern void _gcry_aes_armv8_ce_setkey(RIJNDAEL_context *ctx, const byte *key); extern void _gcry_aes_armv8_ce_prepare_decryption(RIJNDAEL_context *ctx); extern unsigned int _gcry_aes_armv8_ce_encrypt(const RIJNDAEL_context *ctx, unsigned char *dst, const unsigned char *src); extern unsigned int _gcry_aes_armv8_ce_decrypt(const RIJNDAEL_context *ctx, unsigned char *dst, const unsigned char *src); extern void _gcry_aes_armv8_ce_cfb_enc (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern void _gcry_aes_armv8_ce_cbc_enc (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int cbc_mac); extern void _gcry_aes_armv8_ce_ctr_enc (void *context, unsigned char *ctr, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern void _gcry_aes_armv8_ce_cfb_dec (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern void _gcry_aes_armv8_ce_cbc_dec (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks); extern size_t _gcry_aes_armv8_ce_ocb_crypt (gcry_cipher_hd_t c, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int encrypt); extern size_t _gcry_aes_armv8_ce_ocb_auth (gcry_cipher_hd_t c, const void *abuf_arg, size_t nblocks); extern void _gcry_aes_armv8_ce_xts_crypt (void *context, unsigned char *tweak, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int encrypt); #endif /*USE_ARM_ASM*/ static unsigned int do_encrypt (const RIJNDAEL_context *ctx, unsigned char *bx, const unsigned char *ax); static unsigned int do_decrypt (const RIJNDAEL_context *ctx, unsigned char *bx, const unsigned char *ax); /* All the numbers. */ #include "rijndael-tables.h" /* Function prototypes. */ static const char *selftest(void); /* Prefetching for encryption/decryption tables. */ static void prefetch_table(const volatile byte *tab, size_t len) { size_t i; for (i = 0; i < len; i += 8 * 32) { (void)tab[i + 0 * 32]; (void)tab[i + 1 * 32]; (void)tab[i + 2 * 32]; (void)tab[i + 3 * 32]; (void)tab[i + 4 * 32]; (void)tab[i + 5 * 32]; (void)tab[i + 6 * 32]; (void)tab[i + 7 * 32]; } (void)tab[len - 1]; } static void prefetch_enc(void) { prefetch_table((const void *)encT, sizeof(encT)); } static void prefetch_dec(void) { prefetch_table((const void *)&dec_tables, sizeof(dec_tables)); } /* Perform the key setup. */ static gcry_err_code_t do_setkey (RIJNDAEL_context *ctx, const byte *key, const unsigned keylen, gcry_cipher_hd_t hd) { static int initialized = 0; static const char *selftest_failed = 0; int rounds; int i,j, r, t, rconpointer = 0; int KC; #if defined(USE_AESNI) || defined(USE_PADLOCK) || defined(USE_SSSE3) \ || defined(USE_ARM_CE) unsigned int hwfeatures; #endif (void)hd; /* The on-the-fly self tests are only run in non-fips mode. In fips mode explicit self-tests are required. Actually the on-the-fly self-tests are not fully thread-safe and it might happen that a failed self-test won't get noticed in another thread. FIXME: We might want to have a central registry of succeeded self-tests. */ if (!fips_mode () && !initialized) { initialized = 1; selftest_failed = selftest (); if (selftest_failed) log_error ("%s\n", selftest_failed ); } if (selftest_failed) return GPG_ERR_SELFTEST_FAILED; if( keylen == 128/8 ) { rounds = 10; KC = 4; } else if ( keylen == 192/8 ) { rounds = 12; KC = 6; } else if ( keylen == 256/8 ) { rounds = 14; KC = 8; } else return GPG_ERR_INV_KEYLEN; ctx->rounds = rounds; #if defined(USE_AESNI) || defined(USE_PADLOCK) || defined(USE_SSSE3) \ || defined(USE_ARM_CE) hwfeatures = _gcry_get_hw_features (); #endif ctx->decryption_prepared = 0; #ifdef USE_PADLOCK ctx->use_padlock = 0; #endif #ifdef USE_AESNI ctx->use_aesni = 0; #endif #ifdef USE_SSSE3 ctx->use_ssse3 = 0; #endif #ifdef USE_ARM_CE ctx->use_arm_ce = 0; #endif if (0) { ; } #ifdef USE_AESNI else if (hwfeatures & HWF_INTEL_AESNI) { ctx->encrypt_fn = _gcry_aes_aesni_encrypt; ctx->decrypt_fn = _gcry_aes_aesni_decrypt; ctx->prefetch_enc_fn = NULL; ctx->prefetch_dec_fn = NULL; ctx->use_aesni = 1; ctx->use_avx = !!(hwfeatures & HWF_INTEL_AVX); ctx->use_avx2 = !!(hwfeatures & HWF_INTEL_AVX2); if (hd) { hd->bulk.cfb_enc = _gcry_aes_aesni_cfb_enc; hd->bulk.cfb_dec = _gcry_aes_aesni_cfb_dec; hd->bulk.cbc_enc = _gcry_aes_aesni_cbc_enc; hd->bulk.cbc_dec = _gcry_aes_aesni_cbc_dec; hd->bulk.ctr_enc = _gcry_aes_aesni_ctr_enc; hd->bulk.ocb_crypt = _gcry_aes_aesni_ocb_crypt; hd->bulk.ocb_auth = _gcry_aes_aesni_ocb_auth; hd->bulk.xts_crypt = _gcry_aes_aesni_xts_crypt; } } #endif #ifdef USE_PADLOCK else if (hwfeatures & HWF_PADLOCK_AES && keylen == 128/8) { ctx->encrypt_fn = _gcry_aes_padlock_encrypt; ctx->decrypt_fn = _gcry_aes_padlock_decrypt; ctx->prefetch_enc_fn = NULL; ctx->prefetch_dec_fn = NULL; ctx->use_padlock = 1; memcpy (ctx->padlockkey, key, keylen); } #endif #ifdef USE_SSSE3 else if (hwfeatures & HWF_INTEL_SSSE3) { ctx->encrypt_fn = _gcry_aes_ssse3_encrypt; ctx->decrypt_fn = _gcry_aes_ssse3_decrypt; ctx->prefetch_enc_fn = NULL; ctx->prefetch_dec_fn = NULL; ctx->use_ssse3 = 1; if (hd) { hd->bulk.cfb_enc = _gcry_aes_ssse3_cfb_enc; hd->bulk.cfb_dec = _gcry_aes_ssse3_cfb_dec; hd->bulk.cbc_enc = _gcry_aes_ssse3_cbc_enc; hd->bulk.cbc_dec = _gcry_aes_ssse3_cbc_dec; hd->bulk.ctr_enc = _gcry_aes_ssse3_ctr_enc; hd->bulk.ocb_crypt = _gcry_aes_ssse3_ocb_crypt; hd->bulk.ocb_auth = _gcry_aes_ssse3_ocb_auth; } } #endif #ifdef USE_ARM_CE else if (hwfeatures & HWF_ARM_AES) { ctx->encrypt_fn = _gcry_aes_armv8_ce_encrypt; ctx->decrypt_fn = _gcry_aes_armv8_ce_decrypt; ctx->prefetch_enc_fn = NULL; ctx->prefetch_dec_fn = NULL; ctx->use_arm_ce = 1; if (hd) { hd->bulk.cfb_enc = _gcry_aes_armv8_ce_cfb_enc; hd->bulk.cfb_dec = _gcry_aes_armv8_ce_cfb_dec; hd->bulk.cbc_enc = _gcry_aes_armv8_ce_cbc_enc; hd->bulk.cbc_dec = _gcry_aes_armv8_ce_cbc_dec; hd->bulk.ctr_enc = _gcry_aes_armv8_ce_ctr_enc; hd->bulk.ocb_crypt = _gcry_aes_armv8_ce_ocb_crypt; hd->bulk.ocb_auth = _gcry_aes_armv8_ce_ocb_auth; hd->bulk.xts_crypt = _gcry_aes_armv8_ce_xts_crypt; } } #endif else { ctx->encrypt_fn = do_encrypt; ctx->decrypt_fn = do_decrypt; ctx->prefetch_enc_fn = prefetch_enc; ctx->prefetch_dec_fn = prefetch_dec; } /* NB: We don't yet support Padlock hardware key generation. */ if (0) { ; } #ifdef USE_AESNI else if (ctx->use_aesni) _gcry_aes_aesni_do_setkey (ctx, key); #endif #ifdef USE_SSSE3 else if (ctx->use_ssse3) _gcry_aes_ssse3_do_setkey (ctx, key); #endif #ifdef USE_ARM_CE else if (ctx->use_arm_ce) _gcry_aes_armv8_ce_setkey (ctx, key); #endif else { const byte *sbox = ((const byte *)encT) + 1; union { PROPERLY_ALIGNED_TYPE dummy; byte data[MAXKC][4]; u32 data32[MAXKC]; } tkk[2]; #define k tkk[0].data #define k_u32 tkk[0].data32 #define tk tkk[1].data #define tk_u32 tkk[1].data32 #define W (ctx->keyschenc) #define W_u32 (ctx->keyschenc32) prefetch_enc(); for (i = 0; i < keylen; i++) { k[i >> 2][i & 3] = key[i]; } for (j = KC-1; j >= 0; j--) { tk_u32[j] = k_u32[j]; } r = 0; t = 0; /* Copy values into round key array. */ for (j = 0; (j < KC) && (r < rounds + 1); ) { for (; (j < KC) && (t < 4); j++, t++) { W_u32[r][t] = le_bswap32(tk_u32[j]); } if (t == 4) { r++; t = 0; } } while (r < rounds + 1) { /* While not enough round key material calculated calculate new values. */ tk[0][0] ^= sbox[tk[KC-1][1] * 4]; tk[0][1] ^= sbox[tk[KC-1][2] * 4]; tk[0][2] ^= sbox[tk[KC-1][3] * 4]; tk[0][3] ^= sbox[tk[KC-1][0] * 4]; tk[0][0] ^= rcon[rconpointer++]; if (KC != 8) { for (j = 1; j < KC; j++) { tk_u32[j] ^= tk_u32[j-1]; } } else { for (j = 1; j < KC/2; j++) { tk_u32[j] ^= tk_u32[j-1]; } tk[KC/2][0] ^= sbox[tk[KC/2 - 1][0] * 4]; tk[KC/2][1] ^= sbox[tk[KC/2 - 1][1] * 4]; tk[KC/2][2] ^= sbox[tk[KC/2 - 1][2] * 4]; tk[KC/2][3] ^= sbox[tk[KC/2 - 1][3] * 4]; for (j = KC/2 + 1; j < KC; j++) { tk_u32[j] ^= tk_u32[j-1]; } } /* Copy values into round key array. */ for (j = 0; (j < KC) && (r < rounds + 1); ) { for (; (j < KC) && (t < 4); j++, t++) { W_u32[r][t] = le_bswap32(tk_u32[j]); } if (t == 4) { r++; t = 0; } } } #undef W #undef tk #undef k #undef W_u32 #undef tk_u32 #undef k_u32 wipememory(&tkk, sizeof(tkk)); } return 0; } static gcry_err_code_t rijndael_setkey (void *context, const byte *key, const unsigned keylen, gcry_cipher_hd_t hd) { RIJNDAEL_context *ctx = context; return do_setkey (ctx, key, keylen, hd); } /* Make a decryption key from an encryption key. */ static void prepare_decryption( RIJNDAEL_context *ctx ) { int r; if (0) ; #ifdef USE_AESNI else if (ctx->use_aesni) { _gcry_aes_aesni_prepare_decryption (ctx); } #endif /*USE_AESNI*/ #ifdef USE_SSSE3 else if (ctx->use_ssse3) { _gcry_aes_ssse3_prepare_decryption (ctx); } #endif /*USE_SSSE3*/ #ifdef USE_ARM_CE else if (ctx->use_arm_ce) { _gcry_aes_armv8_ce_prepare_decryption (ctx); } #endif /*USE_SSSE3*/ #ifdef USE_PADLOCK else if (ctx->use_padlock) { /* Padlock does not need decryption subkeys. */ } #endif /*USE_PADLOCK*/ else { const byte *sbox = ((const byte *)encT) + 1; prefetch_enc(); prefetch_dec(); ctx->keyschdec32[0][0] = ctx->keyschenc32[0][0]; ctx->keyschdec32[0][1] = ctx->keyschenc32[0][1]; ctx->keyschdec32[0][2] = ctx->keyschenc32[0][2]; ctx->keyschdec32[0][3] = ctx->keyschenc32[0][3]; for (r = 1; r < ctx->rounds; r++) { u32 *wi = ctx->keyschenc32[r]; u32 *wo = ctx->keyschdec32[r]; u32 wt; wt = wi[0]; wo[0] = rol(decT[sbox[(byte)(wt >> 0) * 4]], 8 * 0) ^ rol(decT[sbox[(byte)(wt >> 8) * 4]], 8 * 1) ^ rol(decT[sbox[(byte)(wt >> 16) * 4]], 8 * 2) ^ rol(decT[sbox[(byte)(wt >> 24) * 4]], 8 * 3); wt = wi[1]; wo[1] = rol(decT[sbox[(byte)(wt >> 0) * 4]], 8 * 0) ^ rol(decT[sbox[(byte)(wt >> 8) * 4]], 8 * 1) ^ rol(decT[sbox[(byte)(wt >> 16) * 4]], 8 * 2) ^ rol(decT[sbox[(byte)(wt >> 24) * 4]], 8 * 3); wt = wi[2]; wo[2] = rol(decT[sbox[(byte)(wt >> 0) * 4]], 8 * 0) ^ rol(decT[sbox[(byte)(wt >> 8) * 4]], 8 * 1) ^ rol(decT[sbox[(byte)(wt >> 16) * 4]], 8 * 2) ^ rol(decT[sbox[(byte)(wt >> 24) * 4]], 8 * 3); wt = wi[3]; wo[3] = rol(decT[sbox[(byte)(wt >> 0) * 4]], 8 * 0) ^ rol(decT[sbox[(byte)(wt >> 8) * 4]], 8 * 1) ^ rol(decT[sbox[(byte)(wt >> 16) * 4]], 8 * 2) ^ rol(decT[sbox[(byte)(wt >> 24) * 4]], 8 * 3); } ctx->keyschdec32[r][0] = ctx->keyschenc32[r][0]; ctx->keyschdec32[r][1] = ctx->keyschenc32[r][1]; ctx->keyschdec32[r][2] = ctx->keyschenc32[r][2]; ctx->keyschdec32[r][3] = ctx->keyschenc32[r][3]; } } #if !defined(USE_ARM_ASM) && !defined(USE_AMD64_ASM) /* Encrypt one block. A and B may be the same. */ static unsigned int do_encrypt_fn (const RIJNDAEL_context *ctx, unsigned char *b, const unsigned char *a) { #define rk (ctx->keyschenc32) const byte *sbox = ((const byte *)encT) + 1; int rounds = ctx->rounds; int r; u32 sa[4]; u32 sb[4]; sb[0] = buf_get_le32(a + 0); sb[1] = buf_get_le32(a + 4); sb[2] = buf_get_le32(a + 8); sb[3] = buf_get_le32(a + 12); sa[0] = sb[0] ^ rk[0][0]; sa[1] = sb[1] ^ rk[0][1]; sa[2] = sb[2] ^ rk[0][2]; sa[3] = sb[3] ^ rk[0][3]; sb[0] = rol(encT[(byte)(sa[0] >> (0 * 8))], (0 * 8)); sb[3] = rol(encT[(byte)(sa[0] >> (1 * 8))], (1 * 8)); sb[2] = rol(encT[(byte)(sa[0] >> (2 * 8))], (2 * 8)); sb[1] = rol(encT[(byte)(sa[0] >> (3 * 8))], (3 * 8)); sa[0] = rk[1][0] ^ sb[0]; sb[1] ^= rol(encT[(byte)(sa[1] >> (0 * 8))], (0 * 8)); sa[0] ^= rol(encT[(byte)(sa[1] >> (1 * 8))], (1 * 8)); sb[3] ^= rol(encT[(byte)(sa[1] >> (2 * 8))], (2 * 8)); sb[2] ^= rol(encT[(byte)(sa[1] >> (3 * 8))], (3 * 8)); sa[1] = rk[1][1] ^ sb[1]; sb[2] ^= rol(encT[(byte)(sa[2] >> (0 * 8))], (0 * 8)); sa[1] ^= rol(encT[(byte)(sa[2] >> (1 * 8))], (1 * 8)); sa[0] ^= rol(encT[(byte)(sa[2] >> (2 * 8))], (2 * 8)); sb[3] ^= rol(encT[(byte)(sa[2] >> (3 * 8))], (3 * 8)); sa[2] = rk[1][2] ^ sb[2]; sb[3] ^= rol(encT[(byte)(sa[3] >> (0 * 8))], (0 * 8)); sa[2] ^= rol(encT[(byte)(sa[3] >> (1 * 8))], (1 * 8)); sa[1] ^= rol(encT[(byte)(sa[3] >> (2 * 8))], (2 * 8)); sa[0] ^= rol(encT[(byte)(sa[3] >> (3 * 8))], (3 * 8)); sa[3] = rk[1][3] ^ sb[3]; for (r = 2; r < rounds; r++) { sb[0] = rol(encT[(byte)(sa[0] >> (0 * 8))], (0 * 8)); sb[3] = rol(encT[(byte)(sa[0] >> (1 * 8))], (1 * 8)); sb[2] = rol(encT[(byte)(sa[0] >> (2 * 8))], (2 * 8)); sb[1] = rol(encT[(byte)(sa[0] >> (3 * 8))], (3 * 8)); sa[0] = rk[r][0] ^ sb[0]; sb[1] ^= rol(encT[(byte)(sa[1] >> (0 * 8))], (0 * 8)); sa[0] ^= rol(encT[(byte)(sa[1] >> (1 * 8))], (1 * 8)); sb[3] ^= rol(encT[(byte)(sa[1] >> (2 * 8))], (2 * 8)); sb[2] ^= rol(encT[(byte)(sa[1] >> (3 * 8))], (3 * 8)); sa[1] = rk[r][1] ^ sb[1]; sb[2] ^= rol(encT[(byte)(sa[2] >> (0 * 8))], (0 * 8)); sa[1] ^= rol(encT[(byte)(sa[2] >> (1 * 8))], (1 * 8)); sa[0] ^= rol(encT[(byte)(sa[2] >> (2 * 8))], (2 * 8)); sb[3] ^= rol(encT[(byte)(sa[2] >> (3 * 8))], (3 * 8)); sa[2] = rk[r][2] ^ sb[2]; sb[3] ^= rol(encT[(byte)(sa[3] >> (0 * 8))], (0 * 8)); sa[2] ^= rol(encT[(byte)(sa[3] >> (1 * 8))], (1 * 8)); sa[1] ^= rol(encT[(byte)(sa[3] >> (2 * 8))], (2 * 8)); sa[0] ^= rol(encT[(byte)(sa[3] >> (3 * 8))], (3 * 8)); sa[3] = rk[r][3] ^ sb[3]; r++; sb[0] = rol(encT[(byte)(sa[0] >> (0 * 8))], (0 * 8)); sb[3] = rol(encT[(byte)(sa[0] >> (1 * 8))], (1 * 8)); sb[2] = rol(encT[(byte)(sa[0] >> (2 * 8))], (2 * 8)); sb[1] = rol(encT[(byte)(sa[0] >> (3 * 8))], (3 * 8)); sa[0] = rk[r][0] ^ sb[0]; sb[1] ^= rol(encT[(byte)(sa[1] >> (0 * 8))], (0 * 8)); sa[0] ^= rol(encT[(byte)(sa[1] >> (1 * 8))], (1 * 8)); sb[3] ^= rol(encT[(byte)(sa[1] >> (2 * 8))], (2 * 8)); sb[2] ^= rol(encT[(byte)(sa[1] >> (3 * 8))], (3 * 8)); sa[1] = rk[r][1] ^ sb[1]; sb[2] ^= rol(encT[(byte)(sa[2] >> (0 * 8))], (0 * 8)); sa[1] ^= rol(encT[(byte)(sa[2] >> (1 * 8))], (1 * 8)); sa[0] ^= rol(encT[(byte)(sa[2] >> (2 * 8))], (2 * 8)); sb[3] ^= rol(encT[(byte)(sa[2] >> (3 * 8))], (3 * 8)); sa[2] = rk[r][2] ^ sb[2]; sb[3] ^= rol(encT[(byte)(sa[3] >> (0 * 8))], (0 * 8)); sa[2] ^= rol(encT[(byte)(sa[3] >> (1 * 8))], (1 * 8)); sa[1] ^= rol(encT[(byte)(sa[3] >> (2 * 8))], (2 * 8)); sa[0] ^= rol(encT[(byte)(sa[3] >> (3 * 8))], (3 * 8)); sa[3] = rk[r][3] ^ sb[3]; } /* Last round is special. */ sb[0] = (sbox[(byte)(sa[0] >> (0 * 8)) * 4]) << (0 * 8); sb[3] = (sbox[(byte)(sa[0] >> (1 * 8)) * 4]) << (1 * 8); sb[2] = (sbox[(byte)(sa[0] >> (2 * 8)) * 4]) << (2 * 8); sb[1] = (sbox[(byte)(sa[0] >> (3 * 8)) * 4]) << (3 * 8); sa[0] = rk[r][0] ^ sb[0]; sb[1] ^= (sbox[(byte)(sa[1] >> (0 * 8)) * 4]) << (0 * 8); sa[0] ^= (sbox[(byte)(sa[1] >> (1 * 8)) * 4]) << (1 * 8); sb[3] ^= (sbox[(byte)(sa[1] >> (2 * 8)) * 4]) << (2 * 8); sb[2] ^= (sbox[(byte)(sa[1] >> (3 * 8)) * 4]) << (3 * 8); sa[1] = rk[r][1] ^ sb[1]; sb[2] ^= (sbox[(byte)(sa[2] >> (0 * 8)) * 4]) << (0 * 8); sa[1] ^= (sbox[(byte)(sa[2] >> (1 * 8)) * 4]) << (1 * 8); sa[0] ^= (sbox[(byte)(sa[2] >> (2 * 8)) * 4]) << (2 * 8); sb[3] ^= (sbox[(byte)(sa[2] >> (3 * 8)) * 4]) << (3 * 8); sa[2] = rk[r][2] ^ sb[2]; sb[3] ^= (sbox[(byte)(sa[3] >> (0 * 8)) * 4]) << (0 * 8); sa[2] ^= (sbox[(byte)(sa[3] >> (1 * 8)) * 4]) << (1 * 8); sa[1] ^= (sbox[(byte)(sa[3] >> (2 * 8)) * 4]) << (2 * 8); sa[0] ^= (sbox[(byte)(sa[3] >> (3 * 8)) * 4]) << (3 * 8); sa[3] = rk[r][3] ^ sb[3]; buf_put_le32(b + 0, sa[0]); buf_put_le32(b + 4, sa[1]); buf_put_le32(b + 8, sa[2]); buf_put_le32(b + 12, sa[3]); #undef rk return (56 + 2*sizeof(int)); } #endif /*!USE_ARM_ASM && !USE_AMD64_ASM*/ static unsigned int do_encrypt (const RIJNDAEL_context *ctx, unsigned char *bx, const unsigned char *ax) { #ifdef USE_AMD64_ASM return _gcry_aes_amd64_encrypt_block(ctx->keyschenc, bx, ax, ctx->rounds, encT); #elif defined(USE_ARM_ASM) return _gcry_aes_arm_encrypt_block(ctx->keyschenc, bx, ax, ctx->rounds, encT); #else return do_encrypt_fn (ctx, bx, ax); #endif /* !USE_ARM_ASM && !USE_AMD64_ASM*/ } static unsigned int rijndael_encrypt (void *context, byte *b, const byte *a) { RIJNDAEL_context *ctx = context; if (ctx->prefetch_enc_fn) ctx->prefetch_enc_fn(); return ctx->encrypt_fn (ctx, b, a); } /* Bulk encryption of complete blocks in CFB mode. Caller needs to make sure that IV is aligned on an unsigned long boundary. This function is only intended for the bulk encryption feature of cipher.c. */ void _gcry_aes_cfb_enc (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks) { RIJNDAEL_context *ctx = context; unsigned char *outbuf = outbuf_arg; const unsigned char *inbuf = inbuf_arg; unsigned int burn_depth = 0; if (0) ; #ifdef USE_AESNI else if (ctx->use_aesni) { _gcry_aes_aesni_cfb_enc (ctx, iv, outbuf, inbuf, nblocks); return; } #endif /*USE_AESNI*/ #ifdef USE_SSSE3 else if (ctx->use_ssse3) { _gcry_aes_ssse3_cfb_enc (ctx, iv, outbuf, inbuf, nblocks); return; } #endif /*USE_SSSE3*/ #ifdef USE_ARM_CE else if (ctx->use_arm_ce) { _gcry_aes_armv8_ce_cfb_enc (ctx, iv, outbuf, inbuf, nblocks); return; } #endif /*USE_ARM_CE*/ else { rijndael_cryptfn_t encrypt_fn = ctx->encrypt_fn; if (ctx->prefetch_enc_fn) ctx->prefetch_enc_fn(); for ( ;nblocks; nblocks-- ) { /* Encrypt the IV. */ burn_depth = encrypt_fn (ctx, iv, iv); /* XOR the input with the IV and store input into IV. */ cipher_block_xor_2dst(outbuf, iv, inbuf, BLOCKSIZE); outbuf += BLOCKSIZE; inbuf += BLOCKSIZE; } } if (burn_depth) _gcry_burn_stack (burn_depth + 4 * sizeof(void *)); } /* Bulk encryption of complete blocks in CBC mode. Caller needs to make sure that IV is aligned on an unsigned long boundary. This function is only intended for the bulk encryption feature of cipher.c. */ void _gcry_aes_cbc_enc (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int cbc_mac) { RIJNDAEL_context *ctx = context; unsigned char *outbuf = outbuf_arg; const unsigned char *inbuf = inbuf_arg; unsigned char *last_iv; unsigned int burn_depth = 0; if (0) ; #ifdef USE_AESNI else if (ctx->use_aesni) { _gcry_aes_aesni_cbc_enc (ctx, iv, outbuf, inbuf, nblocks, cbc_mac); return; } #endif /*USE_AESNI*/ #ifdef USE_SSSE3 else if (ctx->use_ssse3) { _gcry_aes_ssse3_cbc_enc (ctx, iv, outbuf, inbuf, nblocks, cbc_mac); return; } #endif /*USE_SSSE3*/ #ifdef USE_ARM_CE else if (ctx->use_arm_ce) { _gcry_aes_armv8_ce_cbc_enc (ctx, iv, outbuf, inbuf, nblocks, cbc_mac); return; } #endif /*USE_ARM_CE*/ else { rijndael_cryptfn_t encrypt_fn = ctx->encrypt_fn; if (ctx->prefetch_enc_fn) ctx->prefetch_enc_fn(); last_iv = iv; for ( ;nblocks; nblocks-- ) { cipher_block_xor(outbuf, inbuf, last_iv, BLOCKSIZE); burn_depth = encrypt_fn (ctx, outbuf, outbuf); last_iv = outbuf; inbuf += BLOCKSIZE; if (!cbc_mac) outbuf += BLOCKSIZE; } if (last_iv != iv) cipher_block_cpy (iv, last_iv, BLOCKSIZE); } if (burn_depth) _gcry_burn_stack (burn_depth + 4 * sizeof(void *)); } /* Bulk encryption of complete blocks in CTR mode. Caller needs to make sure that CTR is aligned on a 16 byte boundary if AESNI; the minimum alignment is for an u32. This function is only intended for the bulk encryption feature of cipher.c. CTR is expected to be of size BLOCKSIZE. */ void _gcry_aes_ctr_enc (void *context, unsigned char *ctr, void *outbuf_arg, const void *inbuf_arg, size_t nblocks) { RIJNDAEL_context *ctx = context; unsigned char *outbuf = outbuf_arg; const unsigned char *inbuf = inbuf_arg; unsigned int burn_depth = 0; if (0) ; #ifdef USE_AESNI else if (ctx->use_aesni) { _gcry_aes_aesni_ctr_enc (ctx, ctr, outbuf, inbuf, nblocks); return; } #endif /*USE_AESNI*/ #ifdef USE_SSSE3 else if (ctx->use_ssse3) { _gcry_aes_ssse3_ctr_enc (ctx, ctr, outbuf, inbuf, nblocks); return; } #endif /*USE_SSSE3*/ #ifdef USE_ARM_CE else if (ctx->use_arm_ce) { _gcry_aes_armv8_ce_ctr_enc (ctx, ctr, outbuf, inbuf, nblocks); return; } #endif /*USE_ARM_CE*/ else { union { unsigned char x1[16] ATTR_ALIGNED_16; u32 x32[4]; } tmp; rijndael_cryptfn_t encrypt_fn = ctx->encrypt_fn; if (ctx->prefetch_enc_fn) ctx->prefetch_enc_fn(); for ( ;nblocks; nblocks-- ) { /* Encrypt the counter. */ burn_depth = encrypt_fn (ctx, tmp.x1, ctr); /* XOR the input with the encrypted counter and store in output. */ cipher_block_xor(outbuf, tmp.x1, inbuf, BLOCKSIZE); outbuf += BLOCKSIZE; inbuf += BLOCKSIZE; /* Increment the counter. */ cipher_block_add(ctr, 1, BLOCKSIZE); } wipememory(&tmp, sizeof(tmp)); } if (burn_depth) _gcry_burn_stack (burn_depth + 4 * sizeof(void *)); } #if !defined(USE_ARM_ASM) && !defined(USE_AMD64_ASM) /* Decrypt one block. A and B may be the same. */ static unsigned int do_decrypt_fn (const RIJNDAEL_context *ctx, unsigned char *b, const unsigned char *a) { #define rk (ctx->keyschdec32) int rounds = ctx->rounds; int r; u32 sa[4]; u32 sb[4]; sb[0] = buf_get_le32(a + 0); sb[1] = buf_get_le32(a + 4); sb[2] = buf_get_le32(a + 8); sb[3] = buf_get_le32(a + 12); sa[0] = sb[0] ^ rk[rounds][0]; sa[1] = sb[1] ^ rk[rounds][1]; sa[2] = sb[2] ^ rk[rounds][2]; sa[3] = sb[3] ^ rk[rounds][3]; for (r = rounds - 1; r > 1; r--) { sb[0] = rol(decT[(byte)(sa[0] >> (0 * 8))], (0 * 8)); sb[1] = rol(decT[(byte)(sa[0] >> (1 * 8))], (1 * 8)); sb[2] = rol(decT[(byte)(sa[0] >> (2 * 8))], (2 * 8)); sb[3] = rol(decT[(byte)(sa[0] >> (3 * 8))], (3 * 8)); sa[0] = rk[r][0] ^ sb[0]; sb[1] ^= rol(decT[(byte)(sa[1] >> (0 * 8))], (0 * 8)); sb[2] ^= rol(decT[(byte)(sa[1] >> (1 * 8))], (1 * 8)); sb[3] ^= rol(decT[(byte)(sa[1] >> (2 * 8))], (2 * 8)); sa[0] ^= rol(decT[(byte)(sa[1] >> (3 * 8))], (3 * 8)); sa[1] = rk[r][1] ^ sb[1]; sb[2] ^= rol(decT[(byte)(sa[2] >> (0 * 8))], (0 * 8)); sb[3] ^= rol(decT[(byte)(sa[2] >> (1 * 8))], (1 * 8)); sa[0] ^= rol(decT[(byte)(sa[2] >> (2 * 8))], (2 * 8)); sa[1] ^= rol(decT[(byte)(sa[2] >> (3 * 8))], (3 * 8)); sa[2] = rk[r][2] ^ sb[2]; sb[3] ^= rol(decT[(byte)(sa[3] >> (0 * 8))], (0 * 8)); sa[0] ^= rol(decT[(byte)(sa[3] >> (1 * 8))], (1 * 8)); sa[1] ^= rol(decT[(byte)(sa[3] >> (2 * 8))], (2 * 8)); sa[2] ^= rol(decT[(byte)(sa[3] >> (3 * 8))], (3 * 8)); sa[3] = rk[r][3] ^ sb[3]; r--; sb[0] = rol(decT[(byte)(sa[0] >> (0 * 8))], (0 * 8)); sb[1] = rol(decT[(byte)(sa[0] >> (1 * 8))], (1 * 8)); sb[2] = rol(decT[(byte)(sa[0] >> (2 * 8))], (2 * 8)); sb[3] = rol(decT[(byte)(sa[0] >> (3 * 8))], (3 * 8)); sa[0] = rk[r][0] ^ sb[0]; sb[1] ^= rol(decT[(byte)(sa[1] >> (0 * 8))], (0 * 8)); sb[2] ^= rol(decT[(byte)(sa[1] >> (1 * 8))], (1 * 8)); sb[3] ^= rol(decT[(byte)(sa[1] >> (2 * 8))], (2 * 8)); sa[0] ^= rol(decT[(byte)(sa[1] >> (3 * 8))], (3 * 8)); sa[1] = rk[r][1] ^ sb[1]; sb[2] ^= rol(decT[(byte)(sa[2] >> (0 * 8))], (0 * 8)); sb[3] ^= rol(decT[(byte)(sa[2] >> (1 * 8))], (1 * 8)); sa[0] ^= rol(decT[(byte)(sa[2] >> (2 * 8))], (2 * 8)); sa[1] ^= rol(decT[(byte)(sa[2] >> (3 * 8))], (3 * 8)); sa[2] = rk[r][2] ^ sb[2]; sb[3] ^= rol(decT[(byte)(sa[3] >> (0 * 8))], (0 * 8)); sa[0] ^= rol(decT[(byte)(sa[3] >> (1 * 8))], (1 * 8)); sa[1] ^= rol(decT[(byte)(sa[3] >> (2 * 8))], (2 * 8)); sa[2] ^= rol(decT[(byte)(sa[3] >> (3 * 8))], (3 * 8)); sa[3] = rk[r][3] ^ sb[3]; } sb[0] = rol(decT[(byte)(sa[0] >> (0 * 8))], (0 * 8)); sb[1] = rol(decT[(byte)(sa[0] >> (1 * 8))], (1 * 8)); sb[2] = rol(decT[(byte)(sa[0] >> (2 * 8))], (2 * 8)); sb[3] = rol(decT[(byte)(sa[0] >> (3 * 8))], (3 * 8)); sa[0] = rk[1][0] ^ sb[0]; sb[1] ^= rol(decT[(byte)(sa[1] >> (0 * 8))], (0 * 8)); sb[2] ^= rol(decT[(byte)(sa[1] >> (1 * 8))], (1 * 8)); sb[3] ^= rol(decT[(byte)(sa[1] >> (2 * 8))], (2 * 8)); sa[0] ^= rol(decT[(byte)(sa[1] >> (3 * 8))], (3 * 8)); sa[1] = rk[1][1] ^ sb[1]; sb[2] ^= rol(decT[(byte)(sa[2] >> (0 * 8))], (0 * 8)); sb[3] ^= rol(decT[(byte)(sa[2] >> (1 * 8))], (1 * 8)); sa[0] ^= rol(decT[(byte)(sa[2] >> (2 * 8))], (2 * 8)); sa[1] ^= rol(decT[(byte)(sa[2] >> (3 * 8))], (3 * 8)); sa[2] = rk[1][2] ^ sb[2]; sb[3] ^= rol(decT[(byte)(sa[3] >> (0 * 8))], (0 * 8)); sa[0] ^= rol(decT[(byte)(sa[3] >> (1 * 8))], (1 * 8)); sa[1] ^= rol(decT[(byte)(sa[3] >> (2 * 8))], (2 * 8)); sa[2] ^= rol(decT[(byte)(sa[3] >> (3 * 8))], (3 * 8)); sa[3] = rk[1][3] ^ sb[3]; /* Last round is special. */ sb[0] = inv_sbox[(byte)(sa[0] >> (0 * 8))] << (0 * 8); sb[1] = inv_sbox[(byte)(sa[0] >> (1 * 8))] << (1 * 8); sb[2] = inv_sbox[(byte)(sa[0] >> (2 * 8))] << (2 * 8); sb[3] = inv_sbox[(byte)(sa[0] >> (3 * 8))] << (3 * 8); sa[0] = sb[0] ^ rk[0][0]; sb[1] ^= inv_sbox[(byte)(sa[1] >> (0 * 8))] << (0 * 8); sb[2] ^= inv_sbox[(byte)(sa[1] >> (1 * 8))] << (1 * 8); sb[3] ^= inv_sbox[(byte)(sa[1] >> (2 * 8))] << (2 * 8); sa[0] ^= inv_sbox[(byte)(sa[1] >> (3 * 8))] << (3 * 8); sa[1] = sb[1] ^ rk[0][1]; sb[2] ^= inv_sbox[(byte)(sa[2] >> (0 * 8))] << (0 * 8); sb[3] ^= inv_sbox[(byte)(sa[2] >> (1 * 8))] << (1 * 8); sa[0] ^= inv_sbox[(byte)(sa[2] >> (2 * 8))] << (2 * 8); sa[1] ^= inv_sbox[(byte)(sa[2] >> (3 * 8))] << (3 * 8); sa[2] = sb[2] ^ rk[0][2]; sb[3] ^= inv_sbox[(byte)(sa[3] >> (0 * 8))] << (0 * 8); sa[0] ^= inv_sbox[(byte)(sa[3] >> (1 * 8))] << (1 * 8); sa[1] ^= inv_sbox[(byte)(sa[3] >> (2 * 8))] << (2 * 8); sa[2] ^= inv_sbox[(byte)(sa[3] >> (3 * 8))] << (3 * 8); sa[3] = sb[3] ^ rk[0][3]; buf_put_le32(b + 0, sa[0]); buf_put_le32(b + 4, sa[1]); buf_put_le32(b + 8, sa[2]); buf_put_le32(b + 12, sa[3]); #undef rk return (56+2*sizeof(int)); } #endif /*!USE_ARM_ASM && !USE_AMD64_ASM*/ /* Decrypt one block. AX and BX may be the same. */ static unsigned int do_decrypt (const RIJNDAEL_context *ctx, unsigned char *bx, const unsigned char *ax) { #ifdef USE_AMD64_ASM return _gcry_aes_amd64_decrypt_block(ctx->keyschdec, bx, ax, ctx->rounds, &dec_tables); #elif defined(USE_ARM_ASM) return _gcry_aes_arm_decrypt_block(ctx->keyschdec, bx, ax, ctx->rounds, &dec_tables); #else return do_decrypt_fn (ctx, bx, ax); #endif /*!USE_ARM_ASM && !USE_AMD64_ASM*/ } static inline void check_decryption_preparation (RIJNDAEL_context *ctx) { if ( !ctx->decryption_prepared ) { prepare_decryption ( ctx ); ctx->decryption_prepared = 1; } } static unsigned int rijndael_decrypt (void *context, byte *b, const byte *a) { RIJNDAEL_context *ctx = context; check_decryption_preparation (ctx); if (ctx->prefetch_dec_fn) ctx->prefetch_dec_fn(); return ctx->decrypt_fn (ctx, b, a); } /* Bulk decryption of complete blocks in CFB mode. Caller needs to make sure that IV is aligned on an unsigned long boundary. This function is only intended for the bulk encryption feature of cipher.c. */ void _gcry_aes_cfb_dec (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks) { RIJNDAEL_context *ctx = context; unsigned char *outbuf = outbuf_arg; const unsigned char *inbuf = inbuf_arg; unsigned int burn_depth = 0; if (0) ; #ifdef USE_AESNI else if (ctx->use_aesni) { _gcry_aes_aesni_cfb_dec (ctx, iv, outbuf, inbuf, nblocks); return; } #endif /*USE_AESNI*/ #ifdef USE_SSSE3 else if (ctx->use_ssse3) { _gcry_aes_ssse3_cfb_dec (ctx, iv, outbuf, inbuf, nblocks); return; } #endif /*USE_SSSE3*/ #ifdef USE_ARM_CE else if (ctx->use_arm_ce) { _gcry_aes_armv8_ce_cfb_dec (ctx, iv, outbuf, inbuf, nblocks); return; } #endif /*USE_ARM_CE*/ else { rijndael_cryptfn_t encrypt_fn = ctx->encrypt_fn; if (ctx->prefetch_enc_fn) ctx->prefetch_enc_fn(); for ( ;nblocks; nblocks-- ) { burn_depth = encrypt_fn (ctx, iv, iv); cipher_block_xor_n_copy(outbuf, iv, inbuf, BLOCKSIZE); outbuf += BLOCKSIZE; inbuf += BLOCKSIZE; } } if (burn_depth) _gcry_burn_stack (burn_depth + 4 * sizeof(void *)); } /* Bulk decryption of complete blocks in CBC mode. Caller needs to make sure that IV is aligned on an unsigned long boundary. This function is only intended for the bulk encryption feature of cipher.c. */ void _gcry_aes_cbc_dec (void *context, unsigned char *iv, void *outbuf_arg, const void *inbuf_arg, size_t nblocks) { RIJNDAEL_context *ctx = context; unsigned char *outbuf = outbuf_arg; const unsigned char *inbuf = inbuf_arg; unsigned int burn_depth = 0; if (0) ; #ifdef USE_AESNI else if (ctx->use_aesni) { _gcry_aes_aesni_cbc_dec (ctx, iv, outbuf, inbuf, nblocks); return; } #endif /*USE_AESNI*/ #ifdef USE_SSSE3 else if (ctx->use_ssse3) { _gcry_aes_ssse3_cbc_dec (ctx, iv, outbuf, inbuf, nblocks); return; } #endif /*USE_SSSE3*/ #ifdef USE_ARM_CE else if (ctx->use_arm_ce) { _gcry_aes_armv8_ce_cbc_dec (ctx, iv, outbuf, inbuf, nblocks); return; } #endif /*USE_ARM_CE*/ else { unsigned char savebuf[BLOCKSIZE] ATTR_ALIGNED_16; rijndael_cryptfn_t decrypt_fn = ctx->decrypt_fn; check_decryption_preparation (ctx); if (ctx->prefetch_dec_fn) ctx->prefetch_dec_fn(); for ( ;nblocks; nblocks-- ) { /* INBUF is needed later and it may be identical to OUTBUF, so store the intermediate result to SAVEBUF. */ burn_depth = decrypt_fn (ctx, savebuf, inbuf); cipher_block_xor_n_copy_2(outbuf, savebuf, iv, inbuf, BLOCKSIZE); inbuf += BLOCKSIZE; outbuf += BLOCKSIZE; } wipememory(savebuf, sizeof(savebuf)); } if (burn_depth) _gcry_burn_stack (burn_depth + 4 * sizeof(void *)); } /* Bulk encryption/decryption of complete blocks in OCB mode. */ size_t _gcry_aes_ocb_crypt (gcry_cipher_hd_t c, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int encrypt) { RIJNDAEL_context *ctx = (void *)&c->context.c; unsigned char *outbuf = outbuf_arg; const unsigned char *inbuf = inbuf_arg; unsigned int burn_depth = 0; if (0) ; #ifdef USE_AESNI else if (ctx->use_aesni) { return _gcry_aes_aesni_ocb_crypt (c, outbuf, inbuf, nblocks, encrypt); } #endif /*USE_AESNI*/ #ifdef USE_SSSE3 else if (ctx->use_ssse3) { return _gcry_aes_ssse3_ocb_crypt (c, outbuf, inbuf, nblocks, encrypt); } #endif /*USE_SSSE3*/ #ifdef USE_ARM_CE else if (ctx->use_arm_ce) { return _gcry_aes_armv8_ce_ocb_crypt (c, outbuf, inbuf, nblocks, encrypt); } #endif /*USE_ARM_CE*/ else if (encrypt) { union { unsigned char x1[16] ATTR_ALIGNED_16; u32 x32[4]; } l_tmp; rijndael_cryptfn_t encrypt_fn = ctx->encrypt_fn; if (ctx->prefetch_enc_fn) ctx->prefetch_enc_fn(); for ( ;nblocks; nblocks-- ) { u64 i = ++c->u_mode.ocb.data_nblocks; const unsigned char *l = ocb_get_l(c, i); /* Offset_i = Offset_{i-1} xor L_{ntz(i)} */ cipher_block_xor_1 (c->u_iv.iv, l, BLOCKSIZE); cipher_block_cpy (l_tmp.x1, inbuf, BLOCKSIZE); /* Checksum_i = Checksum_{i-1} xor P_i */ cipher_block_xor_1 (c->u_ctr.ctr, l_tmp.x1, BLOCKSIZE); /* C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) */ cipher_block_xor_1 (l_tmp.x1, c->u_iv.iv, BLOCKSIZE); burn_depth = encrypt_fn (ctx, l_tmp.x1, l_tmp.x1); cipher_block_xor_1 (l_tmp.x1, c->u_iv.iv, BLOCKSIZE); cipher_block_cpy (outbuf, l_tmp.x1, BLOCKSIZE); inbuf += BLOCKSIZE; outbuf += BLOCKSIZE; } } else { union { unsigned char x1[16] ATTR_ALIGNED_16; u32 x32[4]; } l_tmp; rijndael_cryptfn_t decrypt_fn = ctx->decrypt_fn; check_decryption_preparation (ctx); if (ctx->prefetch_dec_fn) ctx->prefetch_dec_fn(); for ( ;nblocks; nblocks-- ) { u64 i = ++c->u_mode.ocb.data_nblocks; const unsigned char *l = ocb_get_l(c, i); /* Offset_i = Offset_{i-1} xor L_{ntz(i)} */ cipher_block_xor_1 (c->u_iv.iv, l, BLOCKSIZE); cipher_block_cpy (l_tmp.x1, inbuf, BLOCKSIZE); /* C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) */ cipher_block_xor_1 (l_tmp.x1, c->u_iv.iv, BLOCKSIZE); burn_depth = decrypt_fn (ctx, l_tmp.x1, l_tmp.x1); cipher_block_xor_1 (l_tmp.x1, c->u_iv.iv, BLOCKSIZE); /* Checksum_i = Checksum_{i-1} xor P_i */ cipher_block_xor_1 (c->u_ctr.ctr, l_tmp.x1, BLOCKSIZE); cipher_block_cpy (outbuf, l_tmp.x1, BLOCKSIZE); inbuf += BLOCKSIZE; outbuf += BLOCKSIZE; } } if (burn_depth) _gcry_burn_stack (burn_depth + 4 * sizeof(void *)); return 0; } /* Bulk authentication of complete blocks in OCB mode. */ size_t _gcry_aes_ocb_auth (gcry_cipher_hd_t c, const void *abuf_arg, size_t nblocks) { RIJNDAEL_context *ctx = (void *)&c->context.c; const unsigned char *abuf = abuf_arg; unsigned int burn_depth = 0; if (0) ; #ifdef USE_AESNI else if (ctx->use_aesni) { return _gcry_aes_aesni_ocb_auth (c, abuf, nblocks); } #endif /*USE_AESNI*/ #ifdef USE_SSSE3 else if (ctx->use_ssse3) { return _gcry_aes_ssse3_ocb_auth (c, abuf, nblocks); } #endif /*USE_SSSE3*/ #ifdef USE_ARM_CE else if (ctx->use_arm_ce) { return _gcry_aes_armv8_ce_ocb_auth (c, abuf, nblocks); } #endif /*USE_ARM_CE*/ else { union { unsigned char x1[16] ATTR_ALIGNED_16; u32 x32[4]; } l_tmp; rijndael_cryptfn_t encrypt_fn = ctx->encrypt_fn; if (ctx->prefetch_enc_fn) ctx->prefetch_enc_fn(); for ( ;nblocks; nblocks-- ) { u64 i = ++c->u_mode.ocb.aad_nblocks; const unsigned char *l = ocb_get_l(c, i); /* Offset_i = Offset_{i-1} xor L_{ntz(i)} */ cipher_block_xor_1 (c->u_mode.ocb.aad_offset, l, BLOCKSIZE); /* Sum_i = Sum_{i-1} xor ENCIPHER(K, A_i xor Offset_i) */ cipher_block_xor (l_tmp.x1, c->u_mode.ocb.aad_offset, abuf, BLOCKSIZE); burn_depth = encrypt_fn (ctx, l_tmp.x1, l_tmp.x1); cipher_block_xor_1 (c->u_mode.ocb.aad_sum, l_tmp.x1, BLOCKSIZE); abuf += BLOCKSIZE; } wipememory(&l_tmp, sizeof(l_tmp)); } if (burn_depth) _gcry_burn_stack (burn_depth + 4 * sizeof(void *)); return 0; } /* Bulk encryption/decryption of complete blocks in XTS mode. */ void _gcry_aes_xts_crypt (void *context, unsigned char *tweak, void *outbuf_arg, const void *inbuf_arg, size_t nblocks, int encrypt) { RIJNDAEL_context *ctx = context; unsigned char *outbuf = outbuf_arg; const unsigned char *inbuf = inbuf_arg; unsigned int burn_depth = 0; rijndael_cryptfn_t crypt_fn; u64 tweak_lo, tweak_hi, tweak_next_lo, tweak_next_hi, tmp_lo, tmp_hi, carry; if (0) ; #ifdef USE_AESNI else if (ctx->use_aesni) { _gcry_aes_aesni_xts_crypt (ctx, tweak, outbuf, inbuf, nblocks, encrypt); return; } #endif /*USE_AESNI*/ #ifdef USE_ARM_CE else if (ctx->use_arm_ce) { _gcry_aes_armv8_ce_xts_crypt (ctx, tweak, outbuf, inbuf, nblocks, encrypt); return; } #endif /*USE_ARM_CE*/ else { if (encrypt) { if (ctx->prefetch_enc_fn) ctx->prefetch_enc_fn(); crypt_fn = ctx->encrypt_fn; } else { check_decryption_preparation (ctx); if (ctx->prefetch_dec_fn) ctx->prefetch_dec_fn(); crypt_fn = ctx->decrypt_fn; } tweak_next_lo = buf_get_le64 (tweak + 0); tweak_next_hi = buf_get_le64 (tweak + 8); while (nblocks) { tweak_lo = tweak_next_lo; tweak_hi = tweak_next_hi; /* Xor-Encrypt/Decrypt-Xor block. */ tmp_lo = buf_get_le64 (inbuf + 0) ^ tweak_lo; tmp_hi = buf_get_le64 (inbuf + 8) ^ tweak_hi; buf_put_le64 (outbuf + 0, tmp_lo); buf_put_le64 (outbuf + 8, tmp_hi); /* Generate next tweak. */ carry = -(tweak_next_hi >> 63) & 0x87; tweak_next_hi = (tweak_next_hi << 1) + (tweak_next_lo >> 63); tweak_next_lo = (tweak_next_lo << 1) ^ carry; burn_depth = crypt_fn (ctx, outbuf, outbuf); buf_put_le64 (outbuf + 0, buf_get_le64 (outbuf + 0) ^ tweak_lo); buf_put_le64 (outbuf + 8, buf_get_le64 (outbuf + 8) ^ tweak_hi); outbuf += GCRY_XTS_BLOCK_LEN; inbuf += GCRY_XTS_BLOCK_LEN; nblocks--; } buf_put_le64 (tweak + 0, tweak_next_lo); buf_put_le64 (tweak + 8, tweak_next_hi); } if (burn_depth) _gcry_burn_stack (burn_depth + 5 * sizeof(void *)); } /* Run the self-tests for AES 128. Returns NULL on success. */ static const char* selftest_basic_128 (void) { RIJNDAEL_context *ctx; unsigned char *ctxmem; unsigned char scratch[16]; /* The test vectors are from the AES supplied ones; more or less randomly taken from ecb_tbl.txt (I=42,81,14) */ #if 1 static const unsigned char plaintext_128[16] = { 0x01,0x4B,0xAF,0x22,0x78,0xA6,0x9D,0x33, 0x1D,0x51,0x80,0x10,0x36,0x43,0xE9,0x9A }; static const unsigned char key_128[16] = { 0xE8,0xE9,0xEA,0xEB,0xED,0xEE,0xEF,0xF0, 0xF2,0xF3,0xF4,0xF5,0xF7,0xF8,0xF9,0xFA }; static const unsigned char ciphertext_128[16] = { 0x67,0x43,0xC3,0xD1,0x51,0x9A,0xB4,0xF2, 0xCD,0x9A,0x78,0xAB,0x09,0xA5,0x11,0xBD }; #else /* Test vectors from fips-197, appendix C. */ # warning debug test vectors in use static const unsigned char plaintext_128[16] = { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77, 0x88,0x99,0xaa,0xbb,0xcc,0xdd,0xee,0xff }; static const unsigned char key_128[16] = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07, 0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f /* 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, */ /* 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c */ }; static const unsigned char ciphertext_128[16] = { 0x69,0xc4,0xe0,0xd8,0x6a,0x7b,0x04,0x30, 0xd8,0xcd,0xb7,0x80,0x70,0xb4,0xc5,0x5a }; #endif /* Because gcc/ld can only align the CTX struct on 8 bytes on the stack, we need to allocate that context on the heap. */ ctx = _gcry_cipher_selftest_alloc_ctx (sizeof *ctx, &ctxmem); if (!ctx) return "failed to allocate memory"; rijndael_setkey (ctx, key_128, sizeof (key_128), NULL); rijndael_encrypt (ctx, scratch, plaintext_128); if (memcmp (scratch, ciphertext_128, sizeof (ciphertext_128))) { xfree (ctxmem); return "AES-128 test encryption failed."; } rijndael_decrypt (ctx, scratch, scratch); xfree (ctxmem); if (memcmp (scratch, plaintext_128, sizeof (plaintext_128))) return "AES-128 test decryption failed."; return NULL; } /* Run the self-tests for AES 192. Returns NULL on success. */ static const char* selftest_basic_192 (void) { RIJNDAEL_context *ctx; unsigned char *ctxmem; unsigned char scratch[16]; static unsigned char plaintext_192[16] = { 0x76,0x77,0x74,0x75,0xF1,0xF2,0xF3,0xF4, 0xF8,0xF9,0xE6,0xE7,0x77,0x70,0x71,0x72 }; static unsigned char key_192[24] = { 0x04,0x05,0x06,0x07,0x09,0x0A,0x0B,0x0C, 0x0E,0x0F,0x10,0x11,0x13,0x14,0x15,0x16, 0x18,0x19,0x1A,0x1B,0x1D,0x1E,0x1F,0x20 }; static const unsigned char ciphertext_192[16] = { 0x5D,0x1E,0xF2,0x0D,0xCE,0xD6,0xBC,0xBC, 0x12,0x13,0x1A,0xC7,0xC5,0x47,0x88,0xAA }; ctx = _gcry_cipher_selftest_alloc_ctx (sizeof *ctx, &ctxmem); if (!ctx) return "failed to allocate memory"; rijndael_setkey (ctx, key_192, sizeof(key_192), NULL); rijndael_encrypt (ctx, scratch, plaintext_192); if (memcmp (scratch, ciphertext_192, sizeof (ciphertext_192))) { xfree (ctxmem); return "AES-192 test encryption failed."; } rijndael_decrypt (ctx, scratch, scratch); xfree (ctxmem); if (memcmp (scratch, plaintext_192, sizeof (plaintext_192))) return "AES-192 test decryption failed."; return NULL; } /* Run the self-tests for AES 256. Returns NULL on success. */ static const char* selftest_basic_256 (void) { RIJNDAEL_context *ctx; unsigned char *ctxmem; unsigned char scratch[16]; static unsigned char plaintext_256[16] = { 0x06,0x9A,0x00,0x7F,0xC7,0x6A,0x45,0x9F, 0x98,0xBA,0xF9,0x17,0xFE,0xDF,0x95,0x21 }; static unsigned char key_256[32] = { 0x08,0x09,0x0A,0x0B,0x0D,0x0E,0x0F,0x10, 0x12,0x13,0x14,0x15,0x17,0x18,0x19,0x1A, 0x1C,0x1D,0x1E,0x1F,0x21,0x22,0x23,0x24, 0x26,0x27,0x28,0x29,0x2B,0x2C,0x2D,0x2E }; static const unsigned char ciphertext_256[16] = { 0x08,0x0E,0x95,0x17,0xEB,0x16,0x77,0x71, 0x9A,0xCF,0x72,0x80,0x86,0x04,0x0A,0xE3 }; ctx = _gcry_cipher_selftest_alloc_ctx (sizeof *ctx, &ctxmem); if (!ctx) return "failed to allocate memory"; rijndael_setkey (ctx, key_256, sizeof(key_256), NULL); rijndael_encrypt (ctx, scratch, plaintext_256); if (memcmp (scratch, ciphertext_256, sizeof (ciphertext_256))) { xfree (ctxmem); return "AES-256 test encryption failed."; } rijndael_decrypt (ctx, scratch, scratch); xfree (ctxmem); if (memcmp (scratch, plaintext_256, sizeof (plaintext_256))) return "AES-256 test decryption failed."; return NULL; } /* Run the self-tests for AES-CTR-128, tests IV increment of bulk CTR encryption. Returns NULL on success. */ static const char* selftest_ctr_128 (void) { const int nblocks = 8+1; const int blocksize = BLOCKSIZE; const int context_size = sizeof(RIJNDAEL_context); return _gcry_selftest_helper_ctr("AES", &rijndael_setkey, &rijndael_encrypt, &_gcry_aes_ctr_enc, nblocks, blocksize, context_size); } /* Run the self-tests for AES-CBC-128, tests bulk CBC decryption. Returns NULL on success. */ static const char* selftest_cbc_128 (void) { const int nblocks = 8+2; const int blocksize = BLOCKSIZE; const int context_size = sizeof(RIJNDAEL_context); return _gcry_selftest_helper_cbc("AES", &rijndael_setkey, &rijndael_encrypt, &_gcry_aes_cbc_dec, nblocks, blocksize, context_size); } /* Run the self-tests for AES-CFB-128, tests bulk CFB decryption. Returns NULL on success. */ static const char* selftest_cfb_128 (void) { const int nblocks = 8+2; const int blocksize = BLOCKSIZE; const int context_size = sizeof(RIJNDAEL_context); return _gcry_selftest_helper_cfb("AES", &rijndael_setkey, &rijndael_encrypt, &_gcry_aes_cfb_dec, nblocks, blocksize, context_size); } /* Run all the self-tests and return NULL on success. This function is used for the on-the-fly self-tests. */ static const char * selftest (void) { const char *r; if ( (r = selftest_basic_128 ()) || (r = selftest_basic_192 ()) || (r = selftest_basic_256 ()) ) return r; if ( (r = selftest_ctr_128 ()) ) return r; if ( (r = selftest_cbc_128 ()) ) return r; if ( (r = selftest_cfb_128 ()) ) return r; return r; } /* SP800-38a.pdf for AES-128. */ static const char * selftest_fips_128_38a (int requested_mode) { static const struct tv { int mode; const unsigned char key[16]; const unsigned char iv[16]; struct { const unsigned char input[16]; const unsigned char output[16]; } data[4]; } tv[2] = { { GCRY_CIPHER_MODE_CFB, /* F.3.13, CFB128-AES128 */ { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c }, { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }, { { { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a }, { 0x3b, 0x3f, 0xd9, 0x2e, 0xb7, 0x2d, 0xad, 0x20, 0x33, 0x34, 0x49, 0xf8, 0xe8, 0x3c, 0xfb, 0x4a } }, { { 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51 }, { 0xc8, 0xa6, 0x45, 0x37, 0xa0, 0xb3, 0xa9, 0x3f, 0xcd, 0xe3, 0xcd, 0xad, 0x9f, 0x1c, 0xe5, 0x8b } }, { { 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef }, { 0x26, 0x75, 0x1f, 0x67, 0xa3, 0xcb, 0xb1, 0x40, 0xb1, 0x80, 0x8c, 0xf1, 0x87, 0xa4, 0xf4, 0xdf } }, { { 0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10 }, { 0xc0, 0x4b, 0x05, 0x35, 0x7c, 0x5d, 0x1c, 0x0e, 0xea, 0xc4, 0xc6, 0x6f, 0x9f, 0xf7, 0xf2, 0xe6 } } } }, { GCRY_CIPHER_MODE_OFB, { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c }, { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }, { { { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a }, { 0x3b, 0x3f, 0xd9, 0x2e, 0xb7, 0x2d, 0xad, 0x20, 0x33, 0x34, 0x49, 0xf8, 0xe8, 0x3c, 0xfb, 0x4a } }, { { 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51 }, { 0x77, 0x89, 0x50, 0x8d, 0x16, 0x91, 0x8f, 0x03, 0xf5, 0x3c, 0x52, 0xda, 0xc5, 0x4e, 0xd8, 0x25 } }, { { 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef }, { 0x97, 0x40, 0x05, 0x1e, 0x9c, 0x5f, 0xec, 0xf6, 0x43, 0x44, 0xf7, 0xa8, 0x22, 0x60, 0xed, 0xcc } }, { { 0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10 }, { 0x30, 0x4c, 0x65, 0x28, 0xf6, 0x59, 0xc7, 0x78, 0x66, 0xa5, 0x10, 0xd9, 0xc1, 0xd6, 0xae, 0x5e } }, } } }; unsigned char scratch[16]; gpg_error_t err; int tvi, idx; gcry_cipher_hd_t hdenc = NULL; gcry_cipher_hd_t hddec = NULL; #define Fail(a) do { \ _gcry_cipher_close (hdenc); \ _gcry_cipher_close (hddec); \ return a; \ } while (0) gcry_assert (sizeof tv[0].data[0].input == sizeof scratch); gcry_assert (sizeof tv[0].data[0].output == sizeof scratch); for (tvi=0; tvi < DIM (tv); tvi++) if (tv[tvi].mode == requested_mode) break; if (tvi == DIM (tv)) Fail ("no test data for this mode"); err = _gcry_cipher_open (&hdenc, GCRY_CIPHER_AES, tv[tvi].mode, 0); if (err) Fail ("open"); err = _gcry_cipher_open (&hddec, GCRY_CIPHER_AES, tv[tvi].mode, 0); if (err) Fail ("open"); err = _gcry_cipher_setkey (hdenc, tv[tvi].key, sizeof tv[tvi].key); if (!err) err = _gcry_cipher_setkey (hddec, tv[tvi].key, sizeof tv[tvi].key); if (err) Fail ("set key"); err = _gcry_cipher_setiv (hdenc, tv[tvi].iv, sizeof tv[tvi].iv); if (!err) err = _gcry_cipher_setiv (hddec, tv[tvi].iv, sizeof tv[tvi].iv); if (err) Fail ("set IV"); for (idx=0; idx < DIM (tv[tvi].data); idx++) { err = _gcry_cipher_encrypt (hdenc, scratch, sizeof scratch, tv[tvi].data[idx].input, sizeof tv[tvi].data[idx].input); if (err) Fail ("encrypt command"); if (memcmp (scratch, tv[tvi].data[idx].output, sizeof scratch)) Fail ("encrypt mismatch"); err = _gcry_cipher_decrypt (hddec, scratch, sizeof scratch, tv[tvi].data[idx].output, sizeof tv[tvi].data[idx].output); if (err) Fail ("decrypt command"); if (memcmp (scratch, tv[tvi].data[idx].input, sizeof scratch)) Fail ("decrypt mismatch"); } #undef Fail _gcry_cipher_close (hdenc); _gcry_cipher_close (hddec); return NULL; } /* Complete selftest for AES-128 with all modes and driver code. */ static gpg_err_code_t selftest_fips_128 (int extended, selftest_report_func_t report) { const char *what; const char *errtxt; what = "low-level"; errtxt = selftest_basic_128 (); if (errtxt) goto failed; if (extended) { what = "cfb"; errtxt = selftest_fips_128_38a (GCRY_CIPHER_MODE_CFB); if (errtxt) goto failed; what = "ofb"; errtxt = selftest_fips_128_38a (GCRY_CIPHER_MODE_OFB); if (errtxt) goto failed; } return 0; /* Succeeded. */ failed: if (report) report ("cipher", GCRY_CIPHER_AES128, what, errtxt); return GPG_ERR_SELFTEST_FAILED; } /* Complete selftest for AES-192. */ static gpg_err_code_t selftest_fips_192 (int extended, selftest_report_func_t report) { const char *what; const char *errtxt; (void)extended; /* No extended tests available. */ what = "low-level"; errtxt = selftest_basic_192 (); if (errtxt) goto failed; return 0; /* Succeeded. */ failed: if (report) report ("cipher", GCRY_CIPHER_AES192, what, errtxt); return GPG_ERR_SELFTEST_FAILED; } /* Complete selftest for AES-256. */ static gpg_err_code_t selftest_fips_256 (int extended, selftest_report_func_t report) { const char *what; const char *errtxt; (void)extended; /* No extended tests available. */ what = "low-level"; errtxt = selftest_basic_256 (); if (errtxt) goto failed; return 0; /* Succeeded. */ failed: if (report) report ("cipher", GCRY_CIPHER_AES256, what, errtxt); return GPG_ERR_SELFTEST_FAILED; } /* Run a full self-test for ALGO and return 0 on success. */ static gpg_err_code_t run_selftests (int algo, int extended, selftest_report_func_t report) { gpg_err_code_t ec; switch (algo) { case GCRY_CIPHER_AES128: ec = selftest_fips_128 (extended, report); break; case GCRY_CIPHER_AES192: ec = selftest_fips_192 (extended, report); break; case GCRY_CIPHER_AES256: ec = selftest_fips_256 (extended, report); break; default: ec = GPG_ERR_CIPHER_ALGO; break; } return ec; } static const char *rijndael_names[] = { "RIJNDAEL", "AES128", "AES-128", NULL }; static gcry_cipher_oid_spec_t rijndael_oids[] = { { "2.16.840.1.101.3.4.1.1", GCRY_CIPHER_MODE_ECB }, { "2.16.840.1.101.3.4.1.2", GCRY_CIPHER_MODE_CBC }, { "2.16.840.1.101.3.4.1.3", GCRY_CIPHER_MODE_OFB }, { "2.16.840.1.101.3.4.1.4", GCRY_CIPHER_MODE_CFB }, { NULL } }; gcry_cipher_spec_t _gcry_cipher_spec_aes = { GCRY_CIPHER_AES, {0, 1}, "AES", rijndael_names, rijndael_oids, 16, 128, sizeof (RIJNDAEL_context), rijndael_setkey, rijndael_encrypt, rijndael_decrypt, NULL, NULL, run_selftests }; static const char *rijndael192_names[] = { "RIJNDAEL192", "AES-192", NULL }; static gcry_cipher_oid_spec_t rijndael192_oids[] = { { "2.16.840.1.101.3.4.1.21", GCRY_CIPHER_MODE_ECB }, { "2.16.840.1.101.3.4.1.22", GCRY_CIPHER_MODE_CBC }, { "2.16.840.1.101.3.4.1.23", GCRY_CIPHER_MODE_OFB }, { "2.16.840.1.101.3.4.1.24", GCRY_CIPHER_MODE_CFB }, { NULL } }; gcry_cipher_spec_t _gcry_cipher_spec_aes192 = { GCRY_CIPHER_AES192, {0, 1}, "AES192", rijndael192_names, rijndael192_oids, 16, 192, sizeof (RIJNDAEL_context), rijndael_setkey, rijndael_encrypt, rijndael_decrypt, NULL, NULL, run_selftests }; static const char *rijndael256_names[] = { "RIJNDAEL256", "AES-256", NULL }; static gcry_cipher_oid_spec_t rijndael256_oids[] = { { "2.16.840.1.101.3.4.1.41", GCRY_CIPHER_MODE_ECB }, { "2.16.840.1.101.3.4.1.42", GCRY_CIPHER_MODE_CBC }, { "2.16.840.1.101.3.4.1.43", GCRY_CIPHER_MODE_OFB }, { "2.16.840.1.101.3.4.1.44", GCRY_CIPHER_MODE_CFB }, { NULL } }; gcry_cipher_spec_t _gcry_cipher_spec_aes256 = { GCRY_CIPHER_AES256, {0, 1}, "AES256", rijndael256_names, rijndael256_oids, 16, 256, sizeof (RIJNDAEL_context), rijndael_setkey, rijndael_encrypt, rijndael_decrypt, NULL, NULL, run_selftests };
./CrossVul/dataset_final_sorted/CWE-310/c/bad_893_2
crossvul-cpp_data_good_3783_2
/* * Copyright (C) 2007 Oracle. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License v2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 021110-1307, USA. */ #include <linux/kernel.h> #include <linux/bio.h> #include <linux/buffer_head.h> #include <linux/file.h> #include <linux/fs.h> #include <linux/pagemap.h> #include <linux/highmem.h> #include <linux/time.h> #include <linux/init.h> #include <linux/string.h> #include <linux/backing-dev.h> #include <linux/mpage.h> #include <linux/swap.h> #include <linux/writeback.h> #include <linux/statfs.h> #include <linux/compat.h> #include <linux/bit_spinlock.h> #include <linux/xattr.h> #include <linux/posix_acl.h> #include <linux/falloc.h> #include <linux/slab.h> #include <linux/ratelimit.h> #include <linux/mount.h> #include "compat.h" #include "ctree.h" #include "disk-io.h" #include "transaction.h" #include "btrfs_inode.h" #include "ioctl.h" #include "print-tree.h" #include "ordered-data.h" #include "xattr.h" #include "tree-log.h" #include "volumes.h" #include "compression.h" #include "locking.h" #include "free-space-cache.h" #include "inode-map.h" struct btrfs_iget_args { u64 ino; struct btrfs_root *root; }; static const struct inode_operations btrfs_dir_inode_operations; static const struct inode_operations btrfs_symlink_inode_operations; static const struct inode_operations btrfs_dir_ro_inode_operations; static const struct inode_operations btrfs_special_inode_operations; static const struct inode_operations btrfs_file_inode_operations; static const struct address_space_operations btrfs_aops; static const struct address_space_operations btrfs_symlink_aops; static const struct file_operations btrfs_dir_file_operations; static struct extent_io_ops btrfs_extent_io_ops; static struct kmem_cache *btrfs_inode_cachep; static struct kmem_cache *btrfs_delalloc_work_cachep; struct kmem_cache *btrfs_trans_handle_cachep; struct kmem_cache *btrfs_transaction_cachep; struct kmem_cache *btrfs_path_cachep; struct kmem_cache *btrfs_free_space_cachep; #define S_SHIFT 12 static unsigned char btrfs_type_by_mode[S_IFMT >> S_SHIFT] = { [S_IFREG >> S_SHIFT] = BTRFS_FT_REG_FILE, [S_IFDIR >> S_SHIFT] = BTRFS_FT_DIR, [S_IFCHR >> S_SHIFT] = BTRFS_FT_CHRDEV, [S_IFBLK >> S_SHIFT] = BTRFS_FT_BLKDEV, [S_IFIFO >> S_SHIFT] = BTRFS_FT_FIFO, [S_IFSOCK >> S_SHIFT] = BTRFS_FT_SOCK, [S_IFLNK >> S_SHIFT] = BTRFS_FT_SYMLINK, }; static int btrfs_setsize(struct inode *inode, loff_t newsize); static int btrfs_truncate(struct inode *inode); static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent); static noinline int cow_file_range(struct inode *inode, struct page *locked_page, u64 start, u64 end, int *page_started, unsigned long *nr_written, int unlock); static struct extent_map *create_pinned_em(struct inode *inode, u64 start, u64 len, u64 orig_start, u64 block_start, u64 block_len, u64 orig_block_len, int type); static int btrfs_init_inode_security(struct btrfs_trans_handle *trans, struct inode *inode, struct inode *dir, const struct qstr *qstr) { int err; err = btrfs_init_acl(trans, inode, dir); if (!err) err = btrfs_xattr_security_init(trans, inode, dir, qstr); return err; } /* * this does all the hard work for inserting an inline extent into * the btree. The caller should have done a btrfs_drop_extents so that * no overlapping inline items exist in the btree */ static noinline int insert_inline_extent(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *inode, u64 start, size_t size, size_t compressed_size, int compress_type, struct page **compressed_pages) { struct btrfs_key key; struct btrfs_path *path; struct extent_buffer *leaf; struct page *page = NULL; char *kaddr; unsigned long ptr; struct btrfs_file_extent_item *ei; int err = 0; int ret; size_t cur_size = size; size_t datasize; unsigned long offset; if (compressed_size && compressed_pages) cur_size = compressed_size; path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->leave_spinning = 1; key.objectid = btrfs_ino(inode); key.offset = start; btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY); datasize = btrfs_file_extent_calc_inline_size(cur_size); inode_add_bytes(inode, size); ret = btrfs_insert_empty_item(trans, root, path, &key, datasize); if (ret) { err = ret; goto fail; } leaf = path->nodes[0]; ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); btrfs_set_file_extent_generation(leaf, ei, trans->transid); btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE); btrfs_set_file_extent_encryption(leaf, ei, 0); btrfs_set_file_extent_other_encoding(leaf, ei, 0); btrfs_set_file_extent_ram_bytes(leaf, ei, size); ptr = btrfs_file_extent_inline_start(ei); if (compress_type != BTRFS_COMPRESS_NONE) { struct page *cpage; int i = 0; while (compressed_size > 0) { cpage = compressed_pages[i]; cur_size = min_t(unsigned long, compressed_size, PAGE_CACHE_SIZE); kaddr = kmap_atomic(cpage); write_extent_buffer(leaf, kaddr, ptr, cur_size); kunmap_atomic(kaddr); i++; ptr += cur_size; compressed_size -= cur_size; } btrfs_set_file_extent_compression(leaf, ei, compress_type); } else { page = find_get_page(inode->i_mapping, start >> PAGE_CACHE_SHIFT); btrfs_set_file_extent_compression(leaf, ei, 0); kaddr = kmap_atomic(page); offset = start & (PAGE_CACHE_SIZE - 1); write_extent_buffer(leaf, kaddr + offset, ptr, size); kunmap_atomic(kaddr); page_cache_release(page); } btrfs_mark_buffer_dirty(leaf); btrfs_free_path(path); /* * we're an inline extent, so nobody can * extend the file past i_size without locking * a page we already have locked. * * We must do any isize and inode updates * before we unlock the pages. Otherwise we * could end up racing with unlink. */ BTRFS_I(inode)->disk_i_size = inode->i_size; ret = btrfs_update_inode(trans, root, inode); return ret; fail: btrfs_free_path(path); return err; } /* * conditionally insert an inline extent into the file. This * does the checks required to make sure the data is small enough * to fit as an inline extent. */ static noinline int cow_file_range_inline(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *inode, u64 start, u64 end, size_t compressed_size, int compress_type, struct page **compressed_pages) { u64 isize = i_size_read(inode); u64 actual_end = min(end + 1, isize); u64 inline_len = actual_end - start; u64 aligned_end = (end + root->sectorsize - 1) & ~((u64)root->sectorsize - 1); u64 data_len = inline_len; int ret; if (compressed_size) data_len = compressed_size; if (start > 0 || actual_end >= PAGE_CACHE_SIZE || data_len >= BTRFS_MAX_INLINE_DATA_SIZE(root) || (!compressed_size && (actual_end & (root->sectorsize - 1)) == 0) || end + 1 < isize || data_len > root->fs_info->max_inline) { return 1; } ret = btrfs_drop_extents(trans, root, inode, start, aligned_end, 1); if (ret) return ret; if (isize > actual_end) inline_len = min_t(u64, isize, actual_end); ret = insert_inline_extent(trans, root, inode, start, inline_len, compressed_size, compress_type, compressed_pages); if (ret && ret != -ENOSPC) { btrfs_abort_transaction(trans, root, ret); return ret; } else if (ret == -ENOSPC) { return 1; } btrfs_delalloc_release_metadata(inode, end + 1 - start); btrfs_drop_extent_cache(inode, start, aligned_end - 1, 0); return 0; } struct async_extent { u64 start; u64 ram_size; u64 compressed_size; struct page **pages; unsigned long nr_pages; int compress_type; struct list_head list; }; struct async_cow { struct inode *inode; struct btrfs_root *root; struct page *locked_page; u64 start; u64 end; struct list_head extents; struct btrfs_work work; }; static noinline int add_async_extent(struct async_cow *cow, u64 start, u64 ram_size, u64 compressed_size, struct page **pages, unsigned long nr_pages, int compress_type) { struct async_extent *async_extent; async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS); BUG_ON(!async_extent); /* -ENOMEM */ async_extent->start = start; async_extent->ram_size = ram_size; async_extent->compressed_size = compressed_size; async_extent->pages = pages; async_extent->nr_pages = nr_pages; async_extent->compress_type = compress_type; list_add_tail(&async_extent->list, &cow->extents); return 0; } /* * we create compressed extents in two phases. The first * phase compresses a range of pages that have already been * locked (both pages and state bits are locked). * * This is done inside an ordered work queue, and the compression * is spread across many cpus. The actual IO submission is step * two, and the ordered work queue takes care of making sure that * happens in the same order things were put onto the queue by * writepages and friends. * * If this code finds it can't get good compression, it puts an * entry onto the work queue to write the uncompressed bytes. This * makes sure that both compressed inodes and uncompressed inodes * are written in the same order that the flusher thread sent them * down. */ static noinline int compress_file_range(struct inode *inode, struct page *locked_page, u64 start, u64 end, struct async_cow *async_cow, int *num_added) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; u64 num_bytes; u64 blocksize = root->sectorsize; u64 actual_end; u64 isize = i_size_read(inode); int ret = 0; struct page **pages = NULL; unsigned long nr_pages; unsigned long nr_pages_ret = 0; unsigned long total_compressed = 0; unsigned long total_in = 0; unsigned long max_compressed = 128 * 1024; unsigned long max_uncompressed = 128 * 1024; int i; int will_compress; int compress_type = root->fs_info->compress_type; /* if this is a small write inside eof, kick off a defrag */ if ((end - start + 1) < 16 * 1024 && (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size)) btrfs_add_inode_defrag(NULL, inode); actual_end = min_t(u64, isize, end + 1); again: will_compress = 0; nr_pages = (end >> PAGE_CACHE_SHIFT) - (start >> PAGE_CACHE_SHIFT) + 1; nr_pages = min(nr_pages, (128 * 1024UL) / PAGE_CACHE_SIZE); /* * we don't want to send crud past the end of i_size through * compression, that's just a waste of CPU time. So, if the * end of the file is before the start of our current * requested range of bytes, we bail out to the uncompressed * cleanup code that can deal with all of this. * * It isn't really the fastest way to fix things, but this is a * very uncommon corner. */ if (actual_end <= start) goto cleanup_and_bail_uncompressed; total_compressed = actual_end - start; /* we want to make sure that amount of ram required to uncompress * an extent is reasonable, so we limit the total size in ram * of a compressed extent to 128k. This is a crucial number * because it also controls how easily we can spread reads across * cpus for decompression. * * We also want to make sure the amount of IO required to do * a random read is reasonably small, so we limit the size of * a compressed extent to 128k. */ total_compressed = min(total_compressed, max_uncompressed); num_bytes = (end - start + blocksize) & ~(blocksize - 1); num_bytes = max(blocksize, num_bytes); total_in = 0; ret = 0; /* * we do compression for mount -o compress and when the * inode has not been flagged as nocompress. This flag can * change at any time if we discover bad compression ratios. */ if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) && (btrfs_test_opt(root, COMPRESS) || (BTRFS_I(inode)->force_compress) || (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS))) { WARN_ON(pages); pages = kzalloc(sizeof(struct page *) * nr_pages, GFP_NOFS); if (!pages) { /* just bail out to the uncompressed code */ goto cont; } if (BTRFS_I(inode)->force_compress) compress_type = BTRFS_I(inode)->force_compress; ret = btrfs_compress_pages(compress_type, inode->i_mapping, start, total_compressed, pages, nr_pages, &nr_pages_ret, &total_in, &total_compressed, max_compressed); if (!ret) { unsigned long offset = total_compressed & (PAGE_CACHE_SIZE - 1); struct page *page = pages[nr_pages_ret - 1]; char *kaddr; /* zero the tail end of the last page, we might be * sending it down to disk */ if (offset) { kaddr = kmap_atomic(page); memset(kaddr + offset, 0, PAGE_CACHE_SIZE - offset); kunmap_atomic(kaddr); } will_compress = 1; } } cont: if (start == 0) { trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { ret = PTR_ERR(trans); trans = NULL; goto cleanup_and_out; } trans->block_rsv = &root->fs_info->delalloc_block_rsv; /* lets try to make an inline extent */ if (ret || total_in < (actual_end - start)) { /* we didn't compress the entire range, try * to make an uncompressed inline extent. */ ret = cow_file_range_inline(trans, root, inode, start, end, 0, 0, NULL); } else { /* try making a compressed inline extent */ ret = cow_file_range_inline(trans, root, inode, start, end, total_compressed, compress_type, pages); } if (ret <= 0) { /* * inline extent creation worked or returned error, * we don't need to create any more async work items. * Unlock and free up our temp pages. */ extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, start, end, NULL, EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY | EXTENT_CLEAR_DELALLOC | EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK); btrfs_end_transaction(trans, root); goto free_pages_out; } btrfs_end_transaction(trans, root); } if (will_compress) { /* * we aren't doing an inline extent round the compressed size * up to a block size boundary so the allocator does sane * things */ total_compressed = (total_compressed + blocksize - 1) & ~(blocksize - 1); /* * one last check to make sure the compression is really a * win, compare the page count read with the blocks on disk */ total_in = (total_in + PAGE_CACHE_SIZE - 1) & ~(PAGE_CACHE_SIZE - 1); if (total_compressed >= total_in) { will_compress = 0; } else { num_bytes = total_in; } } if (!will_compress && pages) { /* * the compression code ran but failed to make things smaller, * free any pages it allocated and our page pointer array */ for (i = 0; i < nr_pages_ret; i++) { WARN_ON(pages[i]->mapping); page_cache_release(pages[i]); } kfree(pages); pages = NULL; total_compressed = 0; nr_pages_ret = 0; /* flag the file so we don't compress in the future */ if (!btrfs_test_opt(root, FORCE_COMPRESS) && !(BTRFS_I(inode)->force_compress)) { BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS; } } if (will_compress) { *num_added += 1; /* the async work queues will take care of doing actual * allocation on disk for these compressed pages, * and will submit them to the elevator. */ add_async_extent(async_cow, start, num_bytes, total_compressed, pages, nr_pages_ret, compress_type); if (start + num_bytes < end) { start += num_bytes; pages = NULL; cond_resched(); goto again; } } else { cleanup_and_bail_uncompressed: /* * No compression, but we still need to write the pages in * the file we've been given so far. redirty the locked * page if it corresponds to our extent and set things up * for the async work queue to run cow_file_range to do * the normal delalloc dance */ if (page_offset(locked_page) >= start && page_offset(locked_page) <= end) { __set_page_dirty_nobuffers(locked_page); /* unlocked later on in the async handlers */ } add_async_extent(async_cow, start, end - start + 1, 0, NULL, 0, BTRFS_COMPRESS_NONE); *num_added += 1; } out: return ret; free_pages_out: for (i = 0; i < nr_pages_ret; i++) { WARN_ON(pages[i]->mapping); page_cache_release(pages[i]); } kfree(pages); goto out; cleanup_and_out: extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, start, end, NULL, EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_DIRTY | EXTENT_CLEAR_DELALLOC | EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK); if (!trans || IS_ERR(trans)) btrfs_error(root->fs_info, ret, "Failed to join transaction"); else btrfs_abort_transaction(trans, root, ret); goto free_pages_out; } /* * phase two of compressed writeback. This is the ordered portion * of the code, which only gets called in the order the work was * queued. We walk all the async extents created by compress_file_range * and send them down to the disk. */ static noinline int submit_compressed_extents(struct inode *inode, struct async_cow *async_cow) { struct async_extent *async_extent; u64 alloc_hint = 0; struct btrfs_trans_handle *trans; struct btrfs_key ins; struct extent_map *em; struct btrfs_root *root = BTRFS_I(inode)->root; struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; struct extent_io_tree *io_tree; int ret = 0; if (list_empty(&async_cow->extents)) return 0; while (!list_empty(&async_cow->extents)) { async_extent = list_entry(async_cow->extents.next, struct async_extent, list); list_del(&async_extent->list); io_tree = &BTRFS_I(inode)->io_tree; retry: /* did the compression code fall back to uncompressed IO? */ if (!async_extent->pages) { int page_started = 0; unsigned long nr_written = 0; lock_extent(io_tree, async_extent->start, async_extent->start + async_extent->ram_size - 1); /* allocate blocks */ ret = cow_file_range(inode, async_cow->locked_page, async_extent->start, async_extent->start + async_extent->ram_size - 1, &page_started, &nr_written, 0); /* JDM XXX */ /* * if page_started, cow_file_range inserted an * inline extent and took care of all the unlocking * and IO for us. Otherwise, we need to submit * all those pages down to the drive. */ if (!page_started && !ret) extent_write_locked_range(io_tree, inode, async_extent->start, async_extent->start + async_extent->ram_size - 1, btrfs_get_extent, WB_SYNC_ALL); kfree(async_extent); cond_resched(); continue; } lock_extent(io_tree, async_extent->start, async_extent->start + async_extent->ram_size - 1); trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { ret = PTR_ERR(trans); } else { trans->block_rsv = &root->fs_info->delalloc_block_rsv; ret = btrfs_reserve_extent(trans, root, async_extent->compressed_size, async_extent->compressed_size, 0, alloc_hint, &ins, 1); if (ret && ret != -ENOSPC) btrfs_abort_transaction(trans, root, ret); btrfs_end_transaction(trans, root); } if (ret) { int i; for (i = 0; i < async_extent->nr_pages; i++) { WARN_ON(async_extent->pages[i]->mapping); page_cache_release(async_extent->pages[i]); } kfree(async_extent->pages); async_extent->nr_pages = 0; async_extent->pages = NULL; unlock_extent(io_tree, async_extent->start, async_extent->start + async_extent->ram_size - 1); if (ret == -ENOSPC) goto retry; goto out_free; /* JDM: Requeue? */ } /* * here we're doing allocation and writeback of the * compressed pages */ btrfs_drop_extent_cache(inode, async_extent->start, async_extent->start + async_extent->ram_size - 1, 0); em = alloc_extent_map(); BUG_ON(!em); /* -ENOMEM */ em->start = async_extent->start; em->len = async_extent->ram_size; em->orig_start = em->start; em->block_start = ins.objectid; em->block_len = ins.offset; em->orig_block_len = ins.offset; em->bdev = root->fs_info->fs_devices->latest_bdev; em->compress_type = async_extent->compress_type; set_bit(EXTENT_FLAG_PINNED, &em->flags); set_bit(EXTENT_FLAG_COMPRESSED, &em->flags); em->generation = -1; while (1) { write_lock(&em_tree->lock); ret = add_extent_mapping(em_tree, em); if (!ret) list_move(&em->list, &em_tree->modified_extents); write_unlock(&em_tree->lock); if (ret != -EEXIST) { free_extent_map(em); break; } btrfs_drop_extent_cache(inode, async_extent->start, async_extent->start + async_extent->ram_size - 1, 0); } ret = btrfs_add_ordered_extent_compress(inode, async_extent->start, ins.objectid, async_extent->ram_size, ins.offset, BTRFS_ORDERED_COMPRESSED, async_extent->compress_type); BUG_ON(ret); /* -ENOMEM */ /* * clear dirty, set writeback and unlock the pages. */ extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, async_extent->start, async_extent->start + async_extent->ram_size - 1, NULL, EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC | EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK); ret = btrfs_submit_compressed_write(inode, async_extent->start, async_extent->ram_size, ins.objectid, ins.offset, async_extent->pages, async_extent->nr_pages); BUG_ON(ret); /* -ENOMEM */ alloc_hint = ins.objectid + ins.offset; kfree(async_extent); cond_resched(); } ret = 0; out: return ret; out_free: kfree(async_extent); goto out; } static u64 get_extent_allocation_hint(struct inode *inode, u64 start, u64 num_bytes) { struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; struct extent_map *em; u64 alloc_hint = 0; read_lock(&em_tree->lock); em = search_extent_mapping(em_tree, start, num_bytes); if (em) { /* * if block start isn't an actual block number then find the * first block in this inode and use that as a hint. If that * block is also bogus then just don't worry about it. */ if (em->block_start >= EXTENT_MAP_LAST_BYTE) { free_extent_map(em); em = search_extent_mapping(em_tree, 0, 0); if (em && em->block_start < EXTENT_MAP_LAST_BYTE) alloc_hint = em->block_start; if (em) free_extent_map(em); } else { alloc_hint = em->block_start; free_extent_map(em); } } read_unlock(&em_tree->lock); return alloc_hint; } /* * when extent_io.c finds a delayed allocation range in the file, * the call backs end up in this code. The basic idea is to * allocate extents on disk for the range, and create ordered data structs * in ram to track those extents. * * locked_page is the page that writepage had locked already. We use * it to make sure we don't do extra locks or unlocks. * * *page_started is set to one if we unlock locked_page and do everything * required to start IO on it. It may be clean and already done with * IO when we return. */ static noinline int __cow_file_range(struct btrfs_trans_handle *trans, struct inode *inode, struct btrfs_root *root, struct page *locked_page, u64 start, u64 end, int *page_started, unsigned long *nr_written, int unlock) { u64 alloc_hint = 0; u64 num_bytes; unsigned long ram_size; u64 disk_num_bytes; u64 cur_alloc_size; u64 blocksize = root->sectorsize; struct btrfs_key ins; struct extent_map *em; struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; int ret = 0; BUG_ON(btrfs_is_free_space_inode(inode)); num_bytes = (end - start + blocksize) & ~(blocksize - 1); num_bytes = max(blocksize, num_bytes); disk_num_bytes = num_bytes; /* if this is a small write inside eof, kick off defrag */ if (num_bytes < 64 * 1024 && (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size)) btrfs_add_inode_defrag(trans, inode); if (start == 0) { /* lets try to make an inline extent */ ret = cow_file_range_inline(trans, root, inode, start, end, 0, 0, NULL); if (ret == 0) { extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, start, end, NULL, EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC | EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK); *nr_written = *nr_written + (end - start + PAGE_CACHE_SIZE) / PAGE_CACHE_SIZE; *page_started = 1; goto out; } else if (ret < 0) { btrfs_abort_transaction(trans, root, ret); goto out_unlock; } } BUG_ON(disk_num_bytes > btrfs_super_total_bytes(root->fs_info->super_copy)); alloc_hint = get_extent_allocation_hint(inode, start, num_bytes); btrfs_drop_extent_cache(inode, start, start + num_bytes - 1, 0); while (disk_num_bytes > 0) { unsigned long op; cur_alloc_size = disk_num_bytes; ret = btrfs_reserve_extent(trans, root, cur_alloc_size, root->sectorsize, 0, alloc_hint, &ins, 1); if (ret < 0) { btrfs_abort_transaction(trans, root, ret); goto out_unlock; } em = alloc_extent_map(); BUG_ON(!em); /* -ENOMEM */ em->start = start; em->orig_start = em->start; ram_size = ins.offset; em->len = ins.offset; em->block_start = ins.objectid; em->block_len = ins.offset; em->orig_block_len = ins.offset; em->bdev = root->fs_info->fs_devices->latest_bdev; set_bit(EXTENT_FLAG_PINNED, &em->flags); em->generation = -1; while (1) { write_lock(&em_tree->lock); ret = add_extent_mapping(em_tree, em); if (!ret) list_move(&em->list, &em_tree->modified_extents); write_unlock(&em_tree->lock); if (ret != -EEXIST) { free_extent_map(em); break; } btrfs_drop_extent_cache(inode, start, start + ram_size - 1, 0); } cur_alloc_size = ins.offset; ret = btrfs_add_ordered_extent(inode, start, ins.objectid, ram_size, cur_alloc_size, 0); BUG_ON(ret); /* -ENOMEM */ if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID) { ret = btrfs_reloc_clone_csums(inode, start, cur_alloc_size); if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_unlock; } } if (disk_num_bytes < cur_alloc_size) break; /* we're not doing compressed IO, don't unlock the first * page (which the caller expects to stay locked), don't * clear any dirty bits and don't set any writeback bits * * Do set the Private2 bit so we know this page was properly * setup for writepage */ op = unlock ? EXTENT_CLEAR_UNLOCK_PAGE : 0; op |= EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC | EXTENT_SET_PRIVATE2; extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, start, start + ram_size - 1, locked_page, op); disk_num_bytes -= cur_alloc_size; num_bytes -= cur_alloc_size; alloc_hint = ins.objectid + ins.offset; start += cur_alloc_size; } out: return ret; out_unlock: extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, start, end, locked_page, EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC | EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK); goto out; } static noinline int cow_file_range(struct inode *inode, struct page *locked_page, u64 start, u64 end, int *page_started, unsigned long *nr_written, int unlock) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(inode)->root; int ret; trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, start, end, locked_page, EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC | EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK); return PTR_ERR(trans); } trans->block_rsv = &root->fs_info->delalloc_block_rsv; ret = __cow_file_range(trans, inode, root, locked_page, start, end, page_started, nr_written, unlock); btrfs_end_transaction(trans, root); return ret; } /* * work queue call back to started compression on a file and pages */ static noinline void async_cow_start(struct btrfs_work *work) { struct async_cow *async_cow; int num_added = 0; async_cow = container_of(work, struct async_cow, work); compress_file_range(async_cow->inode, async_cow->locked_page, async_cow->start, async_cow->end, async_cow, &num_added); if (num_added == 0) { btrfs_add_delayed_iput(async_cow->inode); async_cow->inode = NULL; } } /* * work queue call back to submit previously compressed pages */ static noinline void async_cow_submit(struct btrfs_work *work) { struct async_cow *async_cow; struct btrfs_root *root; unsigned long nr_pages; async_cow = container_of(work, struct async_cow, work); root = async_cow->root; nr_pages = (async_cow->end - async_cow->start + PAGE_CACHE_SIZE) >> PAGE_CACHE_SHIFT; if (atomic_sub_return(nr_pages, &root->fs_info->async_delalloc_pages) < 5 * 1024 * 1024 && waitqueue_active(&root->fs_info->async_submit_wait)) wake_up(&root->fs_info->async_submit_wait); if (async_cow->inode) submit_compressed_extents(async_cow->inode, async_cow); } static noinline void async_cow_free(struct btrfs_work *work) { struct async_cow *async_cow; async_cow = container_of(work, struct async_cow, work); if (async_cow->inode) btrfs_add_delayed_iput(async_cow->inode); kfree(async_cow); } static int cow_file_range_async(struct inode *inode, struct page *locked_page, u64 start, u64 end, int *page_started, unsigned long *nr_written) { struct async_cow *async_cow; struct btrfs_root *root = BTRFS_I(inode)->root; unsigned long nr_pages; u64 cur_end; int limit = 10 * 1024 * 1024; clear_extent_bit(&BTRFS_I(inode)->io_tree, start, end, EXTENT_LOCKED, 1, 0, NULL, GFP_NOFS); while (start < end) { async_cow = kmalloc(sizeof(*async_cow), GFP_NOFS); BUG_ON(!async_cow); /* -ENOMEM */ async_cow->inode = igrab(inode); async_cow->root = root; async_cow->locked_page = locked_page; async_cow->start = start; if (BTRFS_I(inode)->flags & BTRFS_INODE_NOCOMPRESS) cur_end = end; else cur_end = min(end, start + 512 * 1024 - 1); async_cow->end = cur_end; INIT_LIST_HEAD(&async_cow->extents); async_cow->work.func = async_cow_start; async_cow->work.ordered_func = async_cow_submit; async_cow->work.ordered_free = async_cow_free; async_cow->work.flags = 0; nr_pages = (cur_end - start + PAGE_CACHE_SIZE) >> PAGE_CACHE_SHIFT; atomic_add(nr_pages, &root->fs_info->async_delalloc_pages); btrfs_queue_worker(&root->fs_info->delalloc_workers, &async_cow->work); if (atomic_read(&root->fs_info->async_delalloc_pages) > limit) { wait_event(root->fs_info->async_submit_wait, (atomic_read(&root->fs_info->async_delalloc_pages) < limit)); } while (atomic_read(&root->fs_info->async_submit_draining) && atomic_read(&root->fs_info->async_delalloc_pages)) { wait_event(root->fs_info->async_submit_wait, (atomic_read(&root->fs_info->async_delalloc_pages) == 0)); } *nr_written += nr_pages; start = cur_end + 1; } *page_started = 1; return 0; } static noinline int csum_exist_in_range(struct btrfs_root *root, u64 bytenr, u64 num_bytes) { int ret; struct btrfs_ordered_sum *sums; LIST_HEAD(list); ret = btrfs_lookup_csums_range(root->fs_info->csum_root, bytenr, bytenr + num_bytes - 1, &list, 0); if (ret == 0 && list_empty(&list)) return 0; while (!list_empty(&list)) { sums = list_entry(list.next, struct btrfs_ordered_sum, list); list_del(&sums->list); kfree(sums); } return 1; } /* * when nowcow writeback call back. This checks for snapshots or COW copies * of the extents that exist in the file, and COWs the file as required. * * If no cow copies or snapshots exist, we write directly to the existing * blocks on disk */ static noinline int run_delalloc_nocow(struct inode *inode, struct page *locked_page, u64 start, u64 end, int *page_started, int force, unsigned long *nr_written) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; struct extent_buffer *leaf; struct btrfs_path *path; struct btrfs_file_extent_item *fi; struct btrfs_key found_key; u64 cow_start; u64 cur_offset; u64 extent_end; u64 extent_offset; u64 disk_bytenr; u64 num_bytes; u64 disk_num_bytes; int extent_type; int ret, err; int type; int nocow; int check_prev = 1; bool nolock; u64 ino = btrfs_ino(inode); path = btrfs_alloc_path(); if (!path) { extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, start, end, locked_page, EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC | EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK); return -ENOMEM; } nolock = btrfs_is_free_space_inode(inode); if (nolock) trans = btrfs_join_transaction_nolock(root); else trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, start, end, locked_page, EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC | EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK); btrfs_free_path(path); return PTR_ERR(trans); } trans->block_rsv = &root->fs_info->delalloc_block_rsv; cow_start = (u64)-1; cur_offset = start; while (1) { ret = btrfs_lookup_file_extent(trans, root, path, ino, cur_offset, 0); if (ret < 0) { btrfs_abort_transaction(trans, root, ret); goto error; } if (ret > 0 && path->slots[0] > 0 && check_prev) { leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0] - 1); if (found_key.objectid == ino && found_key.type == BTRFS_EXTENT_DATA_KEY) path->slots[0]--; } check_prev = 0; next_slot: leaf = path->nodes[0]; if (path->slots[0] >= btrfs_header_nritems(leaf)) { ret = btrfs_next_leaf(root, path); if (ret < 0) { btrfs_abort_transaction(trans, root, ret); goto error; } if (ret > 0) break; leaf = path->nodes[0]; } nocow = 0; disk_bytenr = 0; num_bytes = 0; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); if (found_key.objectid > ino || found_key.type > BTRFS_EXTENT_DATA_KEY || found_key.offset > end) break; if (found_key.offset > cur_offset) { extent_end = found_key.offset; extent_type = 0; goto out_check; } fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); extent_type = btrfs_file_extent_type(leaf, fi); if (extent_type == BTRFS_FILE_EXTENT_REG || extent_type == BTRFS_FILE_EXTENT_PREALLOC) { disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi); extent_offset = btrfs_file_extent_offset(leaf, fi); extent_end = found_key.offset + btrfs_file_extent_num_bytes(leaf, fi); disk_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi); if (extent_end <= start) { path->slots[0]++; goto next_slot; } if (disk_bytenr == 0) goto out_check; if (btrfs_file_extent_compression(leaf, fi) || btrfs_file_extent_encryption(leaf, fi) || btrfs_file_extent_other_encoding(leaf, fi)) goto out_check; if (extent_type == BTRFS_FILE_EXTENT_REG && !force) goto out_check; if (btrfs_extent_readonly(root, disk_bytenr)) goto out_check; if (btrfs_cross_ref_exist(trans, root, ino, found_key.offset - extent_offset, disk_bytenr)) goto out_check; disk_bytenr += extent_offset; disk_bytenr += cur_offset - found_key.offset; num_bytes = min(end + 1, extent_end) - cur_offset; /* * force cow if csum exists in the range. * this ensure that csum for a given extent are * either valid or do not exist. */ if (csum_exist_in_range(root, disk_bytenr, num_bytes)) goto out_check; nocow = 1; } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { extent_end = found_key.offset + btrfs_file_extent_inline_len(leaf, fi); extent_end = ALIGN(extent_end, root->sectorsize); } else { BUG_ON(1); } out_check: if (extent_end <= start) { path->slots[0]++; goto next_slot; } if (!nocow) { if (cow_start == (u64)-1) cow_start = cur_offset; cur_offset = extent_end; if (cur_offset > end) break; path->slots[0]++; goto next_slot; } btrfs_release_path(path); if (cow_start != (u64)-1) { ret = __cow_file_range(trans, inode, root, locked_page, cow_start, found_key.offset - 1, page_started, nr_written, 1); if (ret) { btrfs_abort_transaction(trans, root, ret); goto error; } cow_start = (u64)-1; } if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) { struct extent_map *em; struct extent_map_tree *em_tree; em_tree = &BTRFS_I(inode)->extent_tree; em = alloc_extent_map(); BUG_ON(!em); /* -ENOMEM */ em->start = cur_offset; em->orig_start = found_key.offset - extent_offset; em->len = num_bytes; em->block_len = num_bytes; em->block_start = disk_bytenr; em->orig_block_len = disk_num_bytes; em->bdev = root->fs_info->fs_devices->latest_bdev; set_bit(EXTENT_FLAG_PINNED, &em->flags); set_bit(EXTENT_FLAG_FILLING, &em->flags); em->generation = -1; while (1) { write_lock(&em_tree->lock); ret = add_extent_mapping(em_tree, em); if (!ret) list_move(&em->list, &em_tree->modified_extents); write_unlock(&em_tree->lock); if (ret != -EEXIST) { free_extent_map(em); break; } btrfs_drop_extent_cache(inode, em->start, em->start + em->len - 1, 0); } type = BTRFS_ORDERED_PREALLOC; } else { type = BTRFS_ORDERED_NOCOW; } ret = btrfs_add_ordered_extent(inode, cur_offset, disk_bytenr, num_bytes, num_bytes, type); BUG_ON(ret); /* -ENOMEM */ if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID) { ret = btrfs_reloc_clone_csums(inode, cur_offset, num_bytes); if (ret) { btrfs_abort_transaction(trans, root, ret); goto error; } } extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, cur_offset, cur_offset + num_bytes - 1, locked_page, EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC | EXTENT_SET_PRIVATE2); cur_offset = extent_end; if (cur_offset > end) break; } btrfs_release_path(path); if (cur_offset <= end && cow_start == (u64)-1) { cow_start = cur_offset; cur_offset = end; } if (cow_start != (u64)-1) { ret = __cow_file_range(trans, inode, root, locked_page, cow_start, end, page_started, nr_written, 1); if (ret) { btrfs_abort_transaction(trans, root, ret); goto error; } } error: err = btrfs_end_transaction(trans, root); if (!ret) ret = err; if (ret && cur_offset < end) extent_clear_unlock_delalloc(inode, &BTRFS_I(inode)->io_tree, cur_offset, end, locked_page, EXTENT_CLEAR_UNLOCK_PAGE | EXTENT_CLEAR_UNLOCK | EXTENT_CLEAR_DELALLOC | EXTENT_CLEAR_DIRTY | EXTENT_SET_WRITEBACK | EXTENT_END_WRITEBACK); btrfs_free_path(path); return ret; } /* * extent_io.c call back to do delayed allocation processing */ static int run_delalloc_range(struct inode *inode, struct page *locked_page, u64 start, u64 end, int *page_started, unsigned long *nr_written) { int ret; struct btrfs_root *root = BTRFS_I(inode)->root; if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) { ret = run_delalloc_nocow(inode, locked_page, start, end, page_started, 1, nr_written); } else if (BTRFS_I(inode)->flags & BTRFS_INODE_PREALLOC) { ret = run_delalloc_nocow(inode, locked_page, start, end, page_started, 0, nr_written); } else if (!btrfs_test_opt(root, COMPRESS) && !(BTRFS_I(inode)->force_compress) && !(BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS)) { ret = cow_file_range(inode, locked_page, start, end, page_started, nr_written, 1); } else { set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &BTRFS_I(inode)->runtime_flags); ret = cow_file_range_async(inode, locked_page, start, end, page_started, nr_written); } return ret; } static void btrfs_split_extent_hook(struct inode *inode, struct extent_state *orig, u64 split) { /* not delalloc, ignore it */ if (!(orig->state & EXTENT_DELALLOC)) return; spin_lock(&BTRFS_I(inode)->lock); BTRFS_I(inode)->outstanding_extents++; spin_unlock(&BTRFS_I(inode)->lock); } /* * extent_io.c merge_extent_hook, used to track merged delayed allocation * extents so we can keep track of new extents that are just merged onto old * extents, such as when we are doing sequential writes, so we can properly * account for the metadata space we'll need. */ static void btrfs_merge_extent_hook(struct inode *inode, struct extent_state *new, struct extent_state *other) { /* not delalloc, ignore it */ if (!(other->state & EXTENT_DELALLOC)) return; spin_lock(&BTRFS_I(inode)->lock); BTRFS_I(inode)->outstanding_extents--; spin_unlock(&BTRFS_I(inode)->lock); } /* * extent_io.c set_bit_hook, used to track delayed allocation * bytes in this file, and to maintain the list of inodes that * have pending delalloc work to be done. */ static void btrfs_set_bit_hook(struct inode *inode, struct extent_state *state, int *bits) { /* * set_bit and clear bit hooks normally require _irqsave/restore * but in this case, we are only testing for the DELALLOC * bit, which is only set or cleared with irqs on */ if (!(state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) { struct btrfs_root *root = BTRFS_I(inode)->root; u64 len = state->end + 1 - state->start; bool do_list = !btrfs_is_free_space_inode(inode); if (*bits & EXTENT_FIRST_DELALLOC) { *bits &= ~EXTENT_FIRST_DELALLOC; } else { spin_lock(&BTRFS_I(inode)->lock); BTRFS_I(inode)->outstanding_extents++; spin_unlock(&BTRFS_I(inode)->lock); } spin_lock(&root->fs_info->delalloc_lock); BTRFS_I(inode)->delalloc_bytes += len; root->fs_info->delalloc_bytes += len; if (do_list && list_empty(&BTRFS_I(inode)->delalloc_inodes)) { list_add_tail(&BTRFS_I(inode)->delalloc_inodes, &root->fs_info->delalloc_inodes); } spin_unlock(&root->fs_info->delalloc_lock); } } /* * extent_io.c clear_bit_hook, see set_bit_hook for why */ static void btrfs_clear_bit_hook(struct inode *inode, struct extent_state *state, int *bits) { /* * set_bit and clear bit hooks normally require _irqsave/restore * but in this case, we are only testing for the DELALLOC * bit, which is only set or cleared with irqs on */ if ((state->state & EXTENT_DELALLOC) && (*bits & EXTENT_DELALLOC)) { struct btrfs_root *root = BTRFS_I(inode)->root; u64 len = state->end + 1 - state->start; bool do_list = !btrfs_is_free_space_inode(inode); if (*bits & EXTENT_FIRST_DELALLOC) { *bits &= ~EXTENT_FIRST_DELALLOC; } else if (!(*bits & EXTENT_DO_ACCOUNTING)) { spin_lock(&BTRFS_I(inode)->lock); BTRFS_I(inode)->outstanding_extents--; spin_unlock(&BTRFS_I(inode)->lock); } if (*bits & EXTENT_DO_ACCOUNTING) btrfs_delalloc_release_metadata(inode, len); if (root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID && do_list) btrfs_free_reserved_data_space(inode, len); spin_lock(&root->fs_info->delalloc_lock); root->fs_info->delalloc_bytes -= len; BTRFS_I(inode)->delalloc_bytes -= len; if (do_list && BTRFS_I(inode)->delalloc_bytes == 0 && !list_empty(&BTRFS_I(inode)->delalloc_inodes)) { list_del_init(&BTRFS_I(inode)->delalloc_inodes); } spin_unlock(&root->fs_info->delalloc_lock); } } /* * extent_io.c merge_bio_hook, this must check the chunk tree to make sure * we don't create bios that span stripes or chunks */ int btrfs_merge_bio_hook(struct page *page, unsigned long offset, size_t size, struct bio *bio, unsigned long bio_flags) { struct btrfs_root *root = BTRFS_I(page->mapping->host)->root; u64 logical = (u64)bio->bi_sector << 9; u64 length = 0; u64 map_length; int ret; if (bio_flags & EXTENT_BIO_COMPRESSED) return 0; length = bio->bi_size; map_length = length; ret = btrfs_map_block(root->fs_info, READ, logical, &map_length, NULL, 0); /* Will always return 0 with map_multi == NULL */ BUG_ON(ret < 0); if (map_length < length + size) return 1; return 0; } /* * in order to insert checksums into the metadata in large chunks, * we wait until bio submission time. All the pages in the bio are * checksummed and sums are attached onto the ordered extent record. * * At IO completion time the cums attached on the ordered extent record * are inserted into the btree */ static int __btrfs_submit_bio_start(struct inode *inode, int rw, struct bio *bio, int mirror_num, unsigned long bio_flags, u64 bio_offset) { struct btrfs_root *root = BTRFS_I(inode)->root; int ret = 0; ret = btrfs_csum_one_bio(root, inode, bio, 0, 0); BUG_ON(ret); /* -ENOMEM */ return 0; } /* * in order to insert checksums into the metadata in large chunks, * we wait until bio submission time. All the pages in the bio are * checksummed and sums are attached onto the ordered extent record. * * At IO completion time the cums attached on the ordered extent record * are inserted into the btree */ static int __btrfs_submit_bio_done(struct inode *inode, int rw, struct bio *bio, int mirror_num, unsigned long bio_flags, u64 bio_offset) { struct btrfs_root *root = BTRFS_I(inode)->root; int ret; ret = btrfs_map_bio(root, rw, bio, mirror_num, 1); if (ret) bio_endio(bio, ret); return ret; } /* * extent_io.c submission hook. This does the right thing for csum calculation * on write, or reading the csums from the tree before a read */ static int btrfs_submit_bio_hook(struct inode *inode, int rw, struct bio *bio, int mirror_num, unsigned long bio_flags, u64 bio_offset) { struct btrfs_root *root = BTRFS_I(inode)->root; int ret = 0; int skip_sum; int metadata = 0; int async = !atomic_read(&BTRFS_I(inode)->sync_writers); skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM; if (btrfs_is_free_space_inode(inode)) metadata = 2; if (!(rw & REQ_WRITE)) { ret = btrfs_bio_wq_end_io(root->fs_info, bio, metadata); if (ret) goto out; if (bio_flags & EXTENT_BIO_COMPRESSED) { ret = btrfs_submit_compressed_read(inode, bio, mirror_num, bio_flags); goto out; } else if (!skip_sum) { ret = btrfs_lookup_bio_sums(root, inode, bio, NULL); if (ret) goto out; } goto mapit; } else if (async && !skip_sum) { /* csum items have already been cloned */ if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID) goto mapit; /* we're doing a write, do the async checksumming */ ret = btrfs_wq_submit_bio(BTRFS_I(inode)->root->fs_info, inode, rw, bio, mirror_num, bio_flags, bio_offset, __btrfs_submit_bio_start, __btrfs_submit_bio_done); goto out; } else if (!skip_sum) { ret = btrfs_csum_one_bio(root, inode, bio, 0, 0); if (ret) goto out; } mapit: ret = btrfs_map_bio(root, rw, bio, mirror_num, 0); out: if (ret < 0) bio_endio(bio, ret); return ret; } /* * given a list of ordered sums record them in the inode. This happens * at IO completion time based on sums calculated at bio submission time. */ static noinline int add_pending_csums(struct btrfs_trans_handle *trans, struct inode *inode, u64 file_offset, struct list_head *list) { struct btrfs_ordered_sum *sum; list_for_each_entry(sum, list, list) { btrfs_csum_file_blocks(trans, BTRFS_I(inode)->root->fs_info->csum_root, sum); } return 0; } int btrfs_set_extent_delalloc(struct inode *inode, u64 start, u64 end, struct extent_state **cached_state) { WARN_ON((end & (PAGE_CACHE_SIZE - 1)) == 0); return set_extent_delalloc(&BTRFS_I(inode)->io_tree, start, end, cached_state, GFP_NOFS); } /* see btrfs_writepage_start_hook for details on why this is required */ struct btrfs_writepage_fixup { struct page *page; struct btrfs_work work; }; static void btrfs_writepage_fixup_worker(struct btrfs_work *work) { struct btrfs_writepage_fixup *fixup; struct btrfs_ordered_extent *ordered; struct extent_state *cached_state = NULL; struct page *page; struct inode *inode; u64 page_start; u64 page_end; int ret; fixup = container_of(work, struct btrfs_writepage_fixup, work); page = fixup->page; again: lock_page(page); if (!page->mapping || !PageDirty(page) || !PageChecked(page)) { ClearPageChecked(page); goto out_page; } inode = page->mapping->host; page_start = page_offset(page); page_end = page_offset(page) + PAGE_CACHE_SIZE - 1; lock_extent_bits(&BTRFS_I(inode)->io_tree, page_start, page_end, 0, &cached_state); /* already ordered? We're done */ if (PagePrivate2(page)) goto out; ordered = btrfs_lookup_ordered_extent(inode, page_start); if (ordered) { unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end, &cached_state, GFP_NOFS); unlock_page(page); btrfs_start_ordered_extent(inode, ordered, 1); btrfs_put_ordered_extent(ordered); goto again; } ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE); if (ret) { mapping_set_error(page->mapping, ret); end_extent_writepage(page, ret, page_start, page_end); ClearPageChecked(page); goto out; } btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state); ClearPageChecked(page); set_page_dirty(page); out: unlock_extent_cached(&BTRFS_I(inode)->io_tree, page_start, page_end, &cached_state, GFP_NOFS); out_page: unlock_page(page); page_cache_release(page); kfree(fixup); } /* * There are a few paths in the higher layers of the kernel that directly * set the page dirty bit without asking the filesystem if it is a * good idea. This causes problems because we want to make sure COW * properly happens and the data=ordered rules are followed. * * In our case any range that doesn't have the ORDERED bit set * hasn't been properly setup for IO. We kick off an async process * to fix it up. The async helper will wait for ordered extents, set * the delalloc bit and make it safe to write the page. */ static int btrfs_writepage_start_hook(struct page *page, u64 start, u64 end) { struct inode *inode = page->mapping->host; struct btrfs_writepage_fixup *fixup; struct btrfs_root *root = BTRFS_I(inode)->root; /* this page is properly in the ordered list */ if (TestClearPagePrivate2(page)) return 0; if (PageChecked(page)) return -EAGAIN; fixup = kzalloc(sizeof(*fixup), GFP_NOFS); if (!fixup) return -EAGAIN; SetPageChecked(page); page_cache_get(page); fixup->work.func = btrfs_writepage_fixup_worker; fixup->page = page; btrfs_queue_worker(&root->fs_info->fixup_workers, &fixup->work); return -EBUSY; } static int insert_reserved_file_extent(struct btrfs_trans_handle *trans, struct inode *inode, u64 file_pos, u64 disk_bytenr, u64 disk_num_bytes, u64 num_bytes, u64 ram_bytes, u8 compression, u8 encryption, u16 other_encoding, int extent_type) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_file_extent_item *fi; struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_key ins; int ret; path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->leave_spinning = 1; /* * we may be replacing one extent in the tree with another. * The new extent is pinned in the extent map, and we don't want * to drop it from the cache until it is completely in the btree. * * So, tell btrfs_drop_extents to leave this extent in the cache. * the caller is expected to unpin it and allow it to be merged * with the others. */ ret = btrfs_drop_extents(trans, root, inode, file_pos, file_pos + num_bytes, 0); if (ret) goto out; ins.objectid = btrfs_ino(inode); ins.offset = file_pos; ins.type = BTRFS_EXTENT_DATA_KEY; ret = btrfs_insert_empty_item(trans, root, path, &ins, sizeof(*fi)); if (ret) goto out; leaf = path->nodes[0]; fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); btrfs_set_file_extent_generation(leaf, fi, trans->transid); btrfs_set_file_extent_type(leaf, fi, extent_type); btrfs_set_file_extent_disk_bytenr(leaf, fi, disk_bytenr); btrfs_set_file_extent_disk_num_bytes(leaf, fi, disk_num_bytes); btrfs_set_file_extent_offset(leaf, fi, 0); btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes); btrfs_set_file_extent_ram_bytes(leaf, fi, ram_bytes); btrfs_set_file_extent_compression(leaf, fi, compression); btrfs_set_file_extent_encryption(leaf, fi, encryption); btrfs_set_file_extent_other_encoding(leaf, fi, other_encoding); btrfs_mark_buffer_dirty(leaf); btrfs_release_path(path); inode_add_bytes(inode, num_bytes); ins.objectid = disk_bytenr; ins.offset = disk_num_bytes; ins.type = BTRFS_EXTENT_ITEM_KEY; ret = btrfs_alloc_reserved_file_extent(trans, root, root->root_key.objectid, btrfs_ino(inode), file_pos, &ins); out: btrfs_free_path(path); return ret; } /* * helper function for btrfs_finish_ordered_io, this * just reads in some of the csum leaves to prime them into ram * before we start the transaction. It limits the amount of btree * reads required while inside the transaction. */ /* as ordered data IO finishes, this gets called so we can finish * an ordered extent if the range of bytes in the file it covers are * fully written. */ static int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent) { struct inode *inode = ordered_extent->inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans = NULL; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct extent_state *cached_state = NULL; int compress_type = 0; int ret; bool nolock; nolock = btrfs_is_free_space_inode(inode); if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) { ret = -EIO; goto out; } if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) { BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */ btrfs_ordered_update_i_size(inode, 0, ordered_extent); if (nolock) trans = btrfs_join_transaction_nolock(root); else trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { ret = PTR_ERR(trans); trans = NULL; goto out; } trans->block_rsv = &root->fs_info->delalloc_block_rsv; ret = btrfs_update_inode_fallback(trans, root, inode); if (ret) /* -ENOMEM or corruption */ btrfs_abort_transaction(trans, root, ret); goto out; } lock_extent_bits(io_tree, ordered_extent->file_offset, ordered_extent->file_offset + ordered_extent->len - 1, 0, &cached_state); if (nolock) trans = btrfs_join_transaction_nolock(root); else trans = btrfs_join_transaction(root); if (IS_ERR(trans)) { ret = PTR_ERR(trans); trans = NULL; goto out_unlock; } trans->block_rsv = &root->fs_info->delalloc_block_rsv; if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags)) compress_type = ordered_extent->compress_type; if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) { BUG_ON(compress_type); ret = btrfs_mark_extent_written(trans, inode, ordered_extent->file_offset, ordered_extent->file_offset + ordered_extent->len); } else { BUG_ON(root == root->fs_info->tree_root); ret = insert_reserved_file_extent(trans, inode, ordered_extent->file_offset, ordered_extent->start, ordered_extent->disk_len, ordered_extent->len, ordered_extent->len, compress_type, 0, 0, BTRFS_FILE_EXTENT_REG); } unpin_extent_cache(&BTRFS_I(inode)->extent_tree, ordered_extent->file_offset, ordered_extent->len, trans->transid); if (ret < 0) { btrfs_abort_transaction(trans, root, ret); goto out_unlock; } add_pending_csums(trans, inode, ordered_extent->file_offset, &ordered_extent->list); btrfs_ordered_update_i_size(inode, 0, ordered_extent); ret = btrfs_update_inode_fallback(trans, root, inode); if (ret) { /* -ENOMEM or corruption */ btrfs_abort_transaction(trans, root, ret); goto out_unlock; } ret = 0; out_unlock: unlock_extent_cached(io_tree, ordered_extent->file_offset, ordered_extent->file_offset + ordered_extent->len - 1, &cached_state, GFP_NOFS); out: if (root != root->fs_info->tree_root) btrfs_delalloc_release_metadata(inode, ordered_extent->len); if (trans) btrfs_end_transaction(trans, root); if (ret) clear_extent_uptodate(io_tree, ordered_extent->file_offset, ordered_extent->file_offset + ordered_extent->len - 1, NULL, GFP_NOFS); /* * This needs to be done to make sure anybody waiting knows we are done * updating everything for this ordered extent. */ btrfs_remove_ordered_extent(inode, ordered_extent); /* once for us */ btrfs_put_ordered_extent(ordered_extent); /* once for the tree */ btrfs_put_ordered_extent(ordered_extent); return ret; } static void finish_ordered_fn(struct btrfs_work *work) { struct btrfs_ordered_extent *ordered_extent; ordered_extent = container_of(work, struct btrfs_ordered_extent, work); btrfs_finish_ordered_io(ordered_extent); } static int btrfs_writepage_end_io_hook(struct page *page, u64 start, u64 end, struct extent_state *state, int uptodate) { struct inode *inode = page->mapping->host; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_ordered_extent *ordered_extent = NULL; struct btrfs_workers *workers; trace_btrfs_writepage_end_io_hook(page, start, end, uptodate); ClearPagePrivate2(page); if (!btrfs_dec_test_ordered_pending(inode, &ordered_extent, start, end - start + 1, uptodate)) return 0; ordered_extent->work.func = finish_ordered_fn; ordered_extent->work.flags = 0; if (btrfs_is_free_space_inode(inode)) workers = &root->fs_info->endio_freespace_worker; else workers = &root->fs_info->endio_write_workers; btrfs_queue_worker(workers, &ordered_extent->work); return 0; } /* * when reads are done, we need to check csums to verify the data is correct * if there's a match, we allow the bio to finish. If not, the code in * extent_io.c will try to find good copies for us. */ static int btrfs_readpage_end_io_hook(struct page *page, u64 start, u64 end, struct extent_state *state, int mirror) { size_t offset = start - ((u64)page->index << PAGE_CACHE_SHIFT); struct inode *inode = page->mapping->host; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; char *kaddr; u64 private = ~(u32)0; int ret; struct btrfs_root *root = BTRFS_I(inode)->root; u32 csum = ~(u32)0; if (PageChecked(page)) { ClearPageChecked(page); goto good; } if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM) goto good; if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID && test_range_bit(io_tree, start, end, EXTENT_NODATASUM, 1, NULL)) { clear_extent_bits(io_tree, start, end, EXTENT_NODATASUM, GFP_NOFS); return 0; } if (state && state->start == start) { private = state->private; ret = 0; } else { ret = get_state_private(io_tree, start, &private); } kaddr = kmap_atomic(page); if (ret) goto zeroit; csum = btrfs_csum_data(root, kaddr + offset, csum, end - start + 1); btrfs_csum_final(csum, (char *)&csum); if (csum != private) goto zeroit; kunmap_atomic(kaddr); good: return 0; zeroit: printk_ratelimited(KERN_INFO "btrfs csum failed ino %llu off %llu csum %u " "private %llu\n", (unsigned long long)btrfs_ino(page->mapping->host), (unsigned long long)start, csum, (unsigned long long)private); memset(kaddr + offset, 1, end - start + 1); flush_dcache_page(page); kunmap_atomic(kaddr); if (private == 0) return 0; return -EIO; } struct delayed_iput { struct list_head list; struct inode *inode; }; /* JDM: If this is fs-wide, why can't we add a pointer to * btrfs_inode instead and avoid the allocation? */ void btrfs_add_delayed_iput(struct inode *inode) { struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info; struct delayed_iput *delayed; if (atomic_add_unless(&inode->i_count, -1, 1)) return; delayed = kmalloc(sizeof(*delayed), GFP_NOFS | __GFP_NOFAIL); delayed->inode = inode; spin_lock(&fs_info->delayed_iput_lock); list_add_tail(&delayed->list, &fs_info->delayed_iputs); spin_unlock(&fs_info->delayed_iput_lock); } void btrfs_run_delayed_iputs(struct btrfs_root *root) { LIST_HEAD(list); struct btrfs_fs_info *fs_info = root->fs_info; struct delayed_iput *delayed; int empty; spin_lock(&fs_info->delayed_iput_lock); empty = list_empty(&fs_info->delayed_iputs); spin_unlock(&fs_info->delayed_iput_lock); if (empty) return; spin_lock(&fs_info->delayed_iput_lock); list_splice_init(&fs_info->delayed_iputs, &list); spin_unlock(&fs_info->delayed_iput_lock); while (!list_empty(&list)) { delayed = list_entry(list.next, struct delayed_iput, list); list_del(&delayed->list); iput(delayed->inode); kfree(delayed); } } enum btrfs_orphan_cleanup_state { ORPHAN_CLEANUP_STARTED = 1, ORPHAN_CLEANUP_DONE = 2, }; /* * This is called in transaction commit time. If there are no orphan * files in the subvolume, it removes orphan item and frees block_rsv * structure. */ void btrfs_orphan_commit_root(struct btrfs_trans_handle *trans, struct btrfs_root *root) { struct btrfs_block_rsv *block_rsv; int ret; if (atomic_read(&root->orphan_inodes) || root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) return; spin_lock(&root->orphan_lock); if (atomic_read(&root->orphan_inodes)) { spin_unlock(&root->orphan_lock); return; } if (root->orphan_cleanup_state != ORPHAN_CLEANUP_DONE) { spin_unlock(&root->orphan_lock); return; } block_rsv = root->orphan_block_rsv; root->orphan_block_rsv = NULL; spin_unlock(&root->orphan_lock); if (root->orphan_item_inserted && btrfs_root_refs(&root->root_item) > 0) { ret = btrfs_del_orphan_item(trans, root->fs_info->tree_root, root->root_key.objectid); BUG_ON(ret); root->orphan_item_inserted = 0; } if (block_rsv) { WARN_ON(block_rsv->size > 0); btrfs_free_block_rsv(root, block_rsv); } } /* * This creates an orphan entry for the given inode in case something goes * wrong in the middle of an unlink/truncate. * * NOTE: caller of this function should reserve 5 units of metadata for * this function. */ int btrfs_orphan_add(struct btrfs_trans_handle *trans, struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_block_rsv *block_rsv = NULL; int reserve = 0; int insert = 0; int ret; if (!root->orphan_block_rsv) { block_rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP); if (!block_rsv) return -ENOMEM; } spin_lock(&root->orphan_lock); if (!root->orphan_block_rsv) { root->orphan_block_rsv = block_rsv; } else if (block_rsv) { btrfs_free_block_rsv(root, block_rsv); block_rsv = NULL; } if (!test_and_set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM, &BTRFS_I(inode)->runtime_flags)) { #if 0 /* * For proper ENOSPC handling, we should do orphan * cleanup when mounting. But this introduces backward * compatibility issue. */ if (!xchg(&root->orphan_item_inserted, 1)) insert = 2; else insert = 1; #endif insert = 1; atomic_inc(&root->orphan_inodes); } if (!test_and_set_bit(BTRFS_INODE_ORPHAN_META_RESERVED, &BTRFS_I(inode)->runtime_flags)) reserve = 1; spin_unlock(&root->orphan_lock); /* grab metadata reservation from transaction handle */ if (reserve) { ret = btrfs_orphan_reserve_metadata(trans, inode); BUG_ON(ret); /* -ENOSPC in reservation; Logic error? JDM */ } /* insert an orphan item to track this unlinked/truncated file */ if (insert >= 1) { ret = btrfs_insert_orphan_item(trans, root, btrfs_ino(inode)); if (ret && ret != -EEXIST) { clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM, &BTRFS_I(inode)->runtime_flags); btrfs_abort_transaction(trans, root, ret); return ret; } ret = 0; } /* insert an orphan item to track subvolume contains orphan files */ if (insert >= 2) { ret = btrfs_insert_orphan_item(trans, root->fs_info->tree_root, root->root_key.objectid); if (ret && ret != -EEXIST) { btrfs_abort_transaction(trans, root, ret); return ret; } } return 0; } /* * We have done the truncate/delete so we can go ahead and remove the orphan * item for this particular inode. */ int btrfs_orphan_del(struct btrfs_trans_handle *trans, struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; int delete_item = 0; int release_rsv = 0; int ret = 0; spin_lock(&root->orphan_lock); if (test_and_clear_bit(BTRFS_INODE_HAS_ORPHAN_ITEM, &BTRFS_I(inode)->runtime_flags)) delete_item = 1; if (test_and_clear_bit(BTRFS_INODE_ORPHAN_META_RESERVED, &BTRFS_I(inode)->runtime_flags)) release_rsv = 1; spin_unlock(&root->orphan_lock); if (trans && delete_item) { ret = btrfs_del_orphan_item(trans, root, btrfs_ino(inode)); BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */ } if (release_rsv) { btrfs_orphan_release_metadata(inode); atomic_dec(&root->orphan_inodes); } return 0; } /* * this cleans up any orphans that may be left on the list from the last use * of this root. */ int btrfs_orphan_cleanup(struct btrfs_root *root) { struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_key key, found_key; struct btrfs_trans_handle *trans; struct inode *inode; u64 last_objectid = 0; int ret = 0, nr_unlink = 0, nr_truncate = 0; if (cmpxchg(&root->orphan_cleanup_state, 0, ORPHAN_CLEANUP_STARTED)) return 0; path = btrfs_alloc_path(); if (!path) { ret = -ENOMEM; goto out; } path->reada = -1; key.objectid = BTRFS_ORPHAN_OBJECTID; btrfs_set_key_type(&key, BTRFS_ORPHAN_ITEM_KEY); key.offset = (u64)-1; while (1) { ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) goto out; /* * if ret == 0 means we found what we were searching for, which * is weird, but possible, so only screw with path if we didn't * find the key and see if we have stuff that matches */ if (ret > 0) { ret = 0; if (path->slots[0] == 0) break; path->slots[0]--; } /* pull out the item */ leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); /* make sure the item matches what we want */ if (found_key.objectid != BTRFS_ORPHAN_OBJECTID) break; if (btrfs_key_type(&found_key) != BTRFS_ORPHAN_ITEM_KEY) break; /* release the path since we're done with it */ btrfs_release_path(path); /* * this is where we are basically btrfs_lookup, without the * crossing root thing. we store the inode number in the * offset of the orphan item. */ if (found_key.offset == last_objectid) { printk(KERN_ERR "btrfs: Error removing orphan entry, " "stopping orphan cleanup\n"); ret = -EINVAL; goto out; } last_objectid = found_key.offset; found_key.objectid = found_key.offset; found_key.type = BTRFS_INODE_ITEM_KEY; found_key.offset = 0; inode = btrfs_iget(root->fs_info->sb, &found_key, root, NULL); ret = PTR_RET(inode); if (ret && ret != -ESTALE) goto out; if (ret == -ESTALE && root == root->fs_info->tree_root) { struct btrfs_root *dead_root; struct btrfs_fs_info *fs_info = root->fs_info; int is_dead_root = 0; /* * this is an orphan in the tree root. Currently these * could come from 2 sources: * a) a snapshot deletion in progress * b) a free space cache inode * We need to distinguish those two, as the snapshot * orphan must not get deleted. * find_dead_roots already ran before us, so if this * is a snapshot deletion, we should find the root * in the dead_roots list */ spin_lock(&fs_info->trans_lock); list_for_each_entry(dead_root, &fs_info->dead_roots, root_list) { if (dead_root->root_key.objectid == found_key.objectid) { is_dead_root = 1; break; } } spin_unlock(&fs_info->trans_lock); if (is_dead_root) { /* prevent this orphan from being found again */ key.offset = found_key.objectid - 1; continue; } } /* * Inode is already gone but the orphan item is still there, * kill the orphan item. */ if (ret == -ESTALE) { trans = btrfs_start_transaction(root, 1); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out; } printk(KERN_ERR "auto deleting %Lu\n", found_key.objectid); ret = btrfs_del_orphan_item(trans, root, found_key.objectid); BUG_ON(ret); /* -ENOMEM or corruption (JDM: Recheck) */ btrfs_end_transaction(trans, root); continue; } /* * add this inode to the orphan list so btrfs_orphan_del does * the proper thing when we hit it */ set_bit(BTRFS_INODE_HAS_ORPHAN_ITEM, &BTRFS_I(inode)->runtime_flags); /* if we have links, this was a truncate, lets do that */ if (inode->i_nlink) { if (!S_ISREG(inode->i_mode)) { WARN_ON(1); iput(inode); continue; } nr_truncate++; ret = btrfs_truncate(inode); } else { nr_unlink++; } /* this will do delete_inode and everything for us */ iput(inode); if (ret) goto out; } /* release the path since we're done with it */ btrfs_release_path(path); root->orphan_cleanup_state = ORPHAN_CLEANUP_DONE; if (root->orphan_block_rsv) btrfs_block_rsv_release(root, root->orphan_block_rsv, (u64)-1); if (root->orphan_block_rsv || root->orphan_item_inserted) { trans = btrfs_join_transaction(root); if (!IS_ERR(trans)) btrfs_end_transaction(trans, root); } if (nr_unlink) printk(KERN_INFO "btrfs: unlinked %d orphans\n", nr_unlink); if (nr_truncate) printk(KERN_INFO "btrfs: truncated %d orphans\n", nr_truncate); out: if (ret) printk(KERN_CRIT "btrfs: could not do orphan cleanup %d\n", ret); btrfs_free_path(path); return ret; } /* * very simple check to peek ahead in the leaf looking for xattrs. If we * don't find any xattrs, we know there can't be any acls. * * slot is the slot the inode is in, objectid is the objectid of the inode */ static noinline int acls_after_inode_item(struct extent_buffer *leaf, int slot, u64 objectid) { u32 nritems = btrfs_header_nritems(leaf); struct btrfs_key found_key; int scanned = 0; slot++; while (slot < nritems) { btrfs_item_key_to_cpu(leaf, &found_key, slot); /* we found a different objectid, there must not be acls */ if (found_key.objectid != objectid) return 0; /* we found an xattr, assume we've got an acl */ if (found_key.type == BTRFS_XATTR_ITEM_KEY) return 1; /* * we found a key greater than an xattr key, there can't * be any acls later on */ if (found_key.type > BTRFS_XATTR_ITEM_KEY) return 0; slot++; scanned++; /* * it goes inode, inode backrefs, xattrs, extents, * so if there are a ton of hard links to an inode there can * be a lot of backrefs. Don't waste time searching too hard, * this is just an optimization */ if (scanned >= 8) break; } /* we hit the end of the leaf before we found an xattr or * something larger than an xattr. We have to assume the inode * has acls */ return 1; } /* * read an inode from the btree into the in-memory inode */ static void btrfs_read_locked_inode(struct inode *inode) { struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_inode_item *inode_item; struct btrfs_timespec *tspec; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_key location; int maybe_acls; u32 rdev; int ret; bool filled = false; ret = btrfs_fill_inode(inode, &rdev); if (!ret) filled = true; path = btrfs_alloc_path(); if (!path) goto make_bad; path->leave_spinning = 1; memcpy(&location, &BTRFS_I(inode)->location, sizeof(location)); ret = btrfs_lookup_inode(NULL, root, path, &location, 0); if (ret) goto make_bad; leaf = path->nodes[0]; if (filled) goto cache_acl; inode_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_inode_item); inode->i_mode = btrfs_inode_mode(leaf, inode_item); set_nlink(inode, btrfs_inode_nlink(leaf, inode_item)); i_uid_write(inode, btrfs_inode_uid(leaf, inode_item)); i_gid_write(inode, btrfs_inode_gid(leaf, inode_item)); btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item)); tspec = btrfs_inode_atime(inode_item); inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, tspec); inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, tspec); tspec = btrfs_inode_mtime(inode_item); inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, tspec); inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, tspec); tspec = btrfs_inode_ctime(inode_item); inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, tspec); inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, tspec); inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item)); BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item); BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item); /* * If we were modified in the current generation and evicted from memory * and then re-read we need to do a full sync since we don't have any * idea about which extents were modified before we were evicted from * cache. */ if (BTRFS_I(inode)->last_trans == root->fs_info->generation) set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags); inode->i_version = btrfs_inode_sequence(leaf, inode_item); inode->i_generation = BTRFS_I(inode)->generation; inode->i_rdev = 0; rdev = btrfs_inode_rdev(leaf, inode_item); BTRFS_I(inode)->index_cnt = (u64)-1; BTRFS_I(inode)->flags = btrfs_inode_flags(leaf, inode_item); cache_acl: /* * try to precache a NULL acl entry for files that don't have * any xattrs or acls */ maybe_acls = acls_after_inode_item(leaf, path->slots[0], btrfs_ino(inode)); if (!maybe_acls) cache_no_acl(inode); btrfs_free_path(path); switch (inode->i_mode & S_IFMT) { case S_IFREG: inode->i_mapping->a_ops = &btrfs_aops; inode->i_mapping->backing_dev_info = &root->fs_info->bdi; BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops; inode->i_fop = &btrfs_file_operations; inode->i_op = &btrfs_file_inode_operations; break; case S_IFDIR: inode->i_fop = &btrfs_dir_file_operations; if (root == root->fs_info->tree_root) inode->i_op = &btrfs_dir_ro_inode_operations; else inode->i_op = &btrfs_dir_inode_operations; break; case S_IFLNK: inode->i_op = &btrfs_symlink_inode_operations; inode->i_mapping->a_ops = &btrfs_symlink_aops; inode->i_mapping->backing_dev_info = &root->fs_info->bdi; break; default: inode->i_op = &btrfs_special_inode_operations; init_special_inode(inode, inode->i_mode, rdev); break; } btrfs_update_iflags(inode); return; make_bad: btrfs_free_path(path); make_bad_inode(inode); } /* * given a leaf and an inode, copy the inode fields into the leaf */ static void fill_inode_item(struct btrfs_trans_handle *trans, struct extent_buffer *leaf, struct btrfs_inode_item *item, struct inode *inode) { btrfs_set_inode_uid(leaf, item, i_uid_read(inode)); btrfs_set_inode_gid(leaf, item, i_gid_read(inode)); btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size); btrfs_set_inode_mode(leaf, item, inode->i_mode); btrfs_set_inode_nlink(leaf, item, inode->i_nlink); btrfs_set_timespec_sec(leaf, btrfs_inode_atime(item), inode->i_atime.tv_sec); btrfs_set_timespec_nsec(leaf, btrfs_inode_atime(item), inode->i_atime.tv_nsec); btrfs_set_timespec_sec(leaf, btrfs_inode_mtime(item), inode->i_mtime.tv_sec); btrfs_set_timespec_nsec(leaf, btrfs_inode_mtime(item), inode->i_mtime.tv_nsec); btrfs_set_timespec_sec(leaf, btrfs_inode_ctime(item), inode->i_ctime.tv_sec); btrfs_set_timespec_nsec(leaf, btrfs_inode_ctime(item), inode->i_ctime.tv_nsec); btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode)); btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation); btrfs_set_inode_sequence(leaf, item, inode->i_version); btrfs_set_inode_transid(leaf, item, trans->transid); btrfs_set_inode_rdev(leaf, item, inode->i_rdev); btrfs_set_inode_flags(leaf, item, BTRFS_I(inode)->flags); btrfs_set_inode_block_group(leaf, item, 0); } /* * copy everything in the in-memory inode into the btree. */ static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *inode) { struct btrfs_inode_item *inode_item; struct btrfs_path *path; struct extent_buffer *leaf; int ret; path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->leave_spinning = 1; ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location, 1); if (ret) { if (ret > 0) ret = -ENOENT; goto failed; } btrfs_unlock_up_safe(path, 1); leaf = path->nodes[0]; inode_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_inode_item); fill_inode_item(trans, leaf, inode_item, inode); btrfs_mark_buffer_dirty(leaf); btrfs_set_inode_last_trans(trans, inode); ret = 0; failed: btrfs_free_path(path); return ret; } /* * copy everything in the in-memory inode into the btree. */ noinline int btrfs_update_inode(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *inode) { int ret; /* * If the inode is a free space inode, we can deadlock during commit * if we put it into the delayed code. * * The data relocation inode should also be directly updated * without delay */ if (!btrfs_is_free_space_inode(inode) && root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) { btrfs_update_root_times(trans, root); ret = btrfs_delayed_update_inode(trans, root, inode); if (!ret) btrfs_set_inode_last_trans(trans, inode); return ret; } return btrfs_update_inode_item(trans, root, inode); } noinline int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *inode) { int ret; ret = btrfs_update_inode(trans, root, inode); if (ret == -ENOSPC) return btrfs_update_inode_item(trans, root, inode); return ret; } /* * unlink helper that gets used here in inode.c and in the tree logging * recovery code. It remove a link in a directory with a given name, and * also drops the back refs in the inode to the directory */ static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *dir, struct inode *inode, const char *name, int name_len) { struct btrfs_path *path; int ret = 0; struct extent_buffer *leaf; struct btrfs_dir_item *di; struct btrfs_key key; u64 index; u64 ino = btrfs_ino(inode); u64 dir_ino = btrfs_ino(dir); path = btrfs_alloc_path(); if (!path) { ret = -ENOMEM; goto out; } path->leave_spinning = 1; di = btrfs_lookup_dir_item(trans, root, path, dir_ino, name, name_len, -1); if (IS_ERR(di)) { ret = PTR_ERR(di); goto err; } if (!di) { ret = -ENOENT; goto err; } leaf = path->nodes[0]; btrfs_dir_item_key_to_cpu(leaf, di, &key); ret = btrfs_delete_one_dir_name(trans, root, path, di); if (ret) goto err; btrfs_release_path(path); ret = btrfs_del_inode_ref(trans, root, name, name_len, ino, dir_ino, &index); if (ret) { printk(KERN_INFO "btrfs failed to delete reference to %.*s, " "inode %llu parent %llu\n", name_len, name, (unsigned long long)ino, (unsigned long long)dir_ino); btrfs_abort_transaction(trans, root, ret); goto err; } ret = btrfs_delete_delayed_dir_index(trans, root, dir, index); if (ret) { btrfs_abort_transaction(trans, root, ret); goto err; } ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, inode, dir_ino); if (ret != 0 && ret != -ENOENT) { btrfs_abort_transaction(trans, root, ret); goto err; } ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, dir, index); if (ret == -ENOENT) ret = 0; err: btrfs_free_path(path); if (ret) goto out; btrfs_i_size_write(dir, dir->i_size - name_len * 2); inode_inc_iversion(inode); inode_inc_iversion(dir); inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME; ret = btrfs_update_inode(trans, root, dir); out: return ret; } int btrfs_unlink_inode(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *dir, struct inode *inode, const char *name, int name_len) { int ret; ret = __btrfs_unlink_inode(trans, root, dir, inode, name, name_len); if (!ret) { btrfs_drop_nlink(inode); ret = btrfs_update_inode(trans, root, inode); } return ret; } /* helper to check if there is any shared block in the path */ static int check_path_shared(struct btrfs_root *root, struct btrfs_path *path) { struct extent_buffer *eb; int level; u64 refs = 1; for (level = 0; level < BTRFS_MAX_LEVEL; level++) { int ret; if (!path->nodes[level]) break; eb = path->nodes[level]; if (!btrfs_block_can_be_shared(root, eb)) continue; ret = btrfs_lookup_extent_info(NULL, root, eb->start, eb->len, &refs, NULL); if (refs > 1) return 1; } return 0; } /* * helper to start transaction for unlink and rmdir. * * unlink and rmdir are special in btrfs, they do not always free space. * so in enospc case, we should make sure they will free space before * allowing them to use the global metadata reservation. */ static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir, struct dentry *dentry) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(dir)->root; struct btrfs_path *path; struct btrfs_dir_item *di; struct inode *inode = dentry->d_inode; u64 index; int check_link = 1; int err = -ENOSPC; int ret; u64 ino = btrfs_ino(inode); u64 dir_ino = btrfs_ino(dir); /* * 1 for the possible orphan item * 1 for the dir item * 1 for the dir index * 1 for the inode ref * 1 for the inode ref in the tree log * 2 for the dir entries in the log * 1 for the inode */ trans = btrfs_start_transaction(root, 8); if (!IS_ERR(trans) || PTR_ERR(trans) != -ENOSPC) return trans; if (ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) return ERR_PTR(-ENOSPC); /* check if there is someone else holds reference */ if (S_ISDIR(inode->i_mode) && atomic_read(&inode->i_count) > 1) return ERR_PTR(-ENOSPC); if (atomic_read(&inode->i_count) > 2) return ERR_PTR(-ENOSPC); if (xchg(&root->fs_info->enospc_unlink, 1)) return ERR_PTR(-ENOSPC); path = btrfs_alloc_path(); if (!path) { root->fs_info->enospc_unlink = 0; return ERR_PTR(-ENOMEM); } /* 1 for the orphan item */ trans = btrfs_start_transaction(root, 1); if (IS_ERR(trans)) { btrfs_free_path(path); root->fs_info->enospc_unlink = 0; return trans; } path->skip_locking = 1; path->search_commit_root = 1; ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(dir)->location, 0); if (ret < 0) { err = ret; goto out; } if (ret == 0) { if (check_path_shared(root, path)) goto out; } else { check_link = 0; } btrfs_release_path(path); ret = btrfs_lookup_inode(trans, root, path, &BTRFS_I(inode)->location, 0); if (ret < 0) { err = ret; goto out; } if (ret == 0) { if (check_path_shared(root, path)) goto out; } else { check_link = 0; } btrfs_release_path(path); if (ret == 0 && S_ISREG(inode->i_mode)) { ret = btrfs_lookup_file_extent(trans, root, path, ino, (u64)-1, 0); if (ret < 0) { err = ret; goto out; } BUG_ON(ret == 0); /* Corruption */ if (check_path_shared(root, path)) goto out; btrfs_release_path(path); } if (!check_link) { err = 0; goto out; } di = btrfs_lookup_dir_item(trans, root, path, dir_ino, dentry->d_name.name, dentry->d_name.len, 0); if (IS_ERR(di)) { err = PTR_ERR(di); goto out; } if (di) { if (check_path_shared(root, path)) goto out; } else { err = 0; goto out; } btrfs_release_path(path); ret = btrfs_get_inode_ref_index(trans, root, path, dentry->d_name.name, dentry->d_name.len, ino, dir_ino, 0, &index); if (ret) { err = ret; goto out; } if (check_path_shared(root, path)) goto out; btrfs_release_path(path); /* * This is a commit root search, if we can lookup inode item and other * relative items in the commit root, it means the transaction of * dir/file creation has been committed, and the dir index item that we * delay to insert has also been inserted into the commit root. So * we needn't worry about the delayed insertion of the dir index item * here. */ di = btrfs_lookup_dir_index_item(trans, root, path, dir_ino, index, dentry->d_name.name, dentry->d_name.len, 0); if (IS_ERR(di)) { err = PTR_ERR(di); goto out; } BUG_ON(ret == -ENOENT); if (check_path_shared(root, path)) goto out; err = 0; out: btrfs_free_path(path); /* Migrate the orphan reservation over */ if (!err) err = btrfs_block_rsv_migrate(trans->block_rsv, &root->fs_info->global_block_rsv, trans->bytes_reserved); if (err) { btrfs_end_transaction(trans, root); root->fs_info->enospc_unlink = 0; return ERR_PTR(err); } trans->block_rsv = &root->fs_info->global_block_rsv; return trans; } static void __unlink_end_trans(struct btrfs_trans_handle *trans, struct btrfs_root *root) { if (trans->block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL) { btrfs_block_rsv_release(root, trans->block_rsv, trans->bytes_reserved); trans->block_rsv = &root->fs_info->trans_block_rsv; BUG_ON(!root->fs_info->enospc_unlink); root->fs_info->enospc_unlink = 0; } btrfs_end_transaction(trans, root); } static int btrfs_unlink(struct inode *dir, struct dentry *dentry) { struct btrfs_root *root = BTRFS_I(dir)->root; struct btrfs_trans_handle *trans; struct inode *inode = dentry->d_inode; int ret; trans = __unlink_start_trans(dir, dentry); if (IS_ERR(trans)) return PTR_ERR(trans); btrfs_record_unlink_dir(trans, dir, dentry->d_inode, 0); ret = btrfs_unlink_inode(trans, root, dir, dentry->d_inode, dentry->d_name.name, dentry->d_name.len); if (ret) goto out; if (inode->i_nlink == 0) { ret = btrfs_orphan_add(trans, inode); if (ret) goto out; } out: __unlink_end_trans(trans, root); btrfs_btree_balance_dirty(root); return ret; } int btrfs_unlink_subvol(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *dir, u64 objectid, const char *name, int name_len) { struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_dir_item *di; struct btrfs_key key; u64 index; int ret; u64 dir_ino = btrfs_ino(dir); path = btrfs_alloc_path(); if (!path) return -ENOMEM; di = btrfs_lookup_dir_item(trans, root, path, dir_ino, name, name_len, -1); if (IS_ERR_OR_NULL(di)) { if (!di) ret = -ENOENT; else ret = PTR_ERR(di); goto out; } leaf = path->nodes[0]; btrfs_dir_item_key_to_cpu(leaf, di, &key); WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid); ret = btrfs_delete_one_dir_name(trans, root, path, di); if (ret) { btrfs_abort_transaction(trans, root, ret); goto out; } btrfs_release_path(path); ret = btrfs_del_root_ref(trans, root->fs_info->tree_root, objectid, root->root_key.objectid, dir_ino, &index, name, name_len); if (ret < 0) { if (ret != -ENOENT) { btrfs_abort_transaction(trans, root, ret); goto out; } di = btrfs_search_dir_index_item(root, path, dir_ino, name, name_len); if (IS_ERR_OR_NULL(di)) { if (!di) ret = -ENOENT; else ret = PTR_ERR(di); btrfs_abort_transaction(trans, root, ret); goto out; } leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); btrfs_release_path(path); index = key.offset; } btrfs_release_path(path); ret = btrfs_delete_delayed_dir_index(trans, root, dir, index); if (ret) { btrfs_abort_transaction(trans, root, ret); goto out; } btrfs_i_size_write(dir, dir->i_size - name_len * 2); inode_inc_iversion(dir); dir->i_mtime = dir->i_ctime = CURRENT_TIME; ret = btrfs_update_inode_fallback(trans, root, dir); if (ret) btrfs_abort_transaction(trans, root, ret); out: btrfs_free_path(path); return ret; } static int btrfs_rmdir(struct inode *dir, struct dentry *dentry) { struct inode *inode = dentry->d_inode; int err = 0; struct btrfs_root *root = BTRFS_I(dir)->root; struct btrfs_trans_handle *trans; if (inode->i_size > BTRFS_EMPTY_DIR_SIZE) return -ENOTEMPTY; if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) return -EPERM; trans = __unlink_start_trans(dir, dentry); if (IS_ERR(trans)) return PTR_ERR(trans); if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) { err = btrfs_unlink_subvol(trans, root, dir, BTRFS_I(inode)->location.objectid, dentry->d_name.name, dentry->d_name.len); goto out; } err = btrfs_orphan_add(trans, inode); if (err) goto out; /* now the directory is empty */ err = btrfs_unlink_inode(trans, root, dir, dentry->d_inode, dentry->d_name.name, dentry->d_name.len); if (!err) btrfs_i_size_write(inode, 0); out: __unlink_end_trans(trans, root); btrfs_btree_balance_dirty(root); return err; } /* * this can truncate away extent items, csum items and directory items. * It starts at a high offset and removes keys until it can't find * any higher than new_size * * csum items that cross the new i_size are truncated to the new size * as well. * * min_type is the minimum key type to truncate down to. If set to 0, this * will kill all the items on this inode, including the INODE_ITEM_KEY. */ int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *inode, u64 new_size, u32 min_type) { struct btrfs_path *path; struct extent_buffer *leaf; struct btrfs_file_extent_item *fi; struct btrfs_key key; struct btrfs_key found_key; u64 extent_start = 0; u64 extent_num_bytes = 0; u64 extent_offset = 0; u64 item_end = 0; u64 mask = root->sectorsize - 1; u32 found_type = (u8)-1; int found_extent; int del_item; int pending_del_nr = 0; int pending_del_slot = 0; int extent_type = -1; int ret; int err = 0; u64 ino = btrfs_ino(inode); BUG_ON(new_size > 0 && min_type != BTRFS_EXTENT_DATA_KEY); path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->reada = -1; /* * We want to drop from the next block forward in case this new size is * not block aligned since we will be keeping the last block of the * extent just the way it is. */ if (root->ref_cows || root == root->fs_info->tree_root) btrfs_drop_extent_cache(inode, (new_size + mask) & (~mask), (u64)-1, 0); /* * This function is also used to drop the items in the log tree before * we relog the inode, so if root != BTRFS_I(inode)->root, it means * it is used to drop the loged items. So we shouldn't kill the delayed * items. */ if (min_type == 0 && root == BTRFS_I(inode)->root) btrfs_kill_delayed_inode_items(inode); key.objectid = ino; key.offset = (u64)-1; key.type = (u8)-1; search_again: path->leave_spinning = 1; ret = btrfs_search_slot(trans, root, &key, path, -1, 1); if (ret < 0) { err = ret; goto out; } if (ret > 0) { /* there are no items in the tree for us to truncate, we're * done */ if (path->slots[0] == 0) goto out; path->slots[0]--; } while (1) { fi = NULL; leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); found_type = btrfs_key_type(&found_key); if (found_key.objectid != ino) break; if (found_type < min_type) break; item_end = found_key.offset; if (found_type == BTRFS_EXTENT_DATA_KEY) { fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); extent_type = btrfs_file_extent_type(leaf, fi); if (extent_type != BTRFS_FILE_EXTENT_INLINE) { item_end += btrfs_file_extent_num_bytes(leaf, fi); } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { item_end += btrfs_file_extent_inline_len(leaf, fi); } item_end--; } if (found_type > min_type) { del_item = 1; } else { if (item_end < new_size) break; if (found_key.offset >= new_size) del_item = 1; else del_item = 0; } found_extent = 0; /* FIXME, shrink the extent if the ref count is only 1 */ if (found_type != BTRFS_EXTENT_DATA_KEY) goto delete; if (extent_type != BTRFS_FILE_EXTENT_INLINE) { u64 num_dec; extent_start = btrfs_file_extent_disk_bytenr(leaf, fi); if (!del_item) { u64 orig_num_bytes = btrfs_file_extent_num_bytes(leaf, fi); extent_num_bytes = new_size - found_key.offset + root->sectorsize - 1; extent_num_bytes = extent_num_bytes & ~((u64)root->sectorsize - 1); btrfs_set_file_extent_num_bytes(leaf, fi, extent_num_bytes); num_dec = (orig_num_bytes - extent_num_bytes); if (root->ref_cows && extent_start != 0) inode_sub_bytes(inode, num_dec); btrfs_mark_buffer_dirty(leaf); } else { extent_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi); extent_offset = found_key.offset - btrfs_file_extent_offset(leaf, fi); /* FIXME blocksize != 4096 */ num_dec = btrfs_file_extent_num_bytes(leaf, fi); if (extent_start != 0) { found_extent = 1; if (root->ref_cows) inode_sub_bytes(inode, num_dec); } } } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) { /* * we can't truncate inline items that have had * special encodings */ if (!del_item && btrfs_file_extent_compression(leaf, fi) == 0 && btrfs_file_extent_encryption(leaf, fi) == 0 && btrfs_file_extent_other_encoding(leaf, fi) == 0) { u32 size = new_size - found_key.offset; if (root->ref_cows) { inode_sub_bytes(inode, item_end + 1 - new_size); } size = btrfs_file_extent_calc_inline_size(size); btrfs_truncate_item(trans, root, path, size, 1); } else if (root->ref_cows) { inode_sub_bytes(inode, item_end + 1 - found_key.offset); } } delete: if (del_item) { if (!pending_del_nr) { /* no pending yet, add ourselves */ pending_del_slot = path->slots[0]; pending_del_nr = 1; } else if (pending_del_nr && path->slots[0] + 1 == pending_del_slot) { /* hop on the pending chunk */ pending_del_nr++; pending_del_slot = path->slots[0]; } else { BUG(); } } else { break; } if (found_extent && (root->ref_cows || root == root->fs_info->tree_root)) { btrfs_set_path_blocking(path); ret = btrfs_free_extent(trans, root, extent_start, extent_num_bytes, 0, btrfs_header_owner(leaf), ino, extent_offset, 0); BUG_ON(ret); } if (found_type == BTRFS_INODE_ITEM_KEY) break; if (path->slots[0] == 0 || path->slots[0] != pending_del_slot) { if (pending_del_nr) { ret = btrfs_del_items(trans, root, path, pending_del_slot, pending_del_nr); if (ret) { btrfs_abort_transaction(trans, root, ret); goto error; } pending_del_nr = 0; } btrfs_release_path(path); goto search_again; } else { path->slots[0]--; } } out: if (pending_del_nr) { ret = btrfs_del_items(trans, root, path, pending_del_slot, pending_del_nr); if (ret) btrfs_abort_transaction(trans, root, ret); } error: btrfs_free_path(path); return err; } /* * btrfs_truncate_page - read, zero a chunk and write a page * @inode - inode that we're zeroing * @from - the offset to start zeroing * @len - the length to zero, 0 to zero the entire range respective to the * offset * @front - zero up to the offset instead of from the offset on * * This will find the page for the "from" offset and cow the page and zero the * part we want to zero. This is used with truncate and hole punching. */ int btrfs_truncate_page(struct inode *inode, loff_t from, loff_t len, int front) { struct address_space *mapping = inode->i_mapping; struct btrfs_root *root = BTRFS_I(inode)->root; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct btrfs_ordered_extent *ordered; struct extent_state *cached_state = NULL; char *kaddr; u32 blocksize = root->sectorsize; pgoff_t index = from >> PAGE_CACHE_SHIFT; unsigned offset = from & (PAGE_CACHE_SIZE-1); struct page *page; gfp_t mask = btrfs_alloc_write_mask(mapping); int ret = 0; u64 page_start; u64 page_end; if ((offset & (blocksize - 1)) == 0 && (!len || ((len & (blocksize - 1)) == 0))) goto out; ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE); if (ret) goto out; again: page = find_or_create_page(mapping, index, mask); if (!page) { btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE); ret = -ENOMEM; goto out; } page_start = page_offset(page); page_end = page_start + PAGE_CACHE_SIZE - 1; if (!PageUptodate(page)) { ret = btrfs_readpage(NULL, page); lock_page(page); if (page->mapping != mapping) { unlock_page(page); page_cache_release(page); goto again; } if (!PageUptodate(page)) { ret = -EIO; goto out_unlock; } } wait_on_page_writeback(page); lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state); set_page_extent_mapped(page); ordered = btrfs_lookup_ordered_extent(inode, page_start); if (ordered) { unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS); unlock_page(page); page_cache_release(page); btrfs_start_ordered_extent(inode, ordered, 1); btrfs_put_ordered_extent(ordered); goto again; } clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end, EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS); ret = btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state); if (ret) { unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS); goto out_unlock; } if (offset != PAGE_CACHE_SIZE) { if (!len) len = PAGE_CACHE_SIZE - offset; kaddr = kmap(page); if (front) memset(kaddr, 0, offset); else memset(kaddr + offset, 0, len); flush_dcache_page(page); kunmap(page); } ClearPageChecked(page); set_page_dirty(page); unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS); out_unlock: if (ret) btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE); unlock_page(page); page_cache_release(page); out: return ret; } /* * This function puts in dummy file extents for the area we're creating a hole * for. So if we are truncating this file to a larger size we need to insert * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for * the range between oldsize and size */ int btrfs_cont_expand(struct inode *inode, loff_t oldsize, loff_t size) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(inode)->root; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct extent_map *em = NULL; struct extent_state *cached_state = NULL; struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; u64 mask = root->sectorsize - 1; u64 hole_start = (oldsize + mask) & ~mask; u64 block_end = (size + mask) & ~mask; u64 last_byte; u64 cur_offset; u64 hole_size; int err = 0; if (size <= hole_start) return 0; while (1) { struct btrfs_ordered_extent *ordered; btrfs_wait_ordered_range(inode, hole_start, block_end - hole_start); lock_extent_bits(io_tree, hole_start, block_end - 1, 0, &cached_state); ordered = btrfs_lookup_ordered_extent(inode, hole_start); if (!ordered) break; unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state, GFP_NOFS); btrfs_put_ordered_extent(ordered); } cur_offset = hole_start; while (1) { em = btrfs_get_extent(inode, NULL, 0, cur_offset, block_end - cur_offset, 0); if (IS_ERR(em)) { err = PTR_ERR(em); break; } last_byte = min(extent_map_end(em), block_end); last_byte = (last_byte + mask) & ~mask; if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) { struct extent_map *hole_em; hole_size = last_byte - cur_offset; trans = btrfs_start_transaction(root, 3); if (IS_ERR(trans)) { err = PTR_ERR(trans); break; } err = btrfs_drop_extents(trans, root, inode, cur_offset, cur_offset + hole_size, 1); if (err) { btrfs_abort_transaction(trans, root, err); btrfs_end_transaction(trans, root); break; } err = btrfs_insert_file_extent(trans, root, btrfs_ino(inode), cur_offset, 0, 0, hole_size, 0, hole_size, 0, 0, 0); if (err) { btrfs_abort_transaction(trans, root, err); btrfs_end_transaction(trans, root); break; } btrfs_drop_extent_cache(inode, cur_offset, cur_offset + hole_size - 1, 0); hole_em = alloc_extent_map(); if (!hole_em) { set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags); goto next; } hole_em->start = cur_offset; hole_em->len = hole_size; hole_em->orig_start = cur_offset; hole_em->block_start = EXTENT_MAP_HOLE; hole_em->block_len = 0; hole_em->orig_block_len = 0; hole_em->bdev = root->fs_info->fs_devices->latest_bdev; hole_em->compress_type = BTRFS_COMPRESS_NONE; hole_em->generation = trans->transid; while (1) { write_lock(&em_tree->lock); err = add_extent_mapping(em_tree, hole_em); if (!err) list_move(&hole_em->list, &em_tree->modified_extents); write_unlock(&em_tree->lock); if (err != -EEXIST) break; btrfs_drop_extent_cache(inode, cur_offset, cur_offset + hole_size - 1, 0); } free_extent_map(hole_em); next: btrfs_update_inode(trans, root, inode); btrfs_end_transaction(trans, root); } free_extent_map(em); em = NULL; cur_offset = last_byte; if (cur_offset >= block_end) break; } free_extent_map(em); unlock_extent_cached(io_tree, hole_start, block_end - 1, &cached_state, GFP_NOFS); return err; } static int btrfs_setsize(struct inode *inode, loff_t newsize) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; loff_t oldsize = i_size_read(inode); int ret; if (newsize == oldsize) return 0; if (newsize > oldsize) { truncate_pagecache(inode, oldsize, newsize); ret = btrfs_cont_expand(inode, oldsize, newsize); if (ret) return ret; trans = btrfs_start_transaction(root, 1); if (IS_ERR(trans)) return PTR_ERR(trans); i_size_write(inode, newsize); btrfs_ordered_update_i_size(inode, i_size_read(inode), NULL); ret = btrfs_update_inode(trans, root, inode); btrfs_end_transaction(trans, root); } else { /* * We're truncating a file that used to have good data down to * zero. Make sure it gets into the ordered flush list so that * any new writes get down to disk quickly. */ if (newsize == 0) set_bit(BTRFS_INODE_ORDERED_DATA_CLOSE, &BTRFS_I(inode)->runtime_flags); /* we don't support swapfiles, so vmtruncate shouldn't fail */ truncate_setsize(inode, newsize); ret = btrfs_truncate(inode); } return ret; } static int btrfs_setattr(struct dentry *dentry, struct iattr *attr) { struct inode *inode = dentry->d_inode; struct btrfs_root *root = BTRFS_I(inode)->root; int err; if (btrfs_root_readonly(root)) return -EROFS; err = inode_change_ok(inode, attr); if (err) return err; if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) { err = btrfs_setsize(inode, attr->ia_size); if (err) return err; } if (attr->ia_valid) { setattr_copy(inode, attr); inode_inc_iversion(inode); err = btrfs_dirty_inode(inode); if (!err && attr->ia_valid & ATTR_MODE) err = btrfs_acl_chmod(inode); } return err; } void btrfs_evict_inode(struct inode *inode) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_block_rsv *rsv, *global_rsv; u64 min_size = btrfs_calc_trunc_metadata_size(root, 1); int ret; trace_btrfs_inode_evict(inode); truncate_inode_pages(&inode->i_data, 0); if (inode->i_nlink && (btrfs_root_refs(&root->root_item) != 0 || btrfs_is_free_space_inode(inode))) goto no_delete; if (is_bad_inode(inode)) { btrfs_orphan_del(NULL, inode); goto no_delete; } /* do we really want it for ->i_nlink > 0 and zero btrfs_root_refs? */ btrfs_wait_ordered_range(inode, 0, (u64)-1); if (root->fs_info->log_root_recovering) { BUG_ON(test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM, &BTRFS_I(inode)->runtime_flags)); goto no_delete; } if (inode->i_nlink > 0) { BUG_ON(btrfs_root_refs(&root->root_item) != 0); goto no_delete; } rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP); if (!rsv) { btrfs_orphan_del(NULL, inode); goto no_delete; } rsv->size = min_size; rsv->failfast = 1; global_rsv = &root->fs_info->global_block_rsv; btrfs_i_size_write(inode, 0); /* * This is a bit simpler than btrfs_truncate since we've already * reserved our space for our orphan item in the unlink, so we just * need to reserve some slack space in case we add bytes and update * inode item when doing the truncate. */ while (1) { ret = btrfs_block_rsv_refill(root, rsv, min_size, BTRFS_RESERVE_FLUSH_LIMIT); /* * Try and steal from the global reserve since we will * likely not use this space anyway, we want to try as * hard as possible to get this to work. */ if (ret) ret = btrfs_block_rsv_migrate(global_rsv, rsv, min_size); if (ret) { printk(KERN_WARNING "Could not get space for a " "delete, will truncate on mount %d\n", ret); btrfs_orphan_del(NULL, inode); btrfs_free_block_rsv(root, rsv); goto no_delete; } trans = btrfs_start_transaction_lflush(root, 1); if (IS_ERR(trans)) { btrfs_orphan_del(NULL, inode); btrfs_free_block_rsv(root, rsv); goto no_delete; } trans->block_rsv = rsv; ret = btrfs_truncate_inode_items(trans, root, inode, 0, 0); if (ret != -ENOSPC) break; trans->block_rsv = &root->fs_info->trans_block_rsv; ret = btrfs_update_inode(trans, root, inode); BUG_ON(ret); btrfs_end_transaction(trans, root); trans = NULL; btrfs_btree_balance_dirty(root); } btrfs_free_block_rsv(root, rsv); if (ret == 0) { trans->block_rsv = root->orphan_block_rsv; ret = btrfs_orphan_del(trans, inode); BUG_ON(ret); } trans->block_rsv = &root->fs_info->trans_block_rsv; if (!(root == root->fs_info->tree_root || root->root_key.objectid == BTRFS_TREE_RELOC_OBJECTID)) btrfs_return_ino(root, btrfs_ino(inode)); btrfs_end_transaction(trans, root); btrfs_btree_balance_dirty(root); no_delete: clear_inode(inode); return; } /* * this returns the key found in the dir entry in the location pointer. * If no dir entries were found, location->objectid is 0. */ static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry, struct btrfs_key *location) { const char *name = dentry->d_name.name; int namelen = dentry->d_name.len; struct btrfs_dir_item *di; struct btrfs_path *path; struct btrfs_root *root = BTRFS_I(dir)->root; int ret = 0; path = btrfs_alloc_path(); if (!path) return -ENOMEM; di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir), name, namelen, 0); if (IS_ERR(di)) ret = PTR_ERR(di); if (IS_ERR_OR_NULL(di)) goto out_err; btrfs_dir_item_key_to_cpu(path->nodes[0], di, location); out: btrfs_free_path(path); return ret; out_err: location->objectid = 0; goto out; } /* * when we hit a tree root in a directory, the btrfs part of the inode * needs to be changed to reflect the root directory of the tree root. This * is kind of like crossing a mount point. */ static int fixup_tree_root_location(struct btrfs_root *root, struct inode *dir, struct dentry *dentry, struct btrfs_key *location, struct btrfs_root **sub_root) { struct btrfs_path *path; struct btrfs_root *new_root; struct btrfs_root_ref *ref; struct extent_buffer *leaf; int ret; int err = 0; path = btrfs_alloc_path(); if (!path) { err = -ENOMEM; goto out; } err = -ENOENT; ret = btrfs_find_root_ref(root->fs_info->tree_root, path, BTRFS_I(dir)->root->root_key.objectid, location->objectid); if (ret) { if (ret < 0) err = ret; goto out; } leaf = path->nodes[0]; ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref); if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) || btrfs_root_ref_name_len(leaf, ref) != dentry->d_name.len) goto out; ret = memcmp_extent_buffer(leaf, dentry->d_name.name, (unsigned long)(ref + 1), dentry->d_name.len); if (ret) goto out; btrfs_release_path(path); new_root = btrfs_read_fs_root_no_name(root->fs_info, location); if (IS_ERR(new_root)) { err = PTR_ERR(new_root); goto out; } if (btrfs_root_refs(&new_root->root_item) == 0) { err = -ENOENT; goto out; } *sub_root = new_root; location->objectid = btrfs_root_dirid(&new_root->root_item); location->type = BTRFS_INODE_ITEM_KEY; location->offset = 0; err = 0; out: btrfs_free_path(path); return err; } static void inode_tree_add(struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_inode *entry; struct rb_node **p; struct rb_node *parent; u64 ino = btrfs_ino(inode); again: p = &root->inode_tree.rb_node; parent = NULL; if (inode_unhashed(inode)) return; spin_lock(&root->inode_lock); while (*p) { parent = *p; entry = rb_entry(parent, struct btrfs_inode, rb_node); if (ino < btrfs_ino(&entry->vfs_inode)) p = &parent->rb_left; else if (ino > btrfs_ino(&entry->vfs_inode)) p = &parent->rb_right; else { WARN_ON(!(entry->vfs_inode.i_state & (I_WILL_FREE | I_FREEING))); rb_erase(parent, &root->inode_tree); RB_CLEAR_NODE(parent); spin_unlock(&root->inode_lock); goto again; } } rb_link_node(&BTRFS_I(inode)->rb_node, parent, p); rb_insert_color(&BTRFS_I(inode)->rb_node, &root->inode_tree); spin_unlock(&root->inode_lock); } static void inode_tree_del(struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; int empty = 0; spin_lock(&root->inode_lock); if (!RB_EMPTY_NODE(&BTRFS_I(inode)->rb_node)) { rb_erase(&BTRFS_I(inode)->rb_node, &root->inode_tree); RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node); empty = RB_EMPTY_ROOT(&root->inode_tree); } spin_unlock(&root->inode_lock); /* * Free space cache has inodes in the tree root, but the tree root has a * root_refs of 0, so this could end up dropping the tree root as a * snapshot, so we need the extra !root->fs_info->tree_root check to * make sure we don't drop it. */ if (empty && btrfs_root_refs(&root->root_item) == 0 && root != root->fs_info->tree_root) { synchronize_srcu(&root->fs_info->subvol_srcu); spin_lock(&root->inode_lock); empty = RB_EMPTY_ROOT(&root->inode_tree); spin_unlock(&root->inode_lock); if (empty) btrfs_add_dead_root(root); } } void btrfs_invalidate_inodes(struct btrfs_root *root) { struct rb_node *node; struct rb_node *prev; struct btrfs_inode *entry; struct inode *inode; u64 objectid = 0; WARN_ON(btrfs_root_refs(&root->root_item) != 0); spin_lock(&root->inode_lock); again: node = root->inode_tree.rb_node; prev = NULL; while (node) { prev = node; entry = rb_entry(node, struct btrfs_inode, rb_node); if (objectid < btrfs_ino(&entry->vfs_inode)) node = node->rb_left; else if (objectid > btrfs_ino(&entry->vfs_inode)) node = node->rb_right; else break; } if (!node) { while (prev) { entry = rb_entry(prev, struct btrfs_inode, rb_node); if (objectid <= btrfs_ino(&entry->vfs_inode)) { node = prev; break; } prev = rb_next(prev); } } while (node) { entry = rb_entry(node, struct btrfs_inode, rb_node); objectid = btrfs_ino(&entry->vfs_inode) + 1; inode = igrab(&entry->vfs_inode); if (inode) { spin_unlock(&root->inode_lock); if (atomic_read(&inode->i_count) > 1) d_prune_aliases(inode); /* * btrfs_drop_inode will have it removed from * the inode cache when its usage count * hits zero. */ iput(inode); cond_resched(); spin_lock(&root->inode_lock); goto again; } if (cond_resched_lock(&root->inode_lock)) goto again; node = rb_next(node); } spin_unlock(&root->inode_lock); } static int btrfs_init_locked_inode(struct inode *inode, void *p) { struct btrfs_iget_args *args = p; inode->i_ino = args->ino; BTRFS_I(inode)->root = args->root; return 0; } static int btrfs_find_actor(struct inode *inode, void *opaque) { struct btrfs_iget_args *args = opaque; return args->ino == btrfs_ino(inode) && args->root == BTRFS_I(inode)->root; } static struct inode *btrfs_iget_locked(struct super_block *s, u64 objectid, struct btrfs_root *root) { struct inode *inode; struct btrfs_iget_args args; args.ino = objectid; args.root = root; inode = iget5_locked(s, objectid, btrfs_find_actor, btrfs_init_locked_inode, (void *)&args); return inode; } /* Get an inode object given its location and corresponding root. * Returns in *is_new if the inode was read from disk */ struct inode *btrfs_iget(struct super_block *s, struct btrfs_key *location, struct btrfs_root *root, int *new) { struct inode *inode; inode = btrfs_iget_locked(s, location->objectid, root); if (!inode) return ERR_PTR(-ENOMEM); if (inode->i_state & I_NEW) { BTRFS_I(inode)->root = root; memcpy(&BTRFS_I(inode)->location, location, sizeof(*location)); btrfs_read_locked_inode(inode); if (!is_bad_inode(inode)) { inode_tree_add(inode); unlock_new_inode(inode); if (new) *new = 1; } else { unlock_new_inode(inode); iput(inode); inode = ERR_PTR(-ESTALE); } } return inode; } static struct inode *new_simple_dir(struct super_block *s, struct btrfs_key *key, struct btrfs_root *root) { struct inode *inode = new_inode(s); if (!inode) return ERR_PTR(-ENOMEM); BTRFS_I(inode)->root = root; memcpy(&BTRFS_I(inode)->location, key, sizeof(*key)); set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags); inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID; inode->i_op = &btrfs_dir_ro_inode_operations; inode->i_fop = &simple_dir_operations; inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO; inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME; return inode; } struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry) { struct inode *inode; struct btrfs_root *root = BTRFS_I(dir)->root; struct btrfs_root *sub_root = root; struct btrfs_key location; int index; int ret = 0; if (dentry->d_name.len > BTRFS_NAME_LEN) return ERR_PTR(-ENAMETOOLONG); if (unlikely(d_need_lookup(dentry))) { memcpy(&location, dentry->d_fsdata, sizeof(struct btrfs_key)); kfree(dentry->d_fsdata); dentry->d_fsdata = NULL; /* This thing is hashed, drop it for now */ d_drop(dentry); } else { ret = btrfs_inode_by_name(dir, dentry, &location); } if (ret < 0) return ERR_PTR(ret); if (location.objectid == 0) return NULL; if (location.type == BTRFS_INODE_ITEM_KEY) { inode = btrfs_iget(dir->i_sb, &location, root, NULL); return inode; } BUG_ON(location.type != BTRFS_ROOT_ITEM_KEY); index = srcu_read_lock(&root->fs_info->subvol_srcu); ret = fixup_tree_root_location(root, dir, dentry, &location, &sub_root); if (ret < 0) { if (ret != -ENOENT) inode = ERR_PTR(ret); else inode = new_simple_dir(dir->i_sb, &location, sub_root); } else { inode = btrfs_iget(dir->i_sb, &location, sub_root, NULL); } srcu_read_unlock(&root->fs_info->subvol_srcu, index); if (!IS_ERR(inode) && root != sub_root) { down_read(&root->fs_info->cleanup_work_sem); if (!(inode->i_sb->s_flags & MS_RDONLY)) ret = btrfs_orphan_cleanup(sub_root); up_read(&root->fs_info->cleanup_work_sem); if (ret) inode = ERR_PTR(ret); } return inode; } static int btrfs_dentry_delete(const struct dentry *dentry) { struct btrfs_root *root; struct inode *inode = dentry->d_inode; if (!inode && !IS_ROOT(dentry)) inode = dentry->d_parent->d_inode; if (inode) { root = BTRFS_I(inode)->root; if (btrfs_root_refs(&root->root_item) == 0) return 1; if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) return 1; } return 0; } static void btrfs_dentry_release(struct dentry *dentry) { if (dentry->d_fsdata) kfree(dentry->d_fsdata); } static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags) { struct dentry *ret; ret = d_splice_alias(btrfs_lookup_dentry(dir, dentry), dentry); if (unlikely(d_need_lookup(dentry))) { spin_lock(&dentry->d_lock); dentry->d_flags &= ~DCACHE_NEED_LOOKUP; spin_unlock(&dentry->d_lock); } return ret; } unsigned char btrfs_filetype_table[] = { DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK }; static int btrfs_real_readdir(struct file *filp, void *dirent, filldir_t filldir) { struct inode *inode = filp->f_dentry->d_inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_item *item; struct btrfs_dir_item *di; struct btrfs_key key; struct btrfs_key found_key; struct btrfs_path *path; struct list_head ins_list; struct list_head del_list; int ret; struct extent_buffer *leaf; int slot; unsigned char d_type; int over = 0; u32 di_cur; u32 di_total; u32 di_len; int key_type = BTRFS_DIR_INDEX_KEY; char tmp_name[32]; char *name_ptr; int name_len; int is_curr = 0; /* filp->f_pos points to the current index? */ /* FIXME, use a real flag for deciding about the key type */ if (root->fs_info->tree_root == root) key_type = BTRFS_DIR_ITEM_KEY; /* special case for "." */ if (filp->f_pos == 0) { over = filldir(dirent, ".", 1, filp->f_pos, btrfs_ino(inode), DT_DIR); if (over) return 0; filp->f_pos = 1; } /* special case for .., just use the back ref */ if (filp->f_pos == 1) { u64 pino = parent_ino(filp->f_path.dentry); over = filldir(dirent, "..", 2, filp->f_pos, pino, DT_DIR); if (over) return 0; filp->f_pos = 2; } path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->reada = 1; if (key_type == BTRFS_DIR_INDEX_KEY) { INIT_LIST_HEAD(&ins_list); INIT_LIST_HEAD(&del_list); btrfs_get_delayed_items(inode, &ins_list, &del_list); } btrfs_set_key_type(&key, key_type); key.offset = filp->f_pos; key.objectid = btrfs_ino(inode); ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) goto err; while (1) { leaf = path->nodes[0]; slot = path->slots[0]; if (slot >= btrfs_header_nritems(leaf)) { ret = btrfs_next_leaf(root, path); if (ret < 0) goto err; else if (ret > 0) break; continue; } item = btrfs_item_nr(leaf, slot); btrfs_item_key_to_cpu(leaf, &found_key, slot); if (found_key.objectid != key.objectid) break; if (btrfs_key_type(&found_key) != key_type) break; if (found_key.offset < filp->f_pos) goto next; if (key_type == BTRFS_DIR_INDEX_KEY && btrfs_should_delete_dir_index(&del_list, found_key.offset)) goto next; filp->f_pos = found_key.offset; is_curr = 1; di = btrfs_item_ptr(leaf, slot, struct btrfs_dir_item); di_cur = 0; di_total = btrfs_item_size(leaf, item); while (di_cur < di_total) { struct btrfs_key location; if (verify_dir_item(root, leaf, di)) break; name_len = btrfs_dir_name_len(leaf, di); if (name_len <= sizeof(tmp_name)) { name_ptr = tmp_name; } else { name_ptr = kmalloc(name_len, GFP_NOFS); if (!name_ptr) { ret = -ENOMEM; goto err; } } read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1), name_len); d_type = btrfs_filetype_table[btrfs_dir_type(leaf, di)]; btrfs_dir_item_key_to_cpu(leaf, di, &location); /* is this a reference to our own snapshot? If so * skip it. * * In contrast to old kernels, we insert the snapshot's * dir item and dir index after it has been created, so * we won't find a reference to our own snapshot. We * still keep the following code for backward * compatibility. */ if (location.type == BTRFS_ROOT_ITEM_KEY && location.objectid == root->root_key.objectid) { over = 0; goto skip; } over = filldir(dirent, name_ptr, name_len, found_key.offset, location.objectid, d_type); skip: if (name_ptr != tmp_name) kfree(name_ptr); if (over) goto nopos; di_len = btrfs_dir_name_len(leaf, di) + btrfs_dir_data_len(leaf, di) + sizeof(*di); di_cur += di_len; di = (struct btrfs_dir_item *)((char *)di + di_len); } next: path->slots[0]++; } if (key_type == BTRFS_DIR_INDEX_KEY) { if (is_curr) filp->f_pos++; ret = btrfs_readdir_delayed_dir_index(filp, dirent, filldir, &ins_list); if (ret) goto nopos; } /* Reached end of directory/root. Bump pos past the last item. */ if (key_type == BTRFS_DIR_INDEX_KEY) /* * 32-bit glibc will use getdents64, but then strtol - * so the last number we can serve is this. */ filp->f_pos = 0x7fffffff; else filp->f_pos++; nopos: ret = 0; err: if (key_type == BTRFS_DIR_INDEX_KEY) btrfs_put_delayed_items(&ins_list, &del_list); btrfs_free_path(path); return ret; } int btrfs_write_inode(struct inode *inode, struct writeback_control *wbc) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; int ret = 0; bool nolock = false; if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags)) return 0; if (btrfs_fs_closing(root->fs_info) && btrfs_is_free_space_inode(inode)) nolock = true; if (wbc->sync_mode == WB_SYNC_ALL) { if (nolock) trans = btrfs_join_transaction_nolock(root); else trans = btrfs_join_transaction(root); if (IS_ERR(trans)) return PTR_ERR(trans); ret = btrfs_commit_transaction(trans, root); } return ret; } /* * This is somewhat expensive, updating the tree every time the * inode changes. But, it is most likely to find the inode in cache. * FIXME, needs more benchmarking...there are no reasons other than performance * to keep or drop this code. */ int btrfs_dirty_inode(struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; int ret; if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags)) return 0; trans = btrfs_join_transaction(root); if (IS_ERR(trans)) return PTR_ERR(trans); ret = btrfs_update_inode(trans, root, inode); if (ret && ret == -ENOSPC) { /* whoops, lets try again with the full transaction */ btrfs_end_transaction(trans, root); trans = btrfs_start_transaction(root, 1); if (IS_ERR(trans)) return PTR_ERR(trans); ret = btrfs_update_inode(trans, root, inode); } btrfs_end_transaction(trans, root); if (BTRFS_I(inode)->delayed_node) btrfs_balance_delayed_items(root); return ret; } /* * This is a copy of file_update_time. We need this so we can return error on * ENOSPC for updating the inode in the case of file write and mmap writes. */ static int btrfs_update_time(struct inode *inode, struct timespec *now, int flags) { struct btrfs_root *root = BTRFS_I(inode)->root; if (btrfs_root_readonly(root)) return -EROFS; if (flags & S_VERSION) inode_inc_iversion(inode); if (flags & S_CTIME) inode->i_ctime = *now; if (flags & S_MTIME) inode->i_mtime = *now; if (flags & S_ATIME) inode->i_atime = *now; return btrfs_dirty_inode(inode); } /* * find the highest existing sequence number in a directory * and then set the in-memory index_cnt variable to reflect * free sequence numbers */ static int btrfs_set_inode_index_count(struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_key key, found_key; struct btrfs_path *path; struct extent_buffer *leaf; int ret; key.objectid = btrfs_ino(inode); btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY); key.offset = (u64)-1; path = btrfs_alloc_path(); if (!path) return -ENOMEM; ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) goto out; /* FIXME: we should be able to handle this */ if (ret == 0) goto out; ret = 0; /* * MAGIC NUMBER EXPLANATION: * since we search a directory based on f_pos we have to start at 2 * since '.' and '..' have f_pos of 0 and 1 respectively, so everybody * else has to start at 2 */ if (path->slots[0] == 0) { BTRFS_I(inode)->index_cnt = 2; goto out; } path->slots[0]--; leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); if (found_key.objectid != btrfs_ino(inode) || btrfs_key_type(&found_key) != BTRFS_DIR_INDEX_KEY) { BTRFS_I(inode)->index_cnt = 2; goto out; } BTRFS_I(inode)->index_cnt = found_key.offset + 1; out: btrfs_free_path(path); return ret; } /* * helper to find a free sequence number in a given directory. This current * code is very simple, later versions will do smarter things in the btree */ int btrfs_set_inode_index(struct inode *dir, u64 *index) { int ret = 0; if (BTRFS_I(dir)->index_cnt == (u64)-1) { ret = btrfs_inode_delayed_dir_index_count(dir); if (ret) { ret = btrfs_set_inode_index_count(dir); if (ret) return ret; } } *index = BTRFS_I(dir)->index_cnt; BTRFS_I(dir)->index_cnt++; return ret; } static struct inode *btrfs_new_inode(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct inode *dir, const char *name, int name_len, u64 ref_objectid, u64 objectid, umode_t mode, u64 *index) { struct inode *inode; struct btrfs_inode_item *inode_item; struct btrfs_key *location; struct btrfs_path *path; struct btrfs_inode_ref *ref; struct btrfs_key key[2]; u32 sizes[2]; unsigned long ptr; int ret; int owner; path = btrfs_alloc_path(); if (!path) return ERR_PTR(-ENOMEM); inode = new_inode(root->fs_info->sb); if (!inode) { btrfs_free_path(path); return ERR_PTR(-ENOMEM); } /* * we have to initialize this early, so we can reclaim the inode * number if we fail afterwards in this function. */ inode->i_ino = objectid; if (dir) { trace_btrfs_inode_request(dir); ret = btrfs_set_inode_index(dir, index); if (ret) { btrfs_free_path(path); iput(inode); return ERR_PTR(ret); } } /* * index_cnt is ignored for everything but a dir, * btrfs_get_inode_index_count has an explanation for the magic * number */ BTRFS_I(inode)->index_cnt = 2; BTRFS_I(inode)->root = root; BTRFS_I(inode)->generation = trans->transid; inode->i_generation = BTRFS_I(inode)->generation; /* * We could have gotten an inode number from somebody who was fsynced * and then removed in this same transaction, so let's just set full * sync since it will be a full sync anyway and this will blow away the * old info in the log. */ set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags); if (S_ISDIR(mode)) owner = 0; else owner = 1; key[0].objectid = objectid; btrfs_set_key_type(&key[0], BTRFS_INODE_ITEM_KEY); key[0].offset = 0; /* * Start new inodes with an inode_ref. This is slightly more * efficient for small numbers of hard links since they will * be packed into one item. Extended refs will kick in if we * add more hard links than can fit in the ref item. */ key[1].objectid = objectid; btrfs_set_key_type(&key[1], BTRFS_INODE_REF_KEY); key[1].offset = ref_objectid; sizes[0] = sizeof(struct btrfs_inode_item); sizes[1] = name_len + sizeof(*ref); path->leave_spinning = 1; ret = btrfs_insert_empty_items(trans, root, path, key, sizes, 2); if (ret != 0) goto fail; inode_init_owner(inode, dir, mode); inode_set_bytes(inode, 0); inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME; inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0], struct btrfs_inode_item); memset_extent_buffer(path->nodes[0], 0, (unsigned long)inode_item, sizeof(*inode_item)); fill_inode_item(trans, path->nodes[0], inode_item, inode); ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1, struct btrfs_inode_ref); btrfs_set_inode_ref_name_len(path->nodes[0], ref, name_len); btrfs_set_inode_ref_index(path->nodes[0], ref, *index); ptr = (unsigned long)(ref + 1); write_extent_buffer(path->nodes[0], name, ptr, name_len); btrfs_mark_buffer_dirty(path->nodes[0]); btrfs_free_path(path); location = &BTRFS_I(inode)->location; location->objectid = objectid; location->offset = 0; btrfs_set_key_type(location, BTRFS_INODE_ITEM_KEY); btrfs_inherit_iflags(inode, dir); if (S_ISREG(mode)) { if (btrfs_test_opt(root, NODATASUM)) BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM; if (btrfs_test_opt(root, NODATACOW) || (BTRFS_I(dir)->flags & BTRFS_INODE_NODATACOW)) BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW; } insert_inode_hash(inode); inode_tree_add(inode); trace_btrfs_inode_new(inode); btrfs_set_inode_last_trans(trans, inode); btrfs_update_root_times(trans, root); return inode; fail: if (dir) BTRFS_I(dir)->index_cnt--; btrfs_free_path(path); iput(inode); return ERR_PTR(ret); } static inline u8 btrfs_inode_type(struct inode *inode) { return btrfs_type_by_mode[(inode->i_mode & S_IFMT) >> S_SHIFT]; } /* * utility function to add 'inode' into 'parent_inode' with * a give name and a given sequence number. * if 'add_backref' is true, also insert a backref from the * inode to the parent directory. */ int btrfs_add_link(struct btrfs_trans_handle *trans, struct inode *parent_inode, struct inode *inode, const char *name, int name_len, int add_backref, u64 index) { int ret = 0; struct btrfs_key key; struct btrfs_root *root = BTRFS_I(parent_inode)->root; u64 ino = btrfs_ino(inode); u64 parent_ino = btrfs_ino(parent_inode); if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { memcpy(&key, &BTRFS_I(inode)->root->root_key, sizeof(key)); } else { key.objectid = ino; btrfs_set_key_type(&key, BTRFS_INODE_ITEM_KEY); key.offset = 0; } if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { ret = btrfs_add_root_ref(trans, root->fs_info->tree_root, key.objectid, root->root_key.objectid, parent_ino, index, name, name_len); } else if (add_backref) { ret = btrfs_insert_inode_ref(trans, root, name, name_len, ino, parent_ino, index); } /* Nothing to clean up yet */ if (ret) return ret; ret = btrfs_insert_dir_item(trans, root, name, name_len, parent_inode, &key, btrfs_inode_type(inode), index); if (ret == -EEXIST || ret == -EOVERFLOW) goto fail_dir_item; else if (ret) { btrfs_abort_transaction(trans, root, ret); return ret; } btrfs_i_size_write(parent_inode, parent_inode->i_size + name_len * 2); inode_inc_iversion(parent_inode); parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME; ret = btrfs_update_inode(trans, root, parent_inode); if (ret) btrfs_abort_transaction(trans, root, ret); return ret; fail_dir_item: if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) { u64 local_index; int err; err = btrfs_del_root_ref(trans, root->fs_info->tree_root, key.objectid, root->root_key.objectid, parent_ino, &local_index, name, name_len); } else if (add_backref) { u64 local_index; int err; err = btrfs_del_inode_ref(trans, root, name, name_len, ino, parent_ino, &local_index); } return ret; } static int btrfs_add_nondir(struct btrfs_trans_handle *trans, struct inode *dir, struct dentry *dentry, struct inode *inode, int backref, u64 index) { int err = btrfs_add_link(trans, dir, inode, dentry->d_name.name, dentry->d_name.len, backref, index); if (err > 0) err = -EEXIST; return err; } static int btrfs_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t rdev) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(dir)->root; struct inode *inode = NULL; int err; int drop_inode = 0; u64 objectid; u64 index = 0; if (!new_valid_dev(rdev)) return -EINVAL; /* * 2 for inode item and ref * 2 for dir items * 1 for xattr if selinux is on */ trans = btrfs_start_transaction(root, 5); if (IS_ERR(trans)) return PTR_ERR(trans); err = btrfs_find_free_ino(root, &objectid); if (err) goto out_unlock; inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name, dentry->d_name.len, btrfs_ino(dir), objectid, mode, &index); if (IS_ERR(inode)) { err = PTR_ERR(inode); goto out_unlock; } err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name); if (err) { drop_inode = 1; goto out_unlock; } err = btrfs_update_inode(trans, root, inode); if (err) { drop_inode = 1; goto out_unlock; } /* * If the active LSM wants to access the inode during * d_instantiate it needs these. Smack checks to see * if the filesystem supports xattrs by looking at the * ops vector. */ inode->i_op = &btrfs_special_inode_operations; err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index); if (err) drop_inode = 1; else { init_special_inode(inode, inode->i_mode, rdev); btrfs_update_inode(trans, root, inode); d_instantiate(dentry, inode); } out_unlock: btrfs_end_transaction(trans, root); btrfs_btree_balance_dirty(root); if (drop_inode) { inode_dec_link_count(inode); iput(inode); } return err; } static int btrfs_create(struct inode *dir, struct dentry *dentry, umode_t mode, bool excl) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(dir)->root; struct inode *inode = NULL; int drop_inode_on_err = 0; int err; u64 objectid; u64 index = 0; /* * 2 for inode item and ref * 2 for dir items * 1 for xattr if selinux is on */ trans = btrfs_start_transaction(root, 5); if (IS_ERR(trans)) return PTR_ERR(trans); err = btrfs_find_free_ino(root, &objectid); if (err) goto out_unlock; inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name, dentry->d_name.len, btrfs_ino(dir), objectid, mode, &index); if (IS_ERR(inode)) { err = PTR_ERR(inode); goto out_unlock; } drop_inode_on_err = 1; err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name); if (err) goto out_unlock; err = btrfs_update_inode(trans, root, inode); if (err) goto out_unlock; /* * If the active LSM wants to access the inode during * d_instantiate it needs these. Smack checks to see * if the filesystem supports xattrs by looking at the * ops vector. */ inode->i_fop = &btrfs_file_operations; inode->i_op = &btrfs_file_inode_operations; err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index); if (err) goto out_unlock; inode->i_mapping->a_ops = &btrfs_aops; inode->i_mapping->backing_dev_info = &root->fs_info->bdi; BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops; d_instantiate(dentry, inode); out_unlock: btrfs_end_transaction(trans, root); if (err && drop_inode_on_err) { inode_dec_link_count(inode); iput(inode); } btrfs_btree_balance_dirty(root); return err; } static int btrfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(dir)->root; struct inode *inode = old_dentry->d_inode; u64 index; int err; int drop_inode = 0; /* do not allow sys_link's with other subvols of the same device */ if (root->objectid != BTRFS_I(inode)->root->objectid) return -EXDEV; if (inode->i_nlink >= BTRFS_LINK_MAX) return -EMLINK; err = btrfs_set_inode_index(dir, &index); if (err) goto fail; /* * 2 items for inode and inode ref * 2 items for dir items * 1 item for parent inode */ trans = btrfs_start_transaction(root, 5); if (IS_ERR(trans)) { err = PTR_ERR(trans); goto fail; } btrfs_inc_nlink(inode); inode_inc_iversion(inode); inode->i_ctime = CURRENT_TIME; ihold(inode); set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags); err = btrfs_add_nondir(trans, dir, dentry, inode, 1, index); if (err) { drop_inode = 1; } else { struct dentry *parent = dentry->d_parent; err = btrfs_update_inode(trans, root, inode); if (err) goto fail; d_instantiate(dentry, inode); btrfs_log_new_name(trans, inode, NULL, parent); } btrfs_end_transaction(trans, root); fail: if (drop_inode) { inode_dec_link_count(inode); iput(inode); } btrfs_btree_balance_dirty(root); return err; } static int btrfs_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode) { struct inode *inode = NULL; struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(dir)->root; int err = 0; int drop_on_err = 0; u64 objectid = 0; u64 index = 0; /* * 2 items for inode and ref * 2 items for dir items * 1 for xattr if selinux is on */ trans = btrfs_start_transaction(root, 5); if (IS_ERR(trans)) return PTR_ERR(trans); err = btrfs_find_free_ino(root, &objectid); if (err) goto out_fail; inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name, dentry->d_name.len, btrfs_ino(dir), objectid, S_IFDIR | mode, &index); if (IS_ERR(inode)) { err = PTR_ERR(inode); goto out_fail; } drop_on_err = 1; err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name); if (err) goto out_fail; inode->i_op = &btrfs_dir_inode_operations; inode->i_fop = &btrfs_dir_file_operations; btrfs_i_size_write(inode, 0); err = btrfs_update_inode(trans, root, inode); if (err) goto out_fail; err = btrfs_add_link(trans, dir, inode, dentry->d_name.name, dentry->d_name.len, 0, index); if (err) goto out_fail; d_instantiate(dentry, inode); drop_on_err = 0; out_fail: btrfs_end_transaction(trans, root); if (drop_on_err) iput(inode); btrfs_btree_balance_dirty(root); return err; } /* helper for btfs_get_extent. Given an existing extent in the tree, * and an extent that you want to insert, deal with overlap and insert * the new extent into the tree. */ static int merge_extent_mapping(struct extent_map_tree *em_tree, struct extent_map *existing, struct extent_map *em, u64 map_start, u64 map_len) { u64 start_diff; BUG_ON(map_start < em->start || map_start >= extent_map_end(em)); start_diff = map_start - em->start; em->start = map_start; em->len = map_len; if (em->block_start < EXTENT_MAP_LAST_BYTE && !test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) { em->block_start += start_diff; em->block_len -= start_diff; } return add_extent_mapping(em_tree, em); } static noinline int uncompress_inline(struct btrfs_path *path, struct inode *inode, struct page *page, size_t pg_offset, u64 extent_offset, struct btrfs_file_extent_item *item) { int ret; struct extent_buffer *leaf = path->nodes[0]; char *tmp; size_t max_size; unsigned long inline_size; unsigned long ptr; int compress_type; WARN_ON(pg_offset != 0); compress_type = btrfs_file_extent_compression(leaf, item); max_size = btrfs_file_extent_ram_bytes(leaf, item); inline_size = btrfs_file_extent_inline_item_len(leaf, btrfs_item_nr(leaf, path->slots[0])); tmp = kmalloc(inline_size, GFP_NOFS); if (!tmp) return -ENOMEM; ptr = btrfs_file_extent_inline_start(item); read_extent_buffer(leaf, tmp, ptr, inline_size); max_size = min_t(unsigned long, PAGE_CACHE_SIZE, max_size); ret = btrfs_decompress(compress_type, tmp, page, extent_offset, inline_size, max_size); if (ret) { char *kaddr = kmap_atomic(page); unsigned long copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset, max_size - extent_offset); memset(kaddr + pg_offset, 0, copy_size); kunmap_atomic(kaddr); } kfree(tmp); return 0; } /* * a bit scary, this does extent mapping from logical file offset to the disk. * the ugly parts come from merging extents from the disk with the in-ram * representation. This gets more complex because of the data=ordered code, * where the in-ram extents might be locked pending data=ordered completion. * * This also copies inline extents directly into the page. */ struct extent_map *btrfs_get_extent(struct inode *inode, struct page *page, size_t pg_offset, u64 start, u64 len, int create) { int ret; int err = 0; u64 bytenr; u64 extent_start = 0; u64 extent_end = 0; u64 objectid = btrfs_ino(inode); u32 found_type; struct btrfs_path *path = NULL; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_file_extent_item *item; struct extent_buffer *leaf; struct btrfs_key found_key; struct extent_map *em = NULL; struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct btrfs_trans_handle *trans = NULL; int compress_type; again: read_lock(&em_tree->lock); em = lookup_extent_mapping(em_tree, start, len); if (em) em->bdev = root->fs_info->fs_devices->latest_bdev; read_unlock(&em_tree->lock); if (em) { if (em->start > start || em->start + em->len <= start) free_extent_map(em); else if (em->block_start == EXTENT_MAP_INLINE && page) free_extent_map(em); else goto out; } em = alloc_extent_map(); if (!em) { err = -ENOMEM; goto out; } em->bdev = root->fs_info->fs_devices->latest_bdev; em->start = EXTENT_MAP_HOLE; em->orig_start = EXTENT_MAP_HOLE; em->len = (u64)-1; em->block_len = (u64)-1; if (!path) { path = btrfs_alloc_path(); if (!path) { err = -ENOMEM; goto out; } /* * Chances are we'll be called again, so go ahead and do * readahead */ path->reada = 1; } ret = btrfs_lookup_file_extent(trans, root, path, objectid, start, trans != NULL); if (ret < 0) { err = ret; goto out; } if (ret != 0) { if (path->slots[0] == 0) goto not_found; path->slots[0]--; } leaf = path->nodes[0]; item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); /* are we inside the extent that was found? */ btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); found_type = btrfs_key_type(&found_key); if (found_key.objectid != objectid || found_type != BTRFS_EXTENT_DATA_KEY) { goto not_found; } found_type = btrfs_file_extent_type(leaf, item); extent_start = found_key.offset; compress_type = btrfs_file_extent_compression(leaf, item); if (found_type == BTRFS_FILE_EXTENT_REG || found_type == BTRFS_FILE_EXTENT_PREALLOC) { extent_end = extent_start + btrfs_file_extent_num_bytes(leaf, item); } else if (found_type == BTRFS_FILE_EXTENT_INLINE) { size_t size; size = btrfs_file_extent_inline_len(leaf, item); extent_end = (extent_start + size + root->sectorsize - 1) & ~((u64)root->sectorsize - 1); } if (start >= extent_end) { path->slots[0]++; if (path->slots[0] >= btrfs_header_nritems(leaf)) { ret = btrfs_next_leaf(root, path); if (ret < 0) { err = ret; goto out; } if (ret > 0) goto not_found; leaf = path->nodes[0]; } btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]); if (found_key.objectid != objectid || found_key.type != BTRFS_EXTENT_DATA_KEY) goto not_found; if (start + len <= found_key.offset) goto not_found; em->start = start; em->orig_start = start; em->len = found_key.offset - start; goto not_found_em; } if (found_type == BTRFS_FILE_EXTENT_REG || found_type == BTRFS_FILE_EXTENT_PREALLOC) { em->start = extent_start; em->len = extent_end - extent_start; em->orig_start = extent_start - btrfs_file_extent_offset(leaf, item); em->orig_block_len = btrfs_file_extent_disk_num_bytes(leaf, item); bytenr = btrfs_file_extent_disk_bytenr(leaf, item); if (bytenr == 0) { em->block_start = EXTENT_MAP_HOLE; goto insert; } if (compress_type != BTRFS_COMPRESS_NONE) { set_bit(EXTENT_FLAG_COMPRESSED, &em->flags); em->compress_type = compress_type; em->block_start = bytenr; em->block_len = em->orig_block_len; } else { bytenr += btrfs_file_extent_offset(leaf, item); em->block_start = bytenr; em->block_len = em->len; if (found_type == BTRFS_FILE_EXTENT_PREALLOC) set_bit(EXTENT_FLAG_PREALLOC, &em->flags); } goto insert; } else if (found_type == BTRFS_FILE_EXTENT_INLINE) { unsigned long ptr; char *map; size_t size; size_t extent_offset; size_t copy_size; em->block_start = EXTENT_MAP_INLINE; if (!page || create) { em->start = extent_start; em->len = extent_end - extent_start; goto out; } size = btrfs_file_extent_inline_len(leaf, item); extent_offset = page_offset(page) + pg_offset - extent_start; copy_size = min_t(u64, PAGE_CACHE_SIZE - pg_offset, size - extent_offset); em->start = extent_start + extent_offset; em->len = (copy_size + root->sectorsize - 1) & ~((u64)root->sectorsize - 1); em->orig_block_len = em->len; em->orig_start = em->start; if (compress_type) { set_bit(EXTENT_FLAG_COMPRESSED, &em->flags); em->compress_type = compress_type; } ptr = btrfs_file_extent_inline_start(item) + extent_offset; if (create == 0 && !PageUptodate(page)) { if (btrfs_file_extent_compression(leaf, item) != BTRFS_COMPRESS_NONE) { ret = uncompress_inline(path, inode, page, pg_offset, extent_offset, item); BUG_ON(ret); /* -ENOMEM */ } else { map = kmap(page); read_extent_buffer(leaf, map + pg_offset, ptr, copy_size); if (pg_offset + copy_size < PAGE_CACHE_SIZE) { memset(map + pg_offset + copy_size, 0, PAGE_CACHE_SIZE - pg_offset - copy_size); } kunmap(page); } flush_dcache_page(page); } else if (create && PageUptodate(page)) { BUG(); if (!trans) { kunmap(page); free_extent_map(em); em = NULL; btrfs_release_path(path); trans = btrfs_join_transaction(root); if (IS_ERR(trans)) return ERR_CAST(trans); goto again; } map = kmap(page); write_extent_buffer(leaf, map + pg_offset, ptr, copy_size); kunmap(page); btrfs_mark_buffer_dirty(leaf); } set_extent_uptodate(io_tree, em->start, extent_map_end(em) - 1, NULL, GFP_NOFS); goto insert; } else { WARN(1, KERN_ERR "btrfs unknown found_type %d\n", found_type); } not_found: em->start = start; em->orig_start = start; em->len = len; not_found_em: em->block_start = EXTENT_MAP_HOLE; set_bit(EXTENT_FLAG_VACANCY, &em->flags); insert: btrfs_release_path(path); if (em->start > start || extent_map_end(em) <= start) { printk(KERN_ERR "Btrfs: bad extent! em: [%llu %llu] passed " "[%llu %llu]\n", (unsigned long long)em->start, (unsigned long long)em->len, (unsigned long long)start, (unsigned long long)len); err = -EIO; goto out; } err = 0; write_lock(&em_tree->lock); ret = add_extent_mapping(em_tree, em); /* it is possible that someone inserted the extent into the tree * while we had the lock dropped. It is also possible that * an overlapping map exists in the tree */ if (ret == -EEXIST) { struct extent_map *existing; ret = 0; existing = lookup_extent_mapping(em_tree, start, len); if (existing && (existing->start > start || existing->start + existing->len <= start)) { free_extent_map(existing); existing = NULL; } if (!existing) { existing = lookup_extent_mapping(em_tree, em->start, em->len); if (existing) { err = merge_extent_mapping(em_tree, existing, em, start, root->sectorsize); free_extent_map(existing); if (err) { free_extent_map(em); em = NULL; } } else { err = -EIO; free_extent_map(em); em = NULL; } } else { free_extent_map(em); em = existing; err = 0; } } write_unlock(&em_tree->lock); out: if (em) trace_btrfs_get_extent(root, em); if (path) btrfs_free_path(path); if (trans) { ret = btrfs_end_transaction(trans, root); if (!err) err = ret; } if (err) { free_extent_map(em); return ERR_PTR(err); } BUG_ON(!em); /* Error is always set */ return em; } struct extent_map *btrfs_get_extent_fiemap(struct inode *inode, struct page *page, size_t pg_offset, u64 start, u64 len, int create) { struct extent_map *em; struct extent_map *hole_em = NULL; u64 range_start = start; u64 end; u64 found; u64 found_end; int err = 0; em = btrfs_get_extent(inode, page, pg_offset, start, len, create); if (IS_ERR(em)) return em; if (em) { /* * if our em maps to a hole, there might * actually be delalloc bytes behind it */ if (em->block_start != EXTENT_MAP_HOLE) return em; else hole_em = em; } /* check to see if we've wrapped (len == -1 or similar) */ end = start + len; if (end < start) end = (u64)-1; else end -= 1; em = NULL; /* ok, we didn't find anything, lets look for delalloc */ found = count_range_bits(&BTRFS_I(inode)->io_tree, &range_start, end, len, EXTENT_DELALLOC, 1); found_end = range_start + found; if (found_end < range_start) found_end = (u64)-1; /* * we didn't find anything useful, return * the original results from get_extent() */ if (range_start > end || found_end <= start) { em = hole_em; hole_em = NULL; goto out; } /* adjust the range_start to make sure it doesn't * go backwards from the start they passed in */ range_start = max(start,range_start); found = found_end - range_start; if (found > 0) { u64 hole_start = start; u64 hole_len = len; em = alloc_extent_map(); if (!em) { err = -ENOMEM; goto out; } /* * when btrfs_get_extent can't find anything it * returns one huge hole * * make sure what it found really fits our range, and * adjust to make sure it is based on the start from * the caller */ if (hole_em) { u64 calc_end = extent_map_end(hole_em); if (calc_end <= start || (hole_em->start > end)) { free_extent_map(hole_em); hole_em = NULL; } else { hole_start = max(hole_em->start, start); hole_len = calc_end - hole_start; } } em->bdev = NULL; if (hole_em && range_start > hole_start) { /* our hole starts before our delalloc, so we * have to return just the parts of the hole * that go until the delalloc starts */ em->len = min(hole_len, range_start - hole_start); em->start = hole_start; em->orig_start = hole_start; /* * don't adjust block start at all, * it is fixed at EXTENT_MAP_HOLE */ em->block_start = hole_em->block_start; em->block_len = hole_len; } else { em->start = range_start; em->len = found; em->orig_start = range_start; em->block_start = EXTENT_MAP_DELALLOC; em->block_len = found; } } else if (hole_em) { return hole_em; } out: free_extent_map(hole_em); if (err) { free_extent_map(em); return ERR_PTR(err); } return em; } static struct extent_map *btrfs_new_extent_direct(struct inode *inode, u64 start, u64 len) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_trans_handle *trans; struct extent_map *em; struct btrfs_key ins; u64 alloc_hint; int ret; trans = btrfs_join_transaction(root); if (IS_ERR(trans)) return ERR_CAST(trans); trans->block_rsv = &root->fs_info->delalloc_block_rsv; alloc_hint = get_extent_allocation_hint(inode, start, len); ret = btrfs_reserve_extent(trans, root, len, root->sectorsize, 0, alloc_hint, &ins, 1); if (ret) { em = ERR_PTR(ret); goto out; } em = create_pinned_em(inode, start, ins.offset, start, ins.objectid, ins.offset, ins.offset, 0); if (IS_ERR(em)) goto out; ret = btrfs_add_ordered_extent_dio(inode, start, ins.objectid, ins.offset, ins.offset, 0); if (ret) { btrfs_free_reserved_extent(root, ins.objectid, ins.offset); em = ERR_PTR(ret); } out: btrfs_end_transaction(trans, root); return em; } /* * returns 1 when the nocow is safe, < 1 on error, 0 if the * block must be cow'd */ static noinline int can_nocow_odirect(struct btrfs_trans_handle *trans, struct inode *inode, u64 offset, u64 len) { struct btrfs_path *path; int ret; struct extent_buffer *leaf; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_file_extent_item *fi; struct btrfs_key key; u64 disk_bytenr; u64 backref_offset; u64 extent_end; u64 num_bytes; int slot; int found_type; path = btrfs_alloc_path(); if (!path) return -ENOMEM; ret = btrfs_lookup_file_extent(trans, root, path, btrfs_ino(inode), offset, 0); if (ret < 0) goto out; slot = path->slots[0]; if (ret == 1) { if (slot == 0) { /* can't find the item, must cow */ ret = 0; goto out; } slot--; } ret = 0; leaf = path->nodes[0]; btrfs_item_key_to_cpu(leaf, &key, slot); if (key.objectid != btrfs_ino(inode) || key.type != BTRFS_EXTENT_DATA_KEY) { /* not our file or wrong item type, must cow */ goto out; } if (key.offset > offset) { /* Wrong offset, must cow */ goto out; } fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item); found_type = btrfs_file_extent_type(leaf, fi); if (found_type != BTRFS_FILE_EXTENT_REG && found_type != BTRFS_FILE_EXTENT_PREALLOC) { /* not a regular extent, must cow */ goto out; } disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi); backref_offset = btrfs_file_extent_offset(leaf, fi); extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi); if (extent_end < offset + len) { /* extent doesn't include our full range, must cow */ goto out; } if (btrfs_extent_readonly(root, disk_bytenr)) goto out; /* * look for other files referencing this extent, if we * find any we must cow */ if (btrfs_cross_ref_exist(trans, root, btrfs_ino(inode), key.offset - backref_offset, disk_bytenr)) goto out; /* * adjust disk_bytenr and num_bytes to cover just the bytes * in this extent we are about to write. If there * are any csums in that range we have to cow in order * to keep the csums correct */ disk_bytenr += backref_offset; disk_bytenr += offset - key.offset; num_bytes = min(offset + len, extent_end) - offset; if (csum_exist_in_range(root, disk_bytenr, num_bytes)) goto out; /* * all of the above have passed, it is safe to overwrite this extent * without cow */ ret = 1; out: btrfs_free_path(path); return ret; } static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend, struct extent_state **cached_state, int writing) { struct btrfs_ordered_extent *ordered; int ret = 0; while (1) { lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend, 0, cached_state); /* * We're concerned with the entire range that we're going to be * doing DIO to, so we need to make sure theres no ordered * extents in this range. */ ordered = btrfs_lookup_ordered_range(inode, lockstart, lockend - lockstart + 1); /* * We need to make sure there are no buffered pages in this * range either, we could have raced between the invalidate in * generic_file_direct_write and locking the extent. The * invalidate needs to happen so that reads after a write do not * get stale data. */ if (!ordered && (!writing || !test_range_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend, EXTENT_UPTODATE, 0, *cached_state))) break; unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend, cached_state, GFP_NOFS); if (ordered) { btrfs_start_ordered_extent(inode, ordered, 1); btrfs_put_ordered_extent(ordered); } else { /* Screw you mmap */ ret = filemap_write_and_wait_range(inode->i_mapping, lockstart, lockend); if (ret) break; /* * If we found a page that couldn't be invalidated just * fall back to buffered. */ ret = invalidate_inode_pages2_range(inode->i_mapping, lockstart >> PAGE_CACHE_SHIFT, lockend >> PAGE_CACHE_SHIFT); if (ret) break; } cond_resched(); } return ret; } static struct extent_map *create_pinned_em(struct inode *inode, u64 start, u64 len, u64 orig_start, u64 block_start, u64 block_len, u64 orig_block_len, int type) { struct extent_map_tree *em_tree; struct extent_map *em; struct btrfs_root *root = BTRFS_I(inode)->root; int ret; em_tree = &BTRFS_I(inode)->extent_tree; em = alloc_extent_map(); if (!em) return ERR_PTR(-ENOMEM); em->start = start; em->orig_start = orig_start; em->len = len; em->block_len = block_len; em->block_start = block_start; em->bdev = root->fs_info->fs_devices->latest_bdev; em->orig_block_len = orig_block_len; em->generation = -1; set_bit(EXTENT_FLAG_PINNED, &em->flags); if (type == BTRFS_ORDERED_PREALLOC) set_bit(EXTENT_FLAG_FILLING, &em->flags); do { btrfs_drop_extent_cache(inode, em->start, em->start + em->len - 1, 0); write_lock(&em_tree->lock); ret = add_extent_mapping(em_tree, em); if (!ret) list_move(&em->list, &em_tree->modified_extents); write_unlock(&em_tree->lock); } while (ret == -EEXIST); if (ret) { free_extent_map(em); return ERR_PTR(ret); } return em; } static int btrfs_get_blocks_direct(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create) { struct extent_map *em; struct btrfs_root *root = BTRFS_I(inode)->root; struct extent_state *cached_state = NULL; u64 start = iblock << inode->i_blkbits; u64 lockstart, lockend; u64 len = bh_result->b_size; struct btrfs_trans_handle *trans; int unlock_bits = EXTENT_LOCKED; int ret; if (create) { ret = btrfs_delalloc_reserve_space(inode, len); if (ret) return ret; unlock_bits |= EXTENT_DELALLOC | EXTENT_DIRTY; } else { len = min_t(u64, len, root->sectorsize); } lockstart = start; lockend = start + len - 1; /* * If this errors out it's because we couldn't invalidate pagecache for * this range and we need to fallback to buffered. */ if (lock_extent_direct(inode, lockstart, lockend, &cached_state, create)) return -ENOTBLK; if (create) { ret = set_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend, EXTENT_DELALLOC, NULL, &cached_state, GFP_NOFS); if (ret) goto unlock_err; } em = btrfs_get_extent(inode, NULL, 0, start, len, 0); if (IS_ERR(em)) { ret = PTR_ERR(em); goto unlock_err; } /* * Ok for INLINE and COMPRESSED extents we need to fallback on buffered * io. INLINE is special, and we could probably kludge it in here, but * it's still buffered so for safety lets just fall back to the generic * buffered path. * * For COMPRESSED we _have_ to read the entire extent in so we can * decompress it, so there will be buffering required no matter what we * do, so go ahead and fallback to buffered. * * We return -ENOTBLK because thats what makes DIO go ahead and go back * to buffered IO. Don't blame me, this is the price we pay for using * the generic code. */ if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) || em->block_start == EXTENT_MAP_INLINE) { free_extent_map(em); ret = -ENOTBLK; goto unlock_err; } /* Just a good old fashioned hole, return */ if (!create && (em->block_start == EXTENT_MAP_HOLE || test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) { free_extent_map(em); ret = 0; goto unlock_err; } /* * We don't allocate a new extent in the following cases * * 1) The inode is marked as NODATACOW. In this case we'll just use the * existing extent. * 2) The extent is marked as PREALLOC. We're good to go here and can * just use the extent. * */ if (!create) { len = min(len, em->len - (start - em->start)); lockstart = start + len; goto unlock; } if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) || ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) && em->block_start != EXTENT_MAP_HOLE)) { int type; int ret; u64 block_start; if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) type = BTRFS_ORDERED_PREALLOC; else type = BTRFS_ORDERED_NOCOW; len = min(len, em->len - (start - em->start)); block_start = em->block_start + (start - em->start); /* * we're not going to log anything, but we do need * to make sure the current transaction stays open * while we look for nocow cross refs */ trans = btrfs_join_transaction(root); if (IS_ERR(trans)) goto must_cow; if (can_nocow_odirect(trans, inode, start, len) == 1) { u64 orig_start = em->orig_start; u64 orig_block_len = em->orig_block_len; if (type == BTRFS_ORDERED_PREALLOC) { free_extent_map(em); em = create_pinned_em(inode, start, len, orig_start, block_start, len, orig_block_len, type); if (IS_ERR(em)) { btrfs_end_transaction(trans, root); goto unlock_err; } } ret = btrfs_add_ordered_extent_dio(inode, start, block_start, len, len, type); btrfs_end_transaction(trans, root); if (ret) { free_extent_map(em); goto unlock_err; } goto unlock; } btrfs_end_transaction(trans, root); } must_cow: /* * this will cow the extent, reset the len in case we changed * it above */ len = bh_result->b_size; free_extent_map(em); em = btrfs_new_extent_direct(inode, start, len); if (IS_ERR(em)) { ret = PTR_ERR(em); goto unlock_err; } len = min(len, em->len - (start - em->start)); unlock: bh_result->b_blocknr = (em->block_start + (start - em->start)) >> inode->i_blkbits; bh_result->b_size = len; bh_result->b_bdev = em->bdev; set_buffer_mapped(bh_result); if (create) { if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) set_buffer_new(bh_result); /* * Need to update the i_size under the extent lock so buffered * readers will get the updated i_size when we unlock. */ if (start + len > i_size_read(inode)) i_size_write(inode, start + len); } /* * In the case of write we need to clear and unlock the entire range, * in the case of read we need to unlock only the end area that we * aren't using if there is any left over space. */ if (lockstart < lockend) { if (create && len < lockend - lockstart) { clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockstart + len - 1, unlock_bits | EXTENT_DEFRAG, 1, 0, &cached_state, GFP_NOFS); /* * Beside unlock, we also need to cleanup reserved space * for the left range by attaching EXTENT_DO_ACCOUNTING. */ clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart + len, lockend, unlock_bits | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 0, NULL, GFP_NOFS); } else { clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend, unlock_bits, 1, 0, &cached_state, GFP_NOFS); } } else { free_extent_state(cached_state); } free_extent_map(em); return 0; unlock_err: if (create) unlock_bits |= EXTENT_DO_ACCOUNTING; clear_extent_bit(&BTRFS_I(inode)->io_tree, lockstart, lockend, unlock_bits, 1, 0, &cached_state, GFP_NOFS); return ret; } struct btrfs_dio_private { struct inode *inode; u64 logical_offset; u64 disk_bytenr; u64 bytes; void *private; /* number of bios pending for this dio */ atomic_t pending_bios; /* IO errors */ int errors; struct bio *orig_bio; }; static void btrfs_endio_direct_read(struct bio *bio, int err) { struct btrfs_dio_private *dip = bio->bi_private; struct bio_vec *bvec_end = bio->bi_io_vec + bio->bi_vcnt - 1; struct bio_vec *bvec = bio->bi_io_vec; struct inode *inode = dip->inode; struct btrfs_root *root = BTRFS_I(inode)->root; u64 start; start = dip->logical_offset; do { if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) { struct page *page = bvec->bv_page; char *kaddr; u32 csum = ~(u32)0; u64 private = ~(u32)0; unsigned long flags; if (get_state_private(&BTRFS_I(inode)->io_tree, start, &private)) goto failed; local_irq_save(flags); kaddr = kmap_atomic(page); csum = btrfs_csum_data(root, kaddr + bvec->bv_offset, csum, bvec->bv_len); btrfs_csum_final(csum, (char *)&csum); kunmap_atomic(kaddr); local_irq_restore(flags); flush_dcache_page(bvec->bv_page); if (csum != private) { failed: printk(KERN_ERR "btrfs csum failed ino %llu off" " %llu csum %u private %u\n", (unsigned long long)btrfs_ino(inode), (unsigned long long)start, csum, (unsigned)private); err = -EIO; } } start += bvec->bv_len; bvec++; } while (bvec <= bvec_end); unlock_extent(&BTRFS_I(inode)->io_tree, dip->logical_offset, dip->logical_offset + dip->bytes - 1); bio->bi_private = dip->private; kfree(dip); /* If we had a csum failure make sure to clear the uptodate flag */ if (err) clear_bit(BIO_UPTODATE, &bio->bi_flags); dio_end_io(bio, err); } static void btrfs_endio_direct_write(struct bio *bio, int err) { struct btrfs_dio_private *dip = bio->bi_private; struct inode *inode = dip->inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_ordered_extent *ordered = NULL; u64 ordered_offset = dip->logical_offset; u64 ordered_bytes = dip->bytes; int ret; if (err) goto out_done; again: ret = btrfs_dec_test_first_ordered_pending(inode, &ordered, &ordered_offset, ordered_bytes, !err); if (!ret) goto out_test; ordered->work.func = finish_ordered_fn; ordered->work.flags = 0; btrfs_queue_worker(&root->fs_info->endio_write_workers, &ordered->work); out_test: /* * our bio might span multiple ordered extents. If we haven't * completed the accounting for the whole dio, go back and try again */ if (ordered_offset < dip->logical_offset + dip->bytes) { ordered_bytes = dip->logical_offset + dip->bytes - ordered_offset; ordered = NULL; goto again; } out_done: bio->bi_private = dip->private; kfree(dip); /* If we had an error make sure to clear the uptodate flag */ if (err) clear_bit(BIO_UPTODATE, &bio->bi_flags); dio_end_io(bio, err); } static int __btrfs_submit_bio_start_direct_io(struct inode *inode, int rw, struct bio *bio, int mirror_num, unsigned long bio_flags, u64 offset) { int ret; struct btrfs_root *root = BTRFS_I(inode)->root; ret = btrfs_csum_one_bio(root, inode, bio, offset, 1); BUG_ON(ret); /* -ENOMEM */ return 0; } static void btrfs_end_dio_bio(struct bio *bio, int err) { struct btrfs_dio_private *dip = bio->bi_private; if (err) { printk(KERN_ERR "btrfs direct IO failed ino %llu rw %lu " "sector %#Lx len %u err no %d\n", (unsigned long long)btrfs_ino(dip->inode), bio->bi_rw, (unsigned long long)bio->bi_sector, bio->bi_size, err); dip->errors = 1; /* * before atomic variable goto zero, we must make sure * dip->errors is perceived to be set. */ smp_mb__before_atomic_dec(); } /* if there are more bios still pending for this dio, just exit */ if (!atomic_dec_and_test(&dip->pending_bios)) goto out; if (dip->errors) bio_io_error(dip->orig_bio); else { set_bit(BIO_UPTODATE, &dip->orig_bio->bi_flags); bio_endio(dip->orig_bio, 0); } out: bio_put(bio); } static struct bio *btrfs_dio_bio_alloc(struct block_device *bdev, u64 first_sector, gfp_t gfp_flags) { int nr_vecs = bio_get_nr_vecs(bdev); return btrfs_bio_alloc(bdev, first_sector, nr_vecs, gfp_flags); } static inline int __btrfs_submit_dio_bio(struct bio *bio, struct inode *inode, int rw, u64 file_offset, int skip_sum, int async_submit) { int write = rw & REQ_WRITE; struct btrfs_root *root = BTRFS_I(inode)->root; int ret; if (async_submit) async_submit = !atomic_read(&BTRFS_I(inode)->sync_writers); bio_get(bio); if (!write) { ret = btrfs_bio_wq_end_io(root->fs_info, bio, 0); if (ret) goto err; } if (skip_sum) goto map; if (write && async_submit) { ret = btrfs_wq_submit_bio(root->fs_info, inode, rw, bio, 0, 0, file_offset, __btrfs_submit_bio_start_direct_io, __btrfs_submit_bio_done); goto err; } else if (write) { /* * If we aren't doing async submit, calculate the csum of the * bio now. */ ret = btrfs_csum_one_bio(root, inode, bio, file_offset, 1); if (ret) goto err; } else if (!skip_sum) { ret = btrfs_lookup_bio_sums_dio(root, inode, bio, file_offset); if (ret) goto err; } map: ret = btrfs_map_bio(root, rw, bio, 0, async_submit); err: bio_put(bio); return ret; } static int btrfs_submit_direct_hook(int rw, struct btrfs_dio_private *dip, int skip_sum) { struct inode *inode = dip->inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct bio *bio; struct bio *orig_bio = dip->orig_bio; struct bio_vec *bvec = orig_bio->bi_io_vec; u64 start_sector = orig_bio->bi_sector; u64 file_offset = dip->logical_offset; u64 submit_len = 0; u64 map_length; int nr_pages = 0; int ret = 0; int async_submit = 0; map_length = orig_bio->bi_size; ret = btrfs_map_block(root->fs_info, READ, start_sector << 9, &map_length, NULL, 0); if (ret) { bio_put(orig_bio); return -EIO; } if (map_length >= orig_bio->bi_size) { bio = orig_bio; goto submit; } async_submit = 1; bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS); if (!bio) return -ENOMEM; bio->bi_private = dip; bio->bi_end_io = btrfs_end_dio_bio; atomic_inc(&dip->pending_bios); while (bvec <= (orig_bio->bi_io_vec + orig_bio->bi_vcnt - 1)) { if (unlikely(map_length < submit_len + bvec->bv_len || bio_add_page(bio, bvec->bv_page, bvec->bv_len, bvec->bv_offset) < bvec->bv_len)) { /* * inc the count before we submit the bio so * we know the end IO handler won't happen before * we inc the count. Otherwise, the dip might get freed * before we're done setting it up */ atomic_inc(&dip->pending_bios); ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum, async_submit); if (ret) { bio_put(bio); atomic_dec(&dip->pending_bios); goto out_err; } start_sector += submit_len >> 9; file_offset += submit_len; submit_len = 0; nr_pages = 0; bio = btrfs_dio_bio_alloc(orig_bio->bi_bdev, start_sector, GFP_NOFS); if (!bio) goto out_err; bio->bi_private = dip; bio->bi_end_io = btrfs_end_dio_bio; map_length = orig_bio->bi_size; ret = btrfs_map_block(root->fs_info, READ, start_sector << 9, &map_length, NULL, 0); if (ret) { bio_put(bio); goto out_err; } } else { submit_len += bvec->bv_len; nr_pages ++; bvec++; } } submit: ret = __btrfs_submit_dio_bio(bio, inode, rw, file_offset, skip_sum, async_submit); if (!ret) return 0; bio_put(bio); out_err: dip->errors = 1; /* * before atomic variable goto zero, we must * make sure dip->errors is perceived to be set. */ smp_mb__before_atomic_dec(); if (atomic_dec_and_test(&dip->pending_bios)) bio_io_error(dip->orig_bio); /* bio_end_io() will handle error, so we needn't return it */ return 0; } static void btrfs_submit_direct(int rw, struct bio *bio, struct inode *inode, loff_t file_offset) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_dio_private *dip; struct bio_vec *bvec = bio->bi_io_vec; int skip_sum; int write = rw & REQ_WRITE; int ret = 0; skip_sum = BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM; dip = kmalloc(sizeof(*dip), GFP_NOFS); if (!dip) { ret = -ENOMEM; goto free_ordered; } dip->private = bio->bi_private; dip->inode = inode; dip->logical_offset = file_offset; dip->bytes = 0; do { dip->bytes += bvec->bv_len; bvec++; } while (bvec <= (bio->bi_io_vec + bio->bi_vcnt - 1)); dip->disk_bytenr = (u64)bio->bi_sector << 9; bio->bi_private = dip; dip->errors = 0; dip->orig_bio = bio; atomic_set(&dip->pending_bios, 0); if (write) bio->bi_end_io = btrfs_endio_direct_write; else bio->bi_end_io = btrfs_endio_direct_read; ret = btrfs_submit_direct_hook(rw, dip, skip_sum); if (!ret) return; free_ordered: /* * If this is a write, we need to clean up the reserved space and kill * the ordered extent. */ if (write) { struct btrfs_ordered_extent *ordered; ordered = btrfs_lookup_ordered_extent(inode, file_offset); if (!test_bit(BTRFS_ORDERED_PREALLOC, &ordered->flags) && !test_bit(BTRFS_ORDERED_NOCOW, &ordered->flags)) btrfs_free_reserved_extent(root, ordered->start, ordered->disk_len); btrfs_put_ordered_extent(ordered); btrfs_put_ordered_extent(ordered); } bio_endio(bio, ret); } static ssize_t check_direct_IO(struct btrfs_root *root, int rw, struct kiocb *iocb, const struct iovec *iov, loff_t offset, unsigned long nr_segs) { int seg; int i; size_t size; unsigned long addr; unsigned blocksize_mask = root->sectorsize - 1; ssize_t retval = -EINVAL; loff_t end = offset; if (offset & blocksize_mask) goto out; /* Check the memory alignment. Blocks cannot straddle pages */ for (seg = 0; seg < nr_segs; seg++) { addr = (unsigned long)iov[seg].iov_base; size = iov[seg].iov_len; end += size; if ((addr & blocksize_mask) || (size & blocksize_mask)) goto out; /* If this is a write we don't need to check anymore */ if (rw & WRITE) continue; /* * Check to make sure we don't have duplicate iov_base's in this * iovec, if so return EINVAL, otherwise we'll get csum errors * when reading back. */ for (i = seg + 1; i < nr_segs; i++) { if (iov[seg].iov_base == iov[i].iov_base) goto out; } } retval = 0; out: return retval; } static ssize_t btrfs_direct_IO(int rw, struct kiocb *iocb, const struct iovec *iov, loff_t offset, unsigned long nr_segs) { struct file *file = iocb->ki_filp; struct inode *inode = file->f_mapping->host; if (check_direct_IO(BTRFS_I(inode)->root, rw, iocb, iov, offset, nr_segs)) return 0; return __blockdev_direct_IO(rw, iocb, inode, BTRFS_I(inode)->root->fs_info->fs_devices->latest_bdev, iov, offset, nr_segs, btrfs_get_blocks_direct, NULL, btrfs_submit_direct, 0); } #define BTRFS_FIEMAP_FLAGS (FIEMAP_FLAG_SYNC) static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo, __u64 start, __u64 len) { int ret; ret = fiemap_check_flags(fieinfo, BTRFS_FIEMAP_FLAGS); if (ret) return ret; return extent_fiemap(inode, fieinfo, start, len, btrfs_get_extent_fiemap); } int btrfs_readpage(struct file *file, struct page *page) { struct extent_io_tree *tree; tree = &BTRFS_I(page->mapping->host)->io_tree; return extent_read_full_page(tree, page, btrfs_get_extent, 0); } static int btrfs_writepage(struct page *page, struct writeback_control *wbc) { struct extent_io_tree *tree; if (current->flags & PF_MEMALLOC) { redirty_page_for_writepage(wbc, page); unlock_page(page); return 0; } tree = &BTRFS_I(page->mapping->host)->io_tree; return extent_write_full_page(tree, page, btrfs_get_extent, wbc); } int btrfs_writepages(struct address_space *mapping, struct writeback_control *wbc) { struct extent_io_tree *tree; tree = &BTRFS_I(mapping->host)->io_tree; return extent_writepages(tree, mapping, btrfs_get_extent, wbc); } static int btrfs_readpages(struct file *file, struct address_space *mapping, struct list_head *pages, unsigned nr_pages) { struct extent_io_tree *tree; tree = &BTRFS_I(mapping->host)->io_tree; return extent_readpages(tree, mapping, pages, nr_pages, btrfs_get_extent); } static int __btrfs_releasepage(struct page *page, gfp_t gfp_flags) { struct extent_io_tree *tree; struct extent_map_tree *map; int ret; tree = &BTRFS_I(page->mapping->host)->io_tree; map = &BTRFS_I(page->mapping->host)->extent_tree; ret = try_release_extent_mapping(map, tree, page, gfp_flags); if (ret == 1) { ClearPagePrivate(page); set_page_private(page, 0); page_cache_release(page); } return ret; } static int btrfs_releasepage(struct page *page, gfp_t gfp_flags) { if (PageWriteback(page) || PageDirty(page)) return 0; return __btrfs_releasepage(page, gfp_flags & GFP_NOFS); } static void btrfs_invalidatepage(struct page *page, unsigned long offset) { struct inode *inode = page->mapping->host; struct extent_io_tree *tree; struct btrfs_ordered_extent *ordered; struct extent_state *cached_state = NULL; u64 page_start = page_offset(page); u64 page_end = page_start + PAGE_CACHE_SIZE - 1; /* * we have the page locked, so new writeback can't start, * and the dirty bit won't be cleared while we are here. * * Wait for IO on this page so that we can safely clear * the PagePrivate2 bit and do ordered accounting */ wait_on_page_writeback(page); tree = &BTRFS_I(inode)->io_tree; if (offset) { btrfs_releasepage(page, GFP_NOFS); return; } lock_extent_bits(tree, page_start, page_end, 0, &cached_state); ordered = btrfs_lookup_ordered_extent(inode, page_offset(page)); if (ordered) { /* * IO on this page will never be started, so we need * to account for any ordered extents now */ clear_extent_bit(tree, page_start, page_end, EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_LOCKED | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 0, &cached_state, GFP_NOFS); /* * whoever cleared the private bit is responsible * for the finish_ordered_io */ if (TestClearPagePrivate2(page) && btrfs_dec_test_ordered_pending(inode, &ordered, page_start, PAGE_CACHE_SIZE, 1)) { btrfs_finish_ordered_io(ordered); } btrfs_put_ordered_extent(ordered); cached_state = NULL; lock_extent_bits(tree, page_start, page_end, 0, &cached_state); } clear_extent_bit(tree, page_start, page_end, EXTENT_LOCKED | EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 1, 1, &cached_state, GFP_NOFS); __btrfs_releasepage(page, GFP_NOFS); ClearPageChecked(page); if (PagePrivate(page)) { ClearPagePrivate(page); set_page_private(page, 0); page_cache_release(page); } } /* * btrfs_page_mkwrite() is not allowed to change the file size as it gets * called from a page fault handler when a page is first dirtied. Hence we must * be careful to check for EOF conditions here. We set the page up correctly * for a written page which means we get ENOSPC checking when writing into * holes and correct delalloc and unwritten extent mapping on filesystems that * support these features. * * We are not allowed to take the i_mutex here so we have to play games to * protect against truncate races as the page could now be beyond EOF. Because * vmtruncate() writes the inode size before removing pages, once we have the * page lock we can determine safely if the page is beyond EOF. If it is not * beyond EOF, then the page is guaranteed safe against truncation until we * unlock the page. */ int btrfs_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { struct page *page = vmf->page; struct inode *inode = fdentry(vma->vm_file)->d_inode; struct btrfs_root *root = BTRFS_I(inode)->root; struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree; struct btrfs_ordered_extent *ordered; struct extent_state *cached_state = NULL; char *kaddr; unsigned long zero_start; loff_t size; int ret; int reserved = 0; u64 page_start; u64 page_end; sb_start_pagefault(inode->i_sb); ret = btrfs_delalloc_reserve_space(inode, PAGE_CACHE_SIZE); if (!ret) { ret = file_update_time(vma->vm_file); reserved = 1; } if (ret) { if (ret == -ENOMEM) ret = VM_FAULT_OOM; else /* -ENOSPC, -EIO, etc */ ret = VM_FAULT_SIGBUS; if (reserved) goto out; goto out_noreserve; } ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */ again: lock_page(page); size = i_size_read(inode); page_start = page_offset(page); page_end = page_start + PAGE_CACHE_SIZE - 1; if ((page->mapping != inode->i_mapping) || (page_start >= size)) { /* page got truncated out from underneath us */ goto out_unlock; } wait_on_page_writeback(page); lock_extent_bits(io_tree, page_start, page_end, 0, &cached_state); set_page_extent_mapped(page); /* * we can't set the delalloc bits if there are pending ordered * extents. Drop our locks and wait for them to finish */ ordered = btrfs_lookup_ordered_extent(inode, page_start); if (ordered) { unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS); unlock_page(page); btrfs_start_ordered_extent(inode, ordered, 1); btrfs_put_ordered_extent(ordered); goto again; } /* * XXX - page_mkwrite gets called every time the page is dirtied, even * if it was already dirty, so for space accounting reasons we need to * clear any delalloc bits for the range we are fixing to save. There * is probably a better way to do this, but for now keep consistent with * prepare_pages in the normal write path. */ clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, page_end, EXTENT_DIRTY | EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG, 0, 0, &cached_state, GFP_NOFS); ret = btrfs_set_extent_delalloc(inode, page_start, page_end, &cached_state); if (ret) { unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS); ret = VM_FAULT_SIGBUS; goto out_unlock; } ret = 0; /* page is wholly or partially inside EOF */ if (page_start + PAGE_CACHE_SIZE > size) zero_start = size & ~PAGE_CACHE_MASK; else zero_start = PAGE_CACHE_SIZE; if (zero_start != PAGE_CACHE_SIZE) { kaddr = kmap(page); memset(kaddr + zero_start, 0, PAGE_CACHE_SIZE - zero_start); flush_dcache_page(page); kunmap(page); } ClearPageChecked(page); set_page_dirty(page); SetPageUptodate(page); BTRFS_I(inode)->last_trans = root->fs_info->generation; BTRFS_I(inode)->last_sub_trans = BTRFS_I(inode)->root->log_transid; BTRFS_I(inode)->last_log_commit = BTRFS_I(inode)->root->last_log_commit; unlock_extent_cached(io_tree, page_start, page_end, &cached_state, GFP_NOFS); out_unlock: if (!ret) { sb_end_pagefault(inode->i_sb); return VM_FAULT_LOCKED; } unlock_page(page); out: btrfs_delalloc_release_space(inode, PAGE_CACHE_SIZE); out_noreserve: sb_end_pagefault(inode->i_sb); return ret; } static int btrfs_truncate(struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_block_rsv *rsv; int ret; int err = 0; struct btrfs_trans_handle *trans; u64 mask = root->sectorsize - 1; u64 min_size = btrfs_calc_trunc_metadata_size(root, 1); ret = btrfs_truncate_page(inode, inode->i_size, 0, 0); if (ret) return ret; btrfs_wait_ordered_range(inode, inode->i_size & (~mask), (u64)-1); btrfs_ordered_update_i_size(inode, inode->i_size, NULL); /* * Yes ladies and gentelment, this is indeed ugly. The fact is we have * 3 things going on here * * 1) We need to reserve space for our orphan item and the space to * delete our orphan item. Lord knows we don't want to have a dangling * orphan item because we didn't reserve space to remove it. * * 2) We need to reserve space to update our inode. * * 3) We need to have something to cache all the space that is going to * be free'd up by the truncate operation, but also have some slack * space reserved in case it uses space during the truncate (thank you * very much snapshotting). * * And we need these to all be seperate. The fact is we can use alot of * space doing the truncate, and we have no earthly idea how much space * we will use, so we need the truncate reservation to be seperate so it * doesn't end up using space reserved for updating the inode or * removing the orphan item. We also need to be able to stop the * transaction and start a new one, which means we need to be able to * update the inode several times, and we have no idea of knowing how * many times that will be, so we can't just reserve 1 item for the * entirety of the opration, so that has to be done seperately as well. * Then there is the orphan item, which does indeed need to be held on * to for the whole operation, and we need nobody to touch this reserved * space except the orphan code. * * So that leaves us with * * 1) root->orphan_block_rsv - for the orphan deletion. * 2) rsv - for the truncate reservation, which we will steal from the * transaction reservation. * 3) fs_info->trans_block_rsv - this will have 1 items worth left for * updating the inode. */ rsv = btrfs_alloc_block_rsv(root, BTRFS_BLOCK_RSV_TEMP); if (!rsv) return -ENOMEM; rsv->size = min_size; rsv->failfast = 1; /* * 1 for the truncate slack space * 1 for the orphan item we're going to add * 1 for the orphan item deletion * 1 for updating the inode. */ trans = btrfs_start_transaction(root, 4); if (IS_ERR(trans)) { err = PTR_ERR(trans); goto out; } /* Migrate the slack space for the truncate to our reserve */ ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv, min_size); BUG_ON(ret); ret = btrfs_orphan_add(trans, inode); if (ret) { btrfs_end_transaction(trans, root); goto out; } /* * setattr is responsible for setting the ordered_data_close flag, * but that is only tested during the last file release. That * could happen well after the next commit, leaving a great big * window where new writes may get lost if someone chooses to write * to this file after truncating to zero * * The inode doesn't have any dirty data here, and so if we commit * this is a noop. If someone immediately starts writing to the inode * it is very likely we'll catch some of their writes in this * transaction, and the commit will find this file on the ordered * data list with good things to send down. * * This is a best effort solution, there is still a window where * using truncate to replace the contents of the file will * end up with a zero length file after a crash. */ if (inode->i_size == 0 && test_bit(BTRFS_INODE_ORDERED_DATA_CLOSE, &BTRFS_I(inode)->runtime_flags)) btrfs_add_ordered_operation(trans, root, inode); /* * So if we truncate and then write and fsync we normally would just * write the extents that changed, which is a problem if we need to * first truncate that entire inode. So set this flag so we write out * all of the extents in the inode to the sync log so we're completely * safe. */ set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags); trans->block_rsv = rsv; while (1) { ret = btrfs_truncate_inode_items(trans, root, inode, inode->i_size, BTRFS_EXTENT_DATA_KEY); if (ret != -ENOSPC) { err = ret; break; } trans->block_rsv = &root->fs_info->trans_block_rsv; ret = btrfs_update_inode(trans, root, inode); if (ret) { err = ret; break; } btrfs_end_transaction(trans, root); btrfs_btree_balance_dirty(root); trans = btrfs_start_transaction(root, 2); if (IS_ERR(trans)) { ret = err = PTR_ERR(trans); trans = NULL; break; } ret = btrfs_block_rsv_migrate(&root->fs_info->trans_block_rsv, rsv, min_size); BUG_ON(ret); /* shouldn't happen */ trans->block_rsv = rsv; } if (ret == 0 && inode->i_nlink > 0) { trans->block_rsv = root->orphan_block_rsv; ret = btrfs_orphan_del(trans, inode); if (ret) err = ret; } else if (ret && inode->i_nlink > 0) { /* * Failed to do the truncate, remove us from the in memory * orphan list. */ ret = btrfs_orphan_del(NULL, inode); } if (trans) { trans->block_rsv = &root->fs_info->trans_block_rsv; ret = btrfs_update_inode(trans, root, inode); if (ret && !err) err = ret; ret = btrfs_end_transaction(trans, root); btrfs_btree_balance_dirty(root); } out: btrfs_free_block_rsv(root, rsv); if (ret && !err) err = ret; return err; } /* * create a new subvolume directory/inode (helper for the ioctl). */ int btrfs_create_subvol_root(struct btrfs_trans_handle *trans, struct btrfs_root *new_root, u64 new_dirid) { struct inode *inode; int err; u64 index = 0; inode = btrfs_new_inode(trans, new_root, NULL, "..", 2, new_dirid, new_dirid, S_IFDIR | (~current_umask() & S_IRWXUGO), &index); if (IS_ERR(inode)) return PTR_ERR(inode); inode->i_op = &btrfs_dir_inode_operations; inode->i_fop = &btrfs_dir_file_operations; set_nlink(inode, 1); btrfs_i_size_write(inode, 0); err = btrfs_update_inode(trans, new_root, inode); iput(inode); return err; } struct inode *btrfs_alloc_inode(struct super_block *sb) { struct btrfs_inode *ei; struct inode *inode; ei = kmem_cache_alloc(btrfs_inode_cachep, GFP_NOFS); if (!ei) return NULL; ei->root = NULL; ei->generation = 0; ei->last_trans = 0; ei->last_sub_trans = 0; ei->logged_trans = 0; ei->delalloc_bytes = 0; ei->disk_i_size = 0; ei->flags = 0; ei->csum_bytes = 0; ei->index_cnt = (u64)-1; ei->last_unlink_trans = 0; ei->last_log_commit = 0; spin_lock_init(&ei->lock); ei->outstanding_extents = 0; ei->reserved_extents = 0; ei->runtime_flags = 0; ei->force_compress = BTRFS_COMPRESS_NONE; ei->delayed_node = NULL; inode = &ei->vfs_inode; extent_map_tree_init(&ei->extent_tree); extent_io_tree_init(&ei->io_tree, &inode->i_data); extent_io_tree_init(&ei->io_failure_tree, &inode->i_data); ei->io_tree.track_uptodate = 1; ei->io_failure_tree.track_uptodate = 1; atomic_set(&ei->sync_writers, 0); mutex_init(&ei->log_mutex); mutex_init(&ei->delalloc_mutex); btrfs_ordered_inode_tree_init(&ei->ordered_tree); INIT_LIST_HEAD(&ei->delalloc_inodes); INIT_LIST_HEAD(&ei->ordered_operations); RB_CLEAR_NODE(&ei->rb_node); return inode; } static void btrfs_i_callback(struct rcu_head *head) { struct inode *inode = container_of(head, struct inode, i_rcu); kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode)); } void btrfs_destroy_inode(struct inode *inode) { struct btrfs_ordered_extent *ordered; struct btrfs_root *root = BTRFS_I(inode)->root; WARN_ON(!hlist_empty(&inode->i_dentry)); WARN_ON(inode->i_data.nrpages); WARN_ON(BTRFS_I(inode)->outstanding_extents); WARN_ON(BTRFS_I(inode)->reserved_extents); WARN_ON(BTRFS_I(inode)->delalloc_bytes); WARN_ON(BTRFS_I(inode)->csum_bytes); /* * This can happen where we create an inode, but somebody else also * created the same inode and we need to destroy the one we already * created. */ if (!root) goto free; /* * Make sure we're properly removed from the ordered operation * lists. */ smp_mb(); if (!list_empty(&BTRFS_I(inode)->ordered_operations)) { spin_lock(&root->fs_info->ordered_extent_lock); list_del_init(&BTRFS_I(inode)->ordered_operations); spin_unlock(&root->fs_info->ordered_extent_lock); } if (test_bit(BTRFS_INODE_HAS_ORPHAN_ITEM, &BTRFS_I(inode)->runtime_flags)) { printk(KERN_INFO "BTRFS: inode %llu still on the orphan list\n", (unsigned long long)btrfs_ino(inode)); atomic_dec(&root->orphan_inodes); } while (1) { ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1); if (!ordered) break; else { printk(KERN_ERR "btrfs found ordered " "extent %llu %llu on inode cleanup\n", (unsigned long long)ordered->file_offset, (unsigned long long)ordered->len); btrfs_remove_ordered_extent(inode, ordered); btrfs_put_ordered_extent(ordered); btrfs_put_ordered_extent(ordered); } } inode_tree_del(inode); btrfs_drop_extent_cache(inode, 0, (u64)-1, 0); free: btrfs_remove_delayed_node(inode); call_rcu(&inode->i_rcu, btrfs_i_callback); } int btrfs_drop_inode(struct inode *inode) { struct btrfs_root *root = BTRFS_I(inode)->root; if (btrfs_root_refs(&root->root_item) == 0 && !btrfs_is_free_space_inode(inode)) return 1; else return generic_drop_inode(inode); } static void init_once(void *foo) { struct btrfs_inode *ei = (struct btrfs_inode *) foo; inode_init_once(&ei->vfs_inode); } void btrfs_destroy_cachep(void) { /* * Make sure all delayed rcu free inodes are flushed before we * destroy cache. */ rcu_barrier(); if (btrfs_inode_cachep) kmem_cache_destroy(btrfs_inode_cachep); if (btrfs_trans_handle_cachep) kmem_cache_destroy(btrfs_trans_handle_cachep); if (btrfs_transaction_cachep) kmem_cache_destroy(btrfs_transaction_cachep); if (btrfs_path_cachep) kmem_cache_destroy(btrfs_path_cachep); if (btrfs_free_space_cachep) kmem_cache_destroy(btrfs_free_space_cachep); if (btrfs_delalloc_work_cachep) kmem_cache_destroy(btrfs_delalloc_work_cachep); } int btrfs_init_cachep(void) { btrfs_inode_cachep = kmem_cache_create("btrfs_inode", sizeof(struct btrfs_inode), 0, SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, init_once); if (!btrfs_inode_cachep) goto fail; btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle", sizeof(struct btrfs_trans_handle), 0, SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL); if (!btrfs_trans_handle_cachep) goto fail; btrfs_transaction_cachep = kmem_cache_create("btrfs_transaction", sizeof(struct btrfs_transaction), 0, SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL); if (!btrfs_transaction_cachep) goto fail; btrfs_path_cachep = kmem_cache_create("btrfs_path", sizeof(struct btrfs_path), 0, SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL); if (!btrfs_path_cachep) goto fail; btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space", sizeof(struct btrfs_free_space), 0, SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL); if (!btrfs_free_space_cachep) goto fail; btrfs_delalloc_work_cachep = kmem_cache_create("btrfs_delalloc_work", sizeof(struct btrfs_delalloc_work), 0, SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD, NULL); if (!btrfs_delalloc_work_cachep) goto fail; return 0; fail: btrfs_destroy_cachep(); return -ENOMEM; } static int btrfs_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat) { struct inode *inode = dentry->d_inode; u32 blocksize = inode->i_sb->s_blocksize; generic_fillattr(inode, stat); stat->dev = BTRFS_I(inode)->root->anon_dev; stat->blksize = PAGE_CACHE_SIZE; stat->blocks = (ALIGN(inode_get_bytes(inode), blocksize) + ALIGN(BTRFS_I(inode)->delalloc_bytes, blocksize)) >> 9; return 0; } /* * If a file is moved, it will inherit the cow and compression flags of the new * directory. */ static void fixup_inode_flags(struct inode *dir, struct inode *inode) { struct btrfs_inode *b_dir = BTRFS_I(dir); struct btrfs_inode *b_inode = BTRFS_I(inode); if (b_dir->flags & BTRFS_INODE_NODATACOW) b_inode->flags |= BTRFS_INODE_NODATACOW; else b_inode->flags &= ~BTRFS_INODE_NODATACOW; if (b_dir->flags & BTRFS_INODE_COMPRESS) { b_inode->flags |= BTRFS_INODE_COMPRESS; b_inode->flags &= ~BTRFS_INODE_NOCOMPRESS; } else { b_inode->flags &= ~(BTRFS_INODE_COMPRESS | BTRFS_INODE_NOCOMPRESS); } } static int btrfs_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(old_dir)->root; struct btrfs_root *dest = BTRFS_I(new_dir)->root; struct inode *new_inode = new_dentry->d_inode; struct inode *old_inode = old_dentry->d_inode; struct timespec ctime = CURRENT_TIME; u64 index = 0; u64 root_objectid; int ret; u64 old_ino = btrfs_ino(old_inode); if (btrfs_ino(new_dir) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) return -EPERM; /* we only allow rename subvolume link between subvolumes */ if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest) return -EXDEV; if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID || (new_inode && btrfs_ino(new_inode) == BTRFS_FIRST_FREE_OBJECTID)) return -ENOTEMPTY; if (S_ISDIR(old_inode->i_mode) && new_inode && new_inode->i_size > BTRFS_EMPTY_DIR_SIZE) return -ENOTEMPTY; /* check for collisions, even if the name isn't there */ ret = btrfs_check_dir_item_collision(root, new_dir->i_ino, new_dentry->d_name.name, new_dentry->d_name.len); if (ret) { if (ret == -EEXIST) { /* we shouldn't get * eexist without a new_inode */ if (!new_inode) { WARN_ON(1); return ret; } } else { /* maybe -EOVERFLOW */ return ret; } } ret = 0; /* * we're using rename to replace one file with another. * and the replacement file is large. Start IO on it now so * we don't add too much work to the end of the transaction */ if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size && old_inode->i_size > BTRFS_ORDERED_OPERATIONS_FLUSH_LIMIT) filemap_flush(old_inode->i_mapping); /* close the racy window with snapshot create/destroy ioctl */ if (old_ino == BTRFS_FIRST_FREE_OBJECTID) down_read(&root->fs_info->subvol_sem); /* * We want to reserve the absolute worst case amount of items. So if * both inodes are subvols and we need to unlink them then that would * require 4 item modifications, but if they are both normal inodes it * would require 5 item modifications, so we'll assume their normal * inodes. So 5 * 2 is 10, plus 1 for the new link, so 11 total items * should cover the worst case number of items we'll modify. */ trans = btrfs_start_transaction(root, 20); if (IS_ERR(trans)) { ret = PTR_ERR(trans); goto out_notrans; } if (dest != root) btrfs_record_root_in_trans(trans, dest); ret = btrfs_set_inode_index(new_dir, &index); if (ret) goto out_fail; if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) { /* force full log commit if subvolume involved. */ root->fs_info->last_trans_log_full_commit = trans->transid; } else { ret = btrfs_insert_inode_ref(trans, dest, new_dentry->d_name.name, new_dentry->d_name.len, old_ino, btrfs_ino(new_dir), index); if (ret) goto out_fail; /* * this is an ugly little race, but the rename is required * to make sure that if we crash, the inode is either at the * old name or the new one. pinning the log transaction lets * us make sure we don't allow a log commit to come in after * we unlink the name but before we add the new name back in. */ btrfs_pin_log_trans(root); } /* * make sure the inode gets flushed if it is replacing * something. */ if (new_inode && new_inode->i_size && S_ISREG(old_inode->i_mode)) btrfs_add_ordered_operation(trans, root, old_inode); inode_inc_iversion(old_dir); inode_inc_iversion(new_dir); inode_inc_iversion(old_inode); old_dir->i_ctime = old_dir->i_mtime = ctime; new_dir->i_ctime = new_dir->i_mtime = ctime; old_inode->i_ctime = ctime; if (old_dentry->d_parent != new_dentry->d_parent) btrfs_record_unlink_dir(trans, old_dir, old_inode, 1); if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) { root_objectid = BTRFS_I(old_inode)->root->root_key.objectid; ret = btrfs_unlink_subvol(trans, root, old_dir, root_objectid, old_dentry->d_name.name, old_dentry->d_name.len); } else { ret = __btrfs_unlink_inode(trans, root, old_dir, old_dentry->d_inode, old_dentry->d_name.name, old_dentry->d_name.len); if (!ret) ret = btrfs_update_inode(trans, root, old_inode); } if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_fail; } if (new_inode) { inode_inc_iversion(new_inode); new_inode->i_ctime = CURRENT_TIME; if (unlikely(btrfs_ino(new_inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) { root_objectid = BTRFS_I(new_inode)->location.objectid; ret = btrfs_unlink_subvol(trans, dest, new_dir, root_objectid, new_dentry->d_name.name, new_dentry->d_name.len); BUG_ON(new_inode->i_nlink == 0); } else { ret = btrfs_unlink_inode(trans, dest, new_dir, new_dentry->d_inode, new_dentry->d_name.name, new_dentry->d_name.len); } if (!ret && new_inode->i_nlink == 0) { ret = btrfs_orphan_add(trans, new_dentry->d_inode); BUG_ON(ret); } if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_fail; } } fixup_inode_flags(new_dir, old_inode); ret = btrfs_add_link(trans, new_dir, old_inode, new_dentry->d_name.name, new_dentry->d_name.len, 0, index); if (ret) { btrfs_abort_transaction(trans, root, ret); goto out_fail; } if (old_ino != BTRFS_FIRST_FREE_OBJECTID) { struct dentry *parent = new_dentry->d_parent; btrfs_log_new_name(trans, old_inode, old_dir, parent); btrfs_end_log_trans(root); } out_fail: btrfs_end_transaction(trans, root); out_notrans: if (old_ino == BTRFS_FIRST_FREE_OBJECTID) up_read(&root->fs_info->subvol_sem); return ret; } static void btrfs_run_delalloc_work(struct btrfs_work *work) { struct btrfs_delalloc_work *delalloc_work; delalloc_work = container_of(work, struct btrfs_delalloc_work, work); if (delalloc_work->wait) btrfs_wait_ordered_range(delalloc_work->inode, 0, (u64)-1); else filemap_flush(delalloc_work->inode->i_mapping); if (delalloc_work->delay_iput) btrfs_add_delayed_iput(delalloc_work->inode); else iput(delalloc_work->inode); complete(&delalloc_work->completion); } struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode, int wait, int delay_iput) { struct btrfs_delalloc_work *work; work = kmem_cache_zalloc(btrfs_delalloc_work_cachep, GFP_NOFS); if (!work) return NULL; init_completion(&work->completion); INIT_LIST_HEAD(&work->list); work->inode = inode; work->wait = wait; work->delay_iput = delay_iput; work->work.func = btrfs_run_delalloc_work; return work; } void btrfs_wait_and_free_delalloc_work(struct btrfs_delalloc_work *work) { wait_for_completion(&work->completion); kmem_cache_free(btrfs_delalloc_work_cachep, work); } /* * some fairly slow code that needs optimization. This walks the list * of all the inodes with pending delalloc and forces them to disk. */ int btrfs_start_delalloc_inodes(struct btrfs_root *root, int delay_iput) { struct list_head *head = &root->fs_info->delalloc_inodes; struct btrfs_inode *binode; struct inode *inode; struct btrfs_delalloc_work *work, *next; struct list_head works; int ret = 0; if (root->fs_info->sb->s_flags & MS_RDONLY) return -EROFS; INIT_LIST_HEAD(&works); spin_lock(&root->fs_info->delalloc_lock); while (!list_empty(head)) { binode = list_entry(head->next, struct btrfs_inode, delalloc_inodes); inode = igrab(&binode->vfs_inode); if (!inode) list_del_init(&binode->delalloc_inodes); spin_unlock(&root->fs_info->delalloc_lock); if (inode) { work = btrfs_alloc_delalloc_work(inode, 0, delay_iput); if (!work) { ret = -ENOMEM; goto out; } list_add_tail(&work->list, &works); btrfs_queue_worker(&root->fs_info->flush_workers, &work->work); } cond_resched(); spin_lock(&root->fs_info->delalloc_lock); } spin_unlock(&root->fs_info->delalloc_lock); /* the filemap_flush will queue IO into the worker threads, but * we have to make sure the IO is actually started and that * ordered extents get created before we return */ atomic_inc(&root->fs_info->async_submit_draining); while (atomic_read(&root->fs_info->nr_async_submits) || atomic_read(&root->fs_info->async_delalloc_pages)) { wait_event(root->fs_info->async_submit_wait, (atomic_read(&root->fs_info->nr_async_submits) == 0 && atomic_read(&root->fs_info->async_delalloc_pages) == 0)); } atomic_dec(&root->fs_info->async_submit_draining); out: list_for_each_entry_safe(work, next, &works, list) { list_del_init(&work->list); btrfs_wait_and_free_delalloc_work(work); } return ret; } static int btrfs_symlink(struct inode *dir, struct dentry *dentry, const char *symname) { struct btrfs_trans_handle *trans; struct btrfs_root *root = BTRFS_I(dir)->root; struct btrfs_path *path; struct btrfs_key key; struct inode *inode = NULL; int err; int drop_inode = 0; u64 objectid; u64 index = 0 ; int name_len; int datasize; unsigned long ptr; struct btrfs_file_extent_item *ei; struct extent_buffer *leaf; name_len = strlen(symname) + 1; if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(root)) return -ENAMETOOLONG; /* * 2 items for inode item and ref * 2 items for dir items * 1 item for xattr if selinux is on */ trans = btrfs_start_transaction(root, 5); if (IS_ERR(trans)) return PTR_ERR(trans); err = btrfs_find_free_ino(root, &objectid); if (err) goto out_unlock; inode = btrfs_new_inode(trans, root, dir, dentry->d_name.name, dentry->d_name.len, btrfs_ino(dir), objectid, S_IFLNK|S_IRWXUGO, &index); if (IS_ERR(inode)) { err = PTR_ERR(inode); goto out_unlock; } err = btrfs_init_inode_security(trans, inode, dir, &dentry->d_name); if (err) { drop_inode = 1; goto out_unlock; } /* * If the active LSM wants to access the inode during * d_instantiate it needs these. Smack checks to see * if the filesystem supports xattrs by looking at the * ops vector. */ inode->i_fop = &btrfs_file_operations; inode->i_op = &btrfs_file_inode_operations; err = btrfs_add_nondir(trans, dir, dentry, inode, 0, index); if (err) drop_inode = 1; else { inode->i_mapping->a_ops = &btrfs_aops; inode->i_mapping->backing_dev_info = &root->fs_info->bdi; BTRFS_I(inode)->io_tree.ops = &btrfs_extent_io_ops; } if (drop_inode) goto out_unlock; path = btrfs_alloc_path(); if (!path) { err = -ENOMEM; drop_inode = 1; goto out_unlock; } key.objectid = btrfs_ino(inode); key.offset = 0; btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY); datasize = btrfs_file_extent_calc_inline_size(name_len); err = btrfs_insert_empty_item(trans, root, path, &key, datasize); if (err) { drop_inode = 1; btrfs_free_path(path); goto out_unlock; } leaf = path->nodes[0]; ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item); btrfs_set_file_extent_generation(leaf, ei, trans->transid); btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE); btrfs_set_file_extent_encryption(leaf, ei, 0); btrfs_set_file_extent_compression(leaf, ei, 0); btrfs_set_file_extent_other_encoding(leaf, ei, 0); btrfs_set_file_extent_ram_bytes(leaf, ei, name_len); ptr = btrfs_file_extent_inline_start(ei); write_extent_buffer(leaf, symname, ptr, name_len); btrfs_mark_buffer_dirty(leaf); btrfs_free_path(path); inode->i_op = &btrfs_symlink_inode_operations; inode->i_mapping->a_ops = &btrfs_symlink_aops; inode->i_mapping->backing_dev_info = &root->fs_info->bdi; inode_set_bytes(inode, name_len); btrfs_i_size_write(inode, name_len - 1); err = btrfs_update_inode(trans, root, inode); if (err) drop_inode = 1; out_unlock: if (!err) d_instantiate(dentry, inode); btrfs_end_transaction(trans, root); if (drop_inode) { inode_dec_link_count(inode); iput(inode); } btrfs_btree_balance_dirty(root); return err; } static int __btrfs_prealloc_file_range(struct inode *inode, int mode, u64 start, u64 num_bytes, u64 min_size, loff_t actual_len, u64 *alloc_hint, struct btrfs_trans_handle *trans) { struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree; struct extent_map *em; struct btrfs_root *root = BTRFS_I(inode)->root; struct btrfs_key ins; u64 cur_offset = start; u64 i_size; int ret = 0; bool own_trans = true; if (trans) own_trans = false; while (num_bytes > 0) { if (own_trans) { trans = btrfs_start_transaction(root, 3); if (IS_ERR(trans)) { ret = PTR_ERR(trans); break; } } ret = btrfs_reserve_extent(trans, root, num_bytes, min_size, 0, *alloc_hint, &ins, 1); if (ret) { if (own_trans) btrfs_end_transaction(trans, root); break; } ret = insert_reserved_file_extent(trans, inode, cur_offset, ins.objectid, ins.offset, ins.offset, ins.offset, 0, 0, 0, BTRFS_FILE_EXTENT_PREALLOC); if (ret) { btrfs_abort_transaction(trans, root, ret); if (own_trans) btrfs_end_transaction(trans, root); break; } btrfs_drop_extent_cache(inode, cur_offset, cur_offset + ins.offset -1, 0); em = alloc_extent_map(); if (!em) { set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &BTRFS_I(inode)->runtime_flags); goto next; } em->start = cur_offset; em->orig_start = cur_offset; em->len = ins.offset; em->block_start = ins.objectid; em->block_len = ins.offset; em->orig_block_len = ins.offset; em->bdev = root->fs_info->fs_devices->latest_bdev; set_bit(EXTENT_FLAG_PREALLOC, &em->flags); em->generation = trans->transid; while (1) { write_lock(&em_tree->lock); ret = add_extent_mapping(em_tree, em); if (!ret) list_move(&em->list, &em_tree->modified_extents); write_unlock(&em_tree->lock); if (ret != -EEXIST) break; btrfs_drop_extent_cache(inode, cur_offset, cur_offset + ins.offset - 1, 0); } free_extent_map(em); next: num_bytes -= ins.offset; cur_offset += ins.offset; *alloc_hint = ins.objectid + ins.offset; inode_inc_iversion(inode); inode->i_ctime = CURRENT_TIME; BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC; if (!(mode & FALLOC_FL_KEEP_SIZE) && (actual_len > inode->i_size) && (cur_offset > inode->i_size)) { if (cur_offset > actual_len) i_size = actual_len; else i_size = cur_offset; i_size_write(inode, i_size); btrfs_ordered_update_i_size(inode, i_size, NULL); } ret = btrfs_update_inode(trans, root, inode); if (ret) { btrfs_abort_transaction(trans, root, ret); if (own_trans) btrfs_end_transaction(trans, root); break; } if (own_trans) btrfs_end_transaction(trans, root); } return ret; } int btrfs_prealloc_file_range(struct inode *inode, int mode, u64 start, u64 num_bytes, u64 min_size, loff_t actual_len, u64 *alloc_hint) { return __btrfs_prealloc_file_range(inode, mode, start, num_bytes, min_size, actual_len, alloc_hint, NULL); } int btrfs_prealloc_file_range_trans(struct inode *inode, struct btrfs_trans_handle *trans, int mode, u64 start, u64 num_bytes, u64 min_size, loff_t actual_len, u64 *alloc_hint) { return __btrfs_prealloc_file_range(inode, mode, start, num_bytes, min_size, actual_len, alloc_hint, trans); } static int btrfs_set_page_dirty(struct page *page) { return __set_page_dirty_nobuffers(page); } static int btrfs_permission(struct inode *inode, int mask) { struct btrfs_root *root = BTRFS_I(inode)->root; umode_t mode = inode->i_mode; if (mask & MAY_WRITE && (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) { if (btrfs_root_readonly(root)) return -EROFS; if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY) return -EACCES; } return generic_permission(inode, mask); } static const struct inode_operations btrfs_dir_inode_operations = { .getattr = btrfs_getattr, .lookup = btrfs_lookup, .create = btrfs_create, .unlink = btrfs_unlink, .link = btrfs_link, .mkdir = btrfs_mkdir, .rmdir = btrfs_rmdir, .rename = btrfs_rename, .symlink = btrfs_symlink, .setattr = btrfs_setattr, .mknod = btrfs_mknod, .setxattr = btrfs_setxattr, .getxattr = btrfs_getxattr, .listxattr = btrfs_listxattr, .removexattr = btrfs_removexattr, .permission = btrfs_permission, .get_acl = btrfs_get_acl, }; static const struct inode_operations btrfs_dir_ro_inode_operations = { .lookup = btrfs_lookup, .permission = btrfs_permission, .get_acl = btrfs_get_acl, }; static const struct file_operations btrfs_dir_file_operations = { .llseek = generic_file_llseek, .read = generic_read_dir, .readdir = btrfs_real_readdir, .unlocked_ioctl = btrfs_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = btrfs_ioctl, #endif .release = btrfs_release_file, .fsync = btrfs_sync_file, }; static struct extent_io_ops btrfs_extent_io_ops = { .fill_delalloc = run_delalloc_range, .submit_bio_hook = btrfs_submit_bio_hook, .merge_bio_hook = btrfs_merge_bio_hook, .readpage_end_io_hook = btrfs_readpage_end_io_hook, .writepage_end_io_hook = btrfs_writepage_end_io_hook, .writepage_start_hook = btrfs_writepage_start_hook, .set_bit_hook = btrfs_set_bit_hook, .clear_bit_hook = btrfs_clear_bit_hook, .merge_extent_hook = btrfs_merge_extent_hook, .split_extent_hook = btrfs_split_extent_hook, }; /* * btrfs doesn't support the bmap operation because swapfiles * use bmap to make a mapping of extents in the file. They assume * these extents won't change over the life of the file and they * use the bmap result to do IO directly to the drive. * * the btrfs bmap call would return logical addresses that aren't * suitable for IO and they also will change frequently as COW * operations happen. So, swapfile + btrfs == corruption. * * For now we're avoiding this by dropping bmap. */ static const struct address_space_operations btrfs_aops = { .readpage = btrfs_readpage, .writepage = btrfs_writepage, .writepages = btrfs_writepages, .readpages = btrfs_readpages, .direct_IO = btrfs_direct_IO, .invalidatepage = btrfs_invalidatepage, .releasepage = btrfs_releasepage, .set_page_dirty = btrfs_set_page_dirty, .error_remove_page = generic_error_remove_page, }; static const struct address_space_operations btrfs_symlink_aops = { .readpage = btrfs_readpage, .writepage = btrfs_writepage, .invalidatepage = btrfs_invalidatepage, .releasepage = btrfs_releasepage, }; static const struct inode_operations btrfs_file_inode_operations = { .getattr = btrfs_getattr, .setattr = btrfs_setattr, .setxattr = btrfs_setxattr, .getxattr = btrfs_getxattr, .listxattr = btrfs_listxattr, .removexattr = btrfs_removexattr, .permission = btrfs_permission, .fiemap = btrfs_fiemap, .get_acl = btrfs_get_acl, .update_time = btrfs_update_time, }; static const struct inode_operations btrfs_special_inode_operations = { .getattr = btrfs_getattr, .setattr = btrfs_setattr, .permission = btrfs_permission, .setxattr = btrfs_setxattr, .getxattr = btrfs_getxattr, .listxattr = btrfs_listxattr, .removexattr = btrfs_removexattr, .get_acl = btrfs_get_acl, .update_time = btrfs_update_time, }; static const struct inode_operations btrfs_symlink_inode_operations = { .readlink = generic_readlink, .follow_link = page_follow_link_light, .put_link = page_put_link, .getattr = btrfs_getattr, .setattr = btrfs_setattr, .permission = btrfs_permission, .setxattr = btrfs_setxattr, .getxattr = btrfs_getxattr, .listxattr = btrfs_listxattr, .removexattr = btrfs_removexattr, .get_acl = btrfs_get_acl, .update_time = btrfs_update_time, }; const struct dentry_operations btrfs_dentry_operations = { .d_delete = btrfs_dentry_delete, .d_release = btrfs_dentry_release, };
./CrossVul/dataset_final_sorted/CWE-310/c/good_3783_2
crossvul-cpp_data_bad_3783_1
/* * Copyright (C) 2007 Oracle. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License v2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 021110-1307, USA. */ #include "ctree.h" #include "disk-io.h" #include "hash.h" #include "transaction.h" /* * insert a name into a directory, doing overflow properly if there is a hash * collision. data_size indicates how big the item inserted should be. On * success a struct btrfs_dir_item pointer is returned, otherwise it is * an ERR_PTR. * * The name is not copied into the dir item, you have to do that yourself. */ static struct btrfs_dir_item *insert_with_overflow(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, struct btrfs_key *cpu_key, u32 data_size, const char *name, int name_len) { int ret; char *ptr; struct btrfs_item *item; struct extent_buffer *leaf; ret = btrfs_insert_empty_item(trans, root, path, cpu_key, data_size); if (ret == -EEXIST) { struct btrfs_dir_item *di; di = btrfs_match_dir_item_name(root, path, name, name_len); if (di) return ERR_PTR(-EEXIST); btrfs_extend_item(trans, root, path, data_size); } else if (ret < 0) return ERR_PTR(ret); WARN_ON(ret > 0); leaf = path->nodes[0]; item = btrfs_item_nr(leaf, path->slots[0]); ptr = btrfs_item_ptr(leaf, path->slots[0], char); BUG_ON(data_size > btrfs_item_size(leaf, item)); ptr += btrfs_item_size(leaf, item) - data_size; return (struct btrfs_dir_item *)ptr; } /* * xattrs work a lot like directories, this inserts an xattr item * into the tree */ int btrfs_insert_xattr_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, u64 objectid, const char *name, u16 name_len, const void *data, u16 data_len) { int ret = 0; struct btrfs_dir_item *dir_item; unsigned long name_ptr, data_ptr; struct btrfs_key key, location; struct btrfs_disk_key disk_key; struct extent_buffer *leaf; u32 data_size; BUG_ON(name_len + data_len > BTRFS_MAX_XATTR_SIZE(root)); key.objectid = objectid; btrfs_set_key_type(&key, BTRFS_XATTR_ITEM_KEY); key.offset = btrfs_name_hash(name, name_len); data_size = sizeof(*dir_item) + name_len + data_len; dir_item = insert_with_overflow(trans, root, path, &key, data_size, name, name_len); if (IS_ERR(dir_item)) return PTR_ERR(dir_item); memset(&location, 0, sizeof(location)); leaf = path->nodes[0]; btrfs_cpu_key_to_disk(&disk_key, &location); btrfs_set_dir_item_key(leaf, dir_item, &disk_key); btrfs_set_dir_type(leaf, dir_item, BTRFS_FT_XATTR); btrfs_set_dir_name_len(leaf, dir_item, name_len); btrfs_set_dir_transid(leaf, dir_item, trans->transid); btrfs_set_dir_data_len(leaf, dir_item, data_len); name_ptr = (unsigned long)(dir_item + 1); data_ptr = (unsigned long)((char *)name_ptr + name_len); write_extent_buffer(leaf, name, name_ptr, name_len); write_extent_buffer(leaf, data, data_ptr, data_len); btrfs_mark_buffer_dirty(path->nodes[0]); return ret; } /* * insert a directory item in the tree, doing all the magic for * both indexes. 'dir' indicates which objectid to insert it into, * 'location' is the key to stuff into the directory item, 'type' is the * type of the inode we're pointing to, and 'index' is the sequence number * to use for the second index (if one is created). * Will return 0 or -ENOMEM */ int btrfs_insert_dir_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, const char *name, int name_len, struct inode *dir, struct btrfs_key *location, u8 type, u64 index) { int ret = 0; int ret2 = 0; struct btrfs_path *path; struct btrfs_dir_item *dir_item; struct extent_buffer *leaf; unsigned long name_ptr; struct btrfs_key key; struct btrfs_disk_key disk_key; u32 data_size; key.objectid = btrfs_ino(dir); btrfs_set_key_type(&key, BTRFS_DIR_ITEM_KEY); key.offset = btrfs_name_hash(name, name_len); path = btrfs_alloc_path(); if (!path) return -ENOMEM; path->leave_spinning = 1; btrfs_cpu_key_to_disk(&disk_key, location); data_size = sizeof(*dir_item) + name_len; dir_item = insert_with_overflow(trans, root, path, &key, data_size, name, name_len); if (IS_ERR(dir_item)) { ret = PTR_ERR(dir_item); if (ret == -EEXIST) goto second_insert; goto out_free; } leaf = path->nodes[0]; btrfs_set_dir_item_key(leaf, dir_item, &disk_key); btrfs_set_dir_type(leaf, dir_item, type); btrfs_set_dir_data_len(leaf, dir_item, 0); btrfs_set_dir_name_len(leaf, dir_item, name_len); btrfs_set_dir_transid(leaf, dir_item, trans->transid); name_ptr = (unsigned long)(dir_item + 1); write_extent_buffer(leaf, name, name_ptr, name_len); btrfs_mark_buffer_dirty(leaf); second_insert: /* FIXME, use some real flag for selecting the extra index */ if (root == root->fs_info->tree_root) { ret = 0; goto out_free; } btrfs_release_path(path); ret2 = btrfs_insert_delayed_dir_index(trans, root, name, name_len, dir, &disk_key, type, index); out_free: btrfs_free_path(path); if (ret) return ret; if (ret2) return ret2; return 0; } /* * lookup a directory item based on name. 'dir' is the objectid * we're searching in, and 'mod' tells us if you plan on deleting the * item (use mod < 0) or changing the options (use mod > 0) */ struct btrfs_dir_item *btrfs_lookup_dir_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, u64 dir, const char *name, int name_len, int mod) { int ret; struct btrfs_key key; int ins_len = mod < 0 ? -1 : 0; int cow = mod != 0; key.objectid = dir; btrfs_set_key_type(&key, BTRFS_DIR_ITEM_KEY); key.offset = btrfs_name_hash(name, name_len); ret = btrfs_search_slot(trans, root, &key, path, ins_len, cow); if (ret < 0) return ERR_PTR(ret); if (ret > 0) return NULL; return btrfs_match_dir_item_name(root, path, name, name_len); } /* * lookup a directory item based on index. 'dir' is the objectid * we're searching in, and 'mod' tells us if you plan on deleting the * item (use mod < 0) or changing the options (use mod > 0) * * The name is used to make sure the index really points to the name you were * looking for. */ struct btrfs_dir_item * btrfs_lookup_dir_index_item(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, u64 dir, u64 objectid, const char *name, int name_len, int mod) { int ret; struct btrfs_key key; int ins_len = mod < 0 ? -1 : 0; int cow = mod != 0; key.objectid = dir; btrfs_set_key_type(&key, BTRFS_DIR_INDEX_KEY); key.offset = objectid; ret = btrfs_search_slot(trans, root, &key, path, ins_len, cow); if (ret < 0) return ERR_PTR(ret); if (ret > 0) return ERR_PTR(-ENOENT); return btrfs_match_dir_item_name(root, path, name, name_len); } struct btrfs_dir_item * btrfs_search_dir_index_item(struct btrfs_root *root, struct btrfs_path *path, u64 dirid, const char *name, int name_len) { struct extent_buffer *leaf; struct btrfs_dir_item *di; struct btrfs_key key; u32 nritems; int ret; key.objectid = dirid; key.type = BTRFS_DIR_INDEX_KEY; key.offset = 0; ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); if (ret < 0) return ERR_PTR(ret); leaf = path->nodes[0]; nritems = btrfs_header_nritems(leaf); while (1) { if (path->slots[0] >= nritems) { ret = btrfs_next_leaf(root, path); if (ret < 0) return ERR_PTR(ret); if (ret > 0) break; leaf = path->nodes[0]; nritems = btrfs_header_nritems(leaf); continue; } btrfs_item_key_to_cpu(leaf, &key, path->slots[0]); if (key.objectid != dirid || key.type != BTRFS_DIR_INDEX_KEY) break; di = btrfs_match_dir_item_name(root, path, name, name_len); if (di) return di; path->slots[0]++; } return NULL; } struct btrfs_dir_item *btrfs_lookup_xattr(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, u64 dir, const char *name, u16 name_len, int mod) { int ret; struct btrfs_key key; int ins_len = mod < 0 ? -1 : 0; int cow = mod != 0; key.objectid = dir; btrfs_set_key_type(&key, BTRFS_XATTR_ITEM_KEY); key.offset = btrfs_name_hash(name, name_len); ret = btrfs_search_slot(trans, root, &key, path, ins_len, cow); if (ret < 0) return ERR_PTR(ret); if (ret > 0) return NULL; return btrfs_match_dir_item_name(root, path, name, name_len); } /* * helper function to look at the directory item pointed to by 'path' * this walks through all the entries in a dir item and finds one * for a specific name. */ struct btrfs_dir_item *btrfs_match_dir_item_name(struct btrfs_root *root, struct btrfs_path *path, const char *name, int name_len) { struct btrfs_dir_item *dir_item; unsigned long name_ptr; u32 total_len; u32 cur = 0; u32 this_len; struct extent_buffer *leaf; leaf = path->nodes[0]; dir_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item); if (verify_dir_item(root, leaf, dir_item)) return NULL; total_len = btrfs_item_size_nr(leaf, path->slots[0]); while (cur < total_len) { this_len = sizeof(*dir_item) + btrfs_dir_name_len(leaf, dir_item) + btrfs_dir_data_len(leaf, dir_item); name_ptr = (unsigned long)(dir_item + 1); if (btrfs_dir_name_len(leaf, dir_item) == name_len && memcmp_extent_buffer(leaf, name, name_ptr, name_len) == 0) return dir_item; cur += this_len; dir_item = (struct btrfs_dir_item *)((char *)dir_item + this_len); } return NULL; } /* * given a pointer into a directory item, delete it. This * handles items that have more than one entry in them. */ int btrfs_delete_one_dir_name(struct btrfs_trans_handle *trans, struct btrfs_root *root, struct btrfs_path *path, struct btrfs_dir_item *di) { struct extent_buffer *leaf; u32 sub_item_len; u32 item_len; int ret = 0; leaf = path->nodes[0]; sub_item_len = sizeof(*di) + btrfs_dir_name_len(leaf, di) + btrfs_dir_data_len(leaf, di); item_len = btrfs_item_size_nr(leaf, path->slots[0]); if (sub_item_len == item_len) { ret = btrfs_del_item(trans, root, path); } else { /* MARKER */ unsigned long ptr = (unsigned long)di; unsigned long start; start = btrfs_item_ptr_offset(leaf, path->slots[0]); memmove_extent_buffer(leaf, ptr, ptr + sub_item_len, item_len - (ptr + sub_item_len - start)); btrfs_truncate_item(trans, root, path, item_len - sub_item_len, 1); } return ret; } int verify_dir_item(struct btrfs_root *root, struct extent_buffer *leaf, struct btrfs_dir_item *dir_item) { u16 namelen = BTRFS_NAME_LEN; u8 type = btrfs_dir_type(leaf, dir_item); if (type >= BTRFS_FT_MAX) { printk(KERN_CRIT "btrfs: invalid dir item type: %d\n", (int)type); return 1; } if (type == BTRFS_FT_XATTR) namelen = XATTR_NAME_MAX; if (btrfs_dir_name_len(leaf, dir_item) > namelen) { printk(KERN_CRIT "btrfs: invalid dir item name len: %u\n", (unsigned)btrfs_dir_data_len(leaf, dir_item)); return 1; } /* BTRFS_MAX_XATTR_SIZE is the same for all dir items */ if (btrfs_dir_data_len(leaf, dir_item) > BTRFS_MAX_XATTR_SIZE(root)) { printk(KERN_CRIT "btrfs: invalid dir item data len: %u\n", (unsigned)btrfs_dir_data_len(leaf, dir_item)); return 1; } return 0; }
./CrossVul/dataset_final_sorted/CWE-310/c/bad_3783_1
crossvul-cpp_data_bad_2309_3
/* crypto/ecdsa/ecdsa_vrf.c */ /* * Written by Nils Larsch for the OpenSSL project */ /* ==================================================================== * Copyright (c) 1998-2002 The OpenSSL 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: * * 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. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include "ecs_locl.h" #ifndef OPENSSL_NO_ENGINE #include <openssl/engine.h> #endif /*- * returns * 1: correct signature * 0: incorrect signature * -1: error */ int ECDSA_do_verify(const unsigned char *dgst, int dgst_len, const ECDSA_SIG *sig, EC_KEY *eckey) { ECDSA_DATA *ecdsa = ecdsa_check(eckey); if (ecdsa == NULL) return 0; return ecdsa->meth->ecdsa_do_verify(dgst, dgst_len, sig, eckey); } /*- * returns * 1: correct signature * 0: incorrect signature * -1: error */ int ECDSA_verify(int type, const unsigned char *dgst, int dgst_len, const unsigned char *sigbuf, int sig_len, EC_KEY *eckey) { ECDSA_SIG *s; int ret=-1; s = ECDSA_SIG_new(); if (s == NULL) return(ret); if (d2i_ECDSA_SIG(&s, &sigbuf, sig_len) == NULL) goto err; ret=ECDSA_do_verify(dgst, dgst_len, s, eckey); err: ECDSA_SIG_free(s); return(ret); }
./CrossVul/dataset_final_sorted/CWE-310/c/bad_2309_3
crossvul-cpp_data_bad_2310_0
/* crypto/asn1/a_verify.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <stdio.h> #include <time.h> #include "cryptlib.h" #ifndef NO_SYS_TYPES_H # include <sys/types.h> #endif #include <openssl/bn.h> #include <openssl/x509.h> #include <openssl/objects.h> #include <openssl/buffer.h> #include <openssl/evp.h> #include "asn1_locl.h" #ifndef NO_ASN1_OLD int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *a, ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey) { EVP_MD_CTX ctx; const EVP_MD *type; unsigned char *p,*buf_in=NULL; int ret= -1,i,inl; EVP_MD_CTX_init(&ctx); i=OBJ_obj2nid(a->algorithm); type=EVP_get_digestbyname(OBJ_nid2sn(i)); if (type == NULL) { ASN1err(ASN1_F_ASN1_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } if (signature->type == V_ASN1_BIT_STRING && signature->flags & 0x7) { ASN1err(ASN1_F_ASN1_VERIFY, ASN1_R_INVALID_BIT_STRING_BITS_LEFT); goto err; } inl=i2d(data,NULL); buf_in=OPENSSL_malloc((unsigned int)inl); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } p=buf_in; i2d(data,&p); ret= EVP_VerifyInit_ex(&ctx,type, NULL) && EVP_VerifyUpdate(&ctx,(unsigned char *)buf_in,inl); OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (!ret) { ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB); goto err; } ret = -1; if (EVP_VerifyFinal(&ctx,(unsigned char *)signature->data, (unsigned int)signature->length,pkey) <= 0) { ASN1err(ASN1_F_ASN1_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); } #endif int ASN1_item_verify(const ASN1_ITEM *it, X509_ALGOR *a, ASN1_BIT_STRING *signature, void *asn, EVP_PKEY *pkey) { EVP_MD_CTX ctx; unsigned char *buf_in=NULL; int ret= -1,inl; int mdnid, pknid; if (!pkey) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY, ERR_R_PASSED_NULL_PARAMETER); return -1; } if (signature->type == V_ASN1_BIT_STRING && signature->flags & 0x7) { ASN1err(ASN1_F_ASN1_VERIFY, ASN1_R_INVALID_BIT_STRING_BITS_LEFT); return -1; } EVP_MD_CTX_init(&ctx); /* Convert signature OID into digest and public key OIDs */ if (!OBJ_find_sigid_algs(OBJ_obj2nid(a->algorithm), &mdnid, &pknid)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } if (mdnid == NID_undef) { if (!pkey->ameth || !pkey->ameth->item_verify) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM); goto err; } ret = pkey->ameth->item_verify(&ctx, it, asn, a, signature, pkey); /* Return value of 2 means carry on, anything else means we * exit straight away: either a fatal error of the underlying * verification routine handles all verification. */ if (ret != 2) goto err; ret = -1; } else { const EVP_MD *type; type=EVP_get_digestbynid(mdnid); if (type == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM); goto err; } /* Check public key OID matches public key type */ if (EVP_PKEY_type(pknid) != pkey->ameth->pkey_id) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ASN1_R_WRONG_PUBLIC_KEY_TYPE); goto err; } if (!EVP_DigestVerifyInit(&ctx, NULL, type, NULL, pkey)) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } } inl = ASN1_item_i2d(asn, &buf_in, it); if (buf_in == NULL) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_MALLOC_FAILURE); goto err; } ret = EVP_DigestVerifyUpdate(&ctx,buf_in,inl); OPENSSL_cleanse(buf_in,(unsigned int)inl); OPENSSL_free(buf_in); if (!ret) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); goto err; } ret = -1; if (EVP_DigestVerifyFinal(&ctx,signature->data, (size_t)signature->length) <= 0) { ASN1err(ASN1_F_ASN1_ITEM_VERIFY,ERR_R_EVP_LIB); ret=0; goto err; } /* we don't need to zero the 'ctx' because we just checked * public information */ /* memset(&ctx,0,sizeof(ctx)); */ ret=1; err: EVP_MD_CTX_cleanup(&ctx); return(ret); }
./CrossVul/dataset_final_sorted/CWE-310/c/bad_2310_0
crossvul-cpp_data_bad_5666_1
/* * AEAD: Authenticated Encryption with Associated Data * * This file provides API support for AEAD algorithms. * * Copyright (c) 2007 Herbert Xu <herbert@gondor.apana.org.au> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include <crypto/internal/aead.h> #include <linux/err.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/rtnetlink.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/seq_file.h> #include <linux/cryptouser.h> #include <net/netlink.h> #include "internal.h" static int setkey_unaligned(struct crypto_aead *tfm, const u8 *key, unsigned int keylen) { struct aead_alg *aead = crypto_aead_alg(tfm); unsigned long alignmask = crypto_aead_alignmask(tfm); int ret; u8 *buffer, *alignbuffer; unsigned long absize; absize = keylen + alignmask; buffer = kmalloc(absize, GFP_ATOMIC); if (!buffer) return -ENOMEM; alignbuffer = (u8 *)ALIGN((unsigned long)buffer, alignmask + 1); memcpy(alignbuffer, key, keylen); ret = aead->setkey(tfm, alignbuffer, keylen); memset(alignbuffer, 0, keylen); kfree(buffer); return ret; } static int setkey(struct crypto_aead *tfm, const u8 *key, unsigned int keylen) { struct aead_alg *aead = crypto_aead_alg(tfm); unsigned long alignmask = crypto_aead_alignmask(tfm); if ((unsigned long)key & alignmask) return setkey_unaligned(tfm, key, keylen); return aead->setkey(tfm, key, keylen); } int crypto_aead_setauthsize(struct crypto_aead *tfm, unsigned int authsize) { struct aead_tfm *crt = crypto_aead_crt(tfm); int err; if (authsize > crypto_aead_alg(tfm)->maxauthsize) return -EINVAL; if (crypto_aead_alg(tfm)->setauthsize) { err = crypto_aead_alg(tfm)->setauthsize(crt->base, authsize); if (err) return err; } crypto_aead_crt(crt->base)->authsize = authsize; crt->authsize = authsize; return 0; } EXPORT_SYMBOL_GPL(crypto_aead_setauthsize); static unsigned int crypto_aead_ctxsize(struct crypto_alg *alg, u32 type, u32 mask) { return alg->cra_ctxsize; } static int no_givcrypt(struct aead_givcrypt_request *req) { return -ENOSYS; } static int crypto_init_aead_ops(struct crypto_tfm *tfm, u32 type, u32 mask) { struct aead_alg *alg = &tfm->__crt_alg->cra_aead; struct aead_tfm *crt = &tfm->crt_aead; if (max(alg->maxauthsize, alg->ivsize) > PAGE_SIZE / 8) return -EINVAL; crt->setkey = tfm->__crt_alg->cra_flags & CRYPTO_ALG_GENIV ? alg->setkey : setkey; crt->encrypt = alg->encrypt; crt->decrypt = alg->decrypt; crt->givencrypt = alg->givencrypt ?: no_givcrypt; crt->givdecrypt = alg->givdecrypt ?: no_givcrypt; crt->base = __crypto_aead_cast(tfm); crt->ivsize = alg->ivsize; crt->authsize = alg->maxauthsize; return 0; } #ifdef CONFIG_NET static int crypto_aead_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_aead raead; struct aead_alg *aead = &alg->cra_aead; snprintf(raead.type, CRYPTO_MAX_ALG_NAME, "%s", "aead"); snprintf(raead.geniv, CRYPTO_MAX_ALG_NAME, "%s", aead->geniv ?: "<built-in>"); raead.blocksize = alg->cra_blocksize; raead.maxauthsize = aead->maxauthsize; raead.ivsize = aead->ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_AEAD, sizeof(struct crypto_report_aead), &raead)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } #else static int crypto_aead_report(struct sk_buff *skb, struct crypto_alg *alg) { return -ENOSYS; } #endif static void crypto_aead_show(struct seq_file *m, struct crypto_alg *alg) __attribute__ ((unused)); static void crypto_aead_show(struct seq_file *m, struct crypto_alg *alg) { struct aead_alg *aead = &alg->cra_aead; seq_printf(m, "type : aead\n"); seq_printf(m, "async : %s\n", alg->cra_flags & CRYPTO_ALG_ASYNC ? "yes" : "no"); seq_printf(m, "blocksize : %u\n", alg->cra_blocksize); seq_printf(m, "ivsize : %u\n", aead->ivsize); seq_printf(m, "maxauthsize : %u\n", aead->maxauthsize); seq_printf(m, "geniv : %s\n", aead->geniv ?: "<built-in>"); } const struct crypto_type crypto_aead_type = { .ctxsize = crypto_aead_ctxsize, .init = crypto_init_aead_ops, #ifdef CONFIG_PROC_FS .show = crypto_aead_show, #endif .report = crypto_aead_report, }; EXPORT_SYMBOL_GPL(crypto_aead_type); static int aead_null_givencrypt(struct aead_givcrypt_request *req) { return crypto_aead_encrypt(&req->areq); } static int aead_null_givdecrypt(struct aead_givcrypt_request *req) { return crypto_aead_decrypt(&req->areq); } static int crypto_init_nivaead_ops(struct crypto_tfm *tfm, u32 type, u32 mask) { struct aead_alg *alg = &tfm->__crt_alg->cra_aead; struct aead_tfm *crt = &tfm->crt_aead; if (max(alg->maxauthsize, alg->ivsize) > PAGE_SIZE / 8) return -EINVAL; crt->setkey = setkey; crt->encrypt = alg->encrypt; crt->decrypt = alg->decrypt; if (!alg->ivsize) { crt->givencrypt = aead_null_givencrypt; crt->givdecrypt = aead_null_givdecrypt; } crt->base = __crypto_aead_cast(tfm); crt->ivsize = alg->ivsize; crt->authsize = alg->maxauthsize; return 0; } #ifdef CONFIG_NET static int crypto_nivaead_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_aead raead; struct aead_alg *aead = &alg->cra_aead; snprintf(raead.type, CRYPTO_MAX_ALG_NAME, "%s", "nivaead"); snprintf(raead.geniv, CRYPTO_MAX_ALG_NAME, "%s", aead->geniv); raead.blocksize = alg->cra_blocksize; raead.maxauthsize = aead->maxauthsize; raead.ivsize = aead->ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_AEAD, sizeof(struct crypto_report_aead), &raead)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } #else static int crypto_nivaead_report(struct sk_buff *skb, struct crypto_alg *alg) { return -ENOSYS; } #endif static void crypto_nivaead_show(struct seq_file *m, struct crypto_alg *alg) __attribute__ ((unused)); static void crypto_nivaead_show(struct seq_file *m, struct crypto_alg *alg) { struct aead_alg *aead = &alg->cra_aead; seq_printf(m, "type : nivaead\n"); seq_printf(m, "async : %s\n", alg->cra_flags & CRYPTO_ALG_ASYNC ? "yes" : "no"); seq_printf(m, "blocksize : %u\n", alg->cra_blocksize); seq_printf(m, "ivsize : %u\n", aead->ivsize); seq_printf(m, "maxauthsize : %u\n", aead->maxauthsize); seq_printf(m, "geniv : %s\n", aead->geniv); } const struct crypto_type crypto_nivaead_type = { .ctxsize = crypto_aead_ctxsize, .init = crypto_init_nivaead_ops, #ifdef CONFIG_PROC_FS .show = crypto_nivaead_show, #endif .report = crypto_nivaead_report, }; EXPORT_SYMBOL_GPL(crypto_nivaead_type); static int crypto_grab_nivaead(struct crypto_aead_spawn *spawn, const char *name, u32 type, u32 mask) { struct crypto_alg *alg; int err; type &= ~(CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV); type |= CRYPTO_ALG_TYPE_AEAD; mask |= CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV; alg = crypto_alg_mod_lookup(name, type, mask); if (IS_ERR(alg)) return PTR_ERR(alg); err = crypto_init_spawn(&spawn->base, alg, spawn->base.inst, mask); crypto_mod_put(alg); return err; } struct crypto_instance *aead_geniv_alloc(struct crypto_template *tmpl, struct rtattr **tb, u32 type, u32 mask) { const char *name; struct crypto_aead_spawn *spawn; struct crypto_attr_type *algt; struct crypto_instance *inst; struct crypto_alg *alg; int err; algt = crypto_get_attr_type(tb); if (IS_ERR(algt)) return ERR_CAST(algt); if ((algt->type ^ (CRYPTO_ALG_TYPE_AEAD | CRYPTO_ALG_GENIV)) & algt->mask) return ERR_PTR(-EINVAL); name = crypto_attr_alg_name(tb[1]); if (IS_ERR(name)) return ERR_CAST(name); inst = kzalloc(sizeof(*inst) + sizeof(*spawn), GFP_KERNEL); if (!inst) return ERR_PTR(-ENOMEM); spawn = crypto_instance_ctx(inst); /* Ignore async algorithms if necessary. */ mask |= crypto_requires_sync(algt->type, algt->mask); crypto_set_aead_spawn(spawn, inst); err = crypto_grab_nivaead(spawn, name, type, mask); if (err) goto err_free_inst; alg = crypto_aead_spawn_alg(spawn); err = -EINVAL; if (!alg->cra_aead.ivsize) goto err_drop_alg; /* * This is only true if we're constructing an algorithm with its * default IV generator. For the default generator we elide the * template name and double-check the IV generator. */ if (algt->mask & CRYPTO_ALG_GENIV) { if (strcmp(tmpl->name, alg->cra_aead.geniv)) goto err_drop_alg; memcpy(inst->alg.cra_name, alg->cra_name, CRYPTO_MAX_ALG_NAME); memcpy(inst->alg.cra_driver_name, alg->cra_driver_name, CRYPTO_MAX_ALG_NAME); } else { err = -ENAMETOOLONG; if (snprintf(inst->alg.cra_name, CRYPTO_MAX_ALG_NAME, "%s(%s)", tmpl->name, alg->cra_name) >= CRYPTO_MAX_ALG_NAME) goto err_drop_alg; if (snprintf(inst->alg.cra_driver_name, CRYPTO_MAX_ALG_NAME, "%s(%s)", tmpl->name, alg->cra_driver_name) >= CRYPTO_MAX_ALG_NAME) goto err_drop_alg; } inst->alg.cra_flags = CRYPTO_ALG_TYPE_AEAD | CRYPTO_ALG_GENIV; inst->alg.cra_flags |= alg->cra_flags & CRYPTO_ALG_ASYNC; inst->alg.cra_priority = alg->cra_priority; inst->alg.cra_blocksize = alg->cra_blocksize; inst->alg.cra_alignmask = alg->cra_alignmask; inst->alg.cra_type = &crypto_aead_type; inst->alg.cra_aead.ivsize = alg->cra_aead.ivsize; inst->alg.cra_aead.maxauthsize = alg->cra_aead.maxauthsize; inst->alg.cra_aead.geniv = alg->cra_aead.geniv; inst->alg.cra_aead.setkey = alg->cra_aead.setkey; inst->alg.cra_aead.setauthsize = alg->cra_aead.setauthsize; inst->alg.cra_aead.encrypt = alg->cra_aead.encrypt; inst->alg.cra_aead.decrypt = alg->cra_aead.decrypt; out: return inst; err_drop_alg: crypto_drop_aead(spawn); err_free_inst: kfree(inst); inst = ERR_PTR(err); goto out; } EXPORT_SYMBOL_GPL(aead_geniv_alloc); void aead_geniv_free(struct crypto_instance *inst) { crypto_drop_aead(crypto_instance_ctx(inst)); kfree(inst); } EXPORT_SYMBOL_GPL(aead_geniv_free); int aead_geniv_init(struct crypto_tfm *tfm) { struct crypto_instance *inst = (void *)tfm->__crt_alg; struct crypto_aead *aead; aead = crypto_spawn_aead(crypto_instance_ctx(inst)); if (IS_ERR(aead)) return PTR_ERR(aead); tfm->crt_aead.base = aead; tfm->crt_aead.reqsize += crypto_aead_reqsize(aead); return 0; } EXPORT_SYMBOL_GPL(aead_geniv_init); void aead_geniv_exit(struct crypto_tfm *tfm) { crypto_free_aead(tfm->crt_aead.base); } EXPORT_SYMBOL_GPL(aead_geniv_exit); static int crypto_nivaead_default(struct crypto_alg *alg, u32 type, u32 mask) { struct rtattr *tb[3]; struct { struct rtattr attr; struct crypto_attr_type data; } ptype; struct { struct rtattr attr; struct crypto_attr_alg data; } palg; struct crypto_template *tmpl; struct crypto_instance *inst; struct crypto_alg *larval; const char *geniv; int err; larval = crypto_larval_lookup(alg->cra_driver_name, CRYPTO_ALG_TYPE_AEAD | CRYPTO_ALG_GENIV, CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV); err = PTR_ERR(larval); if (IS_ERR(larval)) goto out; err = -EAGAIN; if (!crypto_is_larval(larval)) goto drop_larval; ptype.attr.rta_len = sizeof(ptype); ptype.attr.rta_type = CRYPTOA_TYPE; ptype.data.type = type | CRYPTO_ALG_GENIV; /* GENIV tells the template that we're making a default geniv. */ ptype.data.mask = mask | CRYPTO_ALG_GENIV; tb[0] = &ptype.attr; palg.attr.rta_len = sizeof(palg); palg.attr.rta_type = CRYPTOA_ALG; /* Must use the exact name to locate ourselves. */ memcpy(palg.data.name, alg->cra_driver_name, CRYPTO_MAX_ALG_NAME); tb[1] = &palg.attr; tb[2] = NULL; geniv = alg->cra_aead.geniv; tmpl = crypto_lookup_template(geniv); err = -ENOENT; if (!tmpl) goto kill_larval; inst = tmpl->alloc(tb); err = PTR_ERR(inst); if (IS_ERR(inst)) goto put_tmpl; if ((err = crypto_register_instance(tmpl, inst))) { tmpl->free(inst); goto put_tmpl; } /* Redo the lookup to use the instance we just registered. */ err = -EAGAIN; put_tmpl: crypto_tmpl_put(tmpl); kill_larval: crypto_larval_kill(larval); drop_larval: crypto_mod_put(larval); out: crypto_mod_put(alg); return err; } struct crypto_alg *crypto_lookup_aead(const char *name, u32 type, u32 mask) { struct crypto_alg *alg; alg = crypto_alg_mod_lookup(name, type, mask); if (IS_ERR(alg)) return alg; if (alg->cra_type == &crypto_aead_type) return alg; if (!alg->cra_aead.ivsize) return alg; crypto_mod_put(alg); alg = crypto_alg_mod_lookup(name, type | CRYPTO_ALG_TESTED, mask & ~CRYPTO_ALG_TESTED); if (IS_ERR(alg)) return alg; if (alg->cra_type == &crypto_aead_type) { if ((alg->cra_flags ^ type ^ ~mask) & CRYPTO_ALG_TESTED) { crypto_mod_put(alg); alg = ERR_PTR(-ENOENT); } return alg; } BUG_ON(!alg->cra_aead.ivsize); return ERR_PTR(crypto_nivaead_default(alg, type, mask)); } EXPORT_SYMBOL_GPL(crypto_lookup_aead); int crypto_grab_aead(struct crypto_aead_spawn *spawn, const char *name, u32 type, u32 mask) { struct crypto_alg *alg; int err; type &= ~(CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV); type |= CRYPTO_ALG_TYPE_AEAD; mask &= ~(CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV); mask |= CRYPTO_ALG_TYPE_MASK; alg = crypto_lookup_aead(name, type, mask); if (IS_ERR(alg)) return PTR_ERR(alg); err = crypto_init_spawn(&spawn->base, alg, spawn->base.inst, mask); crypto_mod_put(alg); return err; } EXPORT_SYMBOL_GPL(crypto_grab_aead); struct crypto_aead *crypto_alloc_aead(const char *alg_name, u32 type, u32 mask) { struct crypto_tfm *tfm; int err; type &= ~(CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV); type |= CRYPTO_ALG_TYPE_AEAD; mask &= ~(CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV); mask |= CRYPTO_ALG_TYPE_MASK; for (;;) { struct crypto_alg *alg; alg = crypto_lookup_aead(alg_name, type, mask); if (IS_ERR(alg)) { err = PTR_ERR(alg); goto err; } tfm = __crypto_alloc_tfm(alg, type, mask); if (!IS_ERR(tfm)) return __crypto_aead_cast(tfm); crypto_mod_put(alg); err = PTR_ERR(tfm); err: if (err != -EAGAIN) break; if (signal_pending(current)) { err = -EINTR; break; } } return ERR_PTR(err); } EXPORT_SYMBOL_GPL(crypto_alloc_aead); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Authenticated Encryption with Associated Data (AEAD)");
./CrossVul/dataset_final_sorted/CWE-310/c/bad_5666_1
crossvul-cpp_data_good_3783_4
/* * Copyright (C) 2007 Oracle. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License v2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 021110-1307, USA. */ #include <linux/fs.h> #include <linux/slab.h> #include <linux/sched.h> #include <linux/writeback.h> #include <linux/pagemap.h> #include <linux/blkdev.h> #include <linux/uuid.h> #include "ctree.h" #include "disk-io.h" #include "transaction.h" #include "locking.h" #include "tree-log.h" #include "inode-map.h" #include "volumes.h" #include "dev-replace.h" #define BTRFS_ROOT_TRANS_TAG 0 void put_transaction(struct btrfs_transaction *transaction) { WARN_ON(atomic_read(&transaction->use_count) == 0); if (atomic_dec_and_test(&transaction->use_count)) { BUG_ON(!list_empty(&transaction->list)); WARN_ON(transaction->delayed_refs.root.rb_node); memset(transaction, 0, sizeof(*transaction)); kmem_cache_free(btrfs_transaction_cachep, transaction); } } static noinline void switch_commit_root(struct btrfs_root *root) { free_extent_buffer(root->commit_root); root->commit_root = btrfs_root_node(root); } /* * either allocate a new transaction or hop into the existing one */ static noinline int join_transaction(struct btrfs_root *root, int type) { struct btrfs_transaction *cur_trans; struct btrfs_fs_info *fs_info = root->fs_info; spin_lock(&fs_info->trans_lock); loop: /* The file system has been taken offline. No new transactions. */ if (fs_info->fs_state & BTRFS_SUPER_FLAG_ERROR) { spin_unlock(&fs_info->trans_lock); return -EROFS; } if (fs_info->trans_no_join) { /* * If we are JOIN_NOLOCK we're already committing a current * transaction, we just need a handle to deal with something * when committing the transaction, such as inode cache and * space cache. It is a special case. */ if (type != TRANS_JOIN_NOLOCK) { spin_unlock(&fs_info->trans_lock); return -EBUSY; } } cur_trans = fs_info->running_transaction; if (cur_trans) { if (cur_trans->aborted) { spin_unlock(&fs_info->trans_lock); return cur_trans->aborted; } atomic_inc(&cur_trans->use_count); atomic_inc(&cur_trans->num_writers); cur_trans->num_joined++; spin_unlock(&fs_info->trans_lock); return 0; } spin_unlock(&fs_info->trans_lock); /* * If we are ATTACH, we just want to catch the current transaction, * and commit it. If there is no transaction, just return ENOENT. */ if (type == TRANS_ATTACH) return -ENOENT; cur_trans = kmem_cache_alloc(btrfs_transaction_cachep, GFP_NOFS); if (!cur_trans) return -ENOMEM; spin_lock(&fs_info->trans_lock); if (fs_info->running_transaction) { /* * someone started a transaction after we unlocked. Make sure * to redo the trans_no_join checks above */ kmem_cache_free(btrfs_transaction_cachep, cur_trans); cur_trans = fs_info->running_transaction; goto loop; } else if (fs_info->fs_state & BTRFS_SUPER_FLAG_ERROR) { spin_unlock(&fs_info->trans_lock); kmem_cache_free(btrfs_transaction_cachep, cur_trans); return -EROFS; } atomic_set(&cur_trans->num_writers, 1); cur_trans->num_joined = 0; init_waitqueue_head(&cur_trans->writer_wait); init_waitqueue_head(&cur_trans->commit_wait); cur_trans->in_commit = 0; cur_trans->blocked = 0; /* * One for this trans handle, one so it will live on until we * commit the transaction. */ atomic_set(&cur_trans->use_count, 2); cur_trans->commit_done = 0; cur_trans->start_time = get_seconds(); cur_trans->delayed_refs.root = RB_ROOT; cur_trans->delayed_refs.num_entries = 0; cur_trans->delayed_refs.num_heads_ready = 0; cur_trans->delayed_refs.num_heads = 0; cur_trans->delayed_refs.flushing = 0; cur_trans->delayed_refs.run_delayed_start = 0; /* * although the tree mod log is per file system and not per transaction, * the log must never go across transaction boundaries. */ smp_mb(); if (!list_empty(&fs_info->tree_mod_seq_list)) WARN(1, KERN_ERR "btrfs: tree_mod_seq_list not empty when " "creating a fresh transaction\n"); if (!RB_EMPTY_ROOT(&fs_info->tree_mod_log)) WARN(1, KERN_ERR "btrfs: tree_mod_log rb tree not empty when " "creating a fresh transaction\n"); atomic_set(&fs_info->tree_mod_seq, 0); spin_lock_init(&cur_trans->commit_lock); spin_lock_init(&cur_trans->delayed_refs.lock); INIT_LIST_HEAD(&cur_trans->pending_snapshots); list_add_tail(&cur_trans->list, &fs_info->trans_list); extent_io_tree_init(&cur_trans->dirty_pages, fs_info->btree_inode->i_mapping); fs_info->generation++; cur_trans->transid = fs_info->generation; fs_info->running_transaction = cur_trans; cur_trans->aborted = 0; spin_unlock(&fs_info->trans_lock); return 0; } /* * this does all the record keeping required to make sure that a reference * counted root is properly recorded in a given transaction. This is required * to make sure the old root from before we joined the transaction is deleted * when the transaction commits */ static int record_root_in_trans(struct btrfs_trans_handle *trans, struct btrfs_root *root) { if (root->ref_cows && root->last_trans < trans->transid) { WARN_ON(root == root->fs_info->extent_root); WARN_ON(root->commit_root != root->node); /* * see below for in_trans_setup usage rules * we have the reloc mutex held now, so there * is only one writer in this function */ root->in_trans_setup = 1; /* make sure readers find in_trans_setup before * they find our root->last_trans update */ smp_wmb(); spin_lock(&root->fs_info->fs_roots_radix_lock); if (root->last_trans == trans->transid) { spin_unlock(&root->fs_info->fs_roots_radix_lock); return 0; } radix_tree_tag_set(&root->fs_info->fs_roots_radix, (unsigned long)root->root_key.objectid, BTRFS_ROOT_TRANS_TAG); spin_unlock(&root->fs_info->fs_roots_radix_lock); root->last_trans = trans->transid; /* this is pretty tricky. We don't want to * take the relocation lock in btrfs_record_root_in_trans * unless we're really doing the first setup for this root in * this transaction. * * Normally we'd use root->last_trans as a flag to decide * if we want to take the expensive mutex. * * But, we have to set root->last_trans before we * init the relocation root, otherwise, we trip over warnings * in ctree.c. The solution used here is to flag ourselves * with root->in_trans_setup. When this is 1, we're still * fixing up the reloc trees and everyone must wait. * * When this is zero, they can trust root->last_trans and fly * through btrfs_record_root_in_trans without having to take the * lock. smp_wmb() makes sure that all the writes above are * done before we pop in the zero below */ btrfs_init_reloc_root(trans, root); smp_wmb(); root->in_trans_setup = 0; } return 0; } int btrfs_record_root_in_trans(struct btrfs_trans_handle *trans, struct btrfs_root *root) { if (!root->ref_cows) return 0; /* * see record_root_in_trans for comments about in_trans_setup usage * and barriers */ smp_rmb(); if (root->last_trans == trans->transid && !root->in_trans_setup) return 0; mutex_lock(&root->fs_info->reloc_mutex); record_root_in_trans(trans, root); mutex_unlock(&root->fs_info->reloc_mutex); return 0; } /* wait for commit against the current transaction to become unblocked * when this is done, it is safe to start a new transaction, but the current * transaction might not be fully on disk. */ static void wait_current_trans(struct btrfs_root *root) { struct btrfs_transaction *cur_trans; spin_lock(&root->fs_info->trans_lock); cur_trans = root->fs_info->running_transaction; if (cur_trans && cur_trans->blocked) { atomic_inc(&cur_trans->use_count); spin_unlock(&root->fs_info->trans_lock); wait_event(root->fs_info->transaction_wait, !cur_trans->blocked); put_transaction(cur_trans); } else { spin_unlock(&root->fs_info->trans_lock); } } static int may_wait_transaction(struct btrfs_root *root, int type) { if (root->fs_info->log_root_recovering) return 0; if (type == TRANS_USERSPACE) return 1; if (type == TRANS_START && !atomic_read(&root->fs_info->open_ioctl_trans)) return 1; return 0; } static struct btrfs_trans_handle * start_transaction(struct btrfs_root *root, u64 num_items, int type, enum btrfs_reserve_flush_enum flush) { struct btrfs_trans_handle *h; struct btrfs_transaction *cur_trans; u64 num_bytes = 0; int ret; u64 qgroup_reserved = 0; if (root->fs_info->fs_state & BTRFS_SUPER_FLAG_ERROR) return ERR_PTR(-EROFS); if (current->journal_info) { WARN_ON(type != TRANS_JOIN && type != TRANS_JOIN_NOLOCK); h = current->journal_info; h->use_count++; WARN_ON(h->use_count > 2); h->orig_rsv = h->block_rsv; h->block_rsv = NULL; goto got_it; } /* * Do the reservation before we join the transaction so we can do all * the appropriate flushing if need be. */ if (num_items > 0 && root != root->fs_info->chunk_root) { if (root->fs_info->quota_enabled && is_fstree(root->root_key.objectid)) { qgroup_reserved = num_items * root->leafsize; ret = btrfs_qgroup_reserve(root, qgroup_reserved); if (ret) return ERR_PTR(ret); } num_bytes = btrfs_calc_trans_metadata_size(root, num_items); ret = btrfs_block_rsv_add(root, &root->fs_info->trans_block_rsv, num_bytes, flush); if (ret) return ERR_PTR(ret); } again: h = kmem_cache_alloc(btrfs_trans_handle_cachep, GFP_NOFS); if (!h) return ERR_PTR(-ENOMEM); /* * If we are JOIN_NOLOCK we're already committing a transaction and * waiting on this guy, so we don't need to do the sb_start_intwrite * because we're already holding a ref. We need this because we could * have raced in and did an fsync() on a file which can kick a commit * and then we deadlock with somebody doing a freeze. * * If we are ATTACH, it means we just want to catch the current * transaction and commit it, so we needn't do sb_start_intwrite(). */ if (type < TRANS_JOIN_NOLOCK) sb_start_intwrite(root->fs_info->sb); if (may_wait_transaction(root, type)) wait_current_trans(root); do { ret = join_transaction(root, type); if (ret == -EBUSY) wait_current_trans(root); } while (ret == -EBUSY); if (ret < 0) { /* We must get the transaction if we are JOIN_NOLOCK. */ BUG_ON(type == TRANS_JOIN_NOLOCK); if (type < TRANS_JOIN_NOLOCK) sb_end_intwrite(root->fs_info->sb); kmem_cache_free(btrfs_trans_handle_cachep, h); return ERR_PTR(ret); } cur_trans = root->fs_info->running_transaction; h->transid = cur_trans->transid; h->transaction = cur_trans; h->blocks_used = 0; h->bytes_reserved = 0; h->root = root; h->delayed_ref_updates = 0; h->use_count = 1; h->adding_csums = 0; h->block_rsv = NULL; h->orig_rsv = NULL; h->aborted = 0; h->qgroup_reserved = qgroup_reserved; h->delayed_ref_elem.seq = 0; h->type = type; INIT_LIST_HEAD(&h->qgroup_ref_list); INIT_LIST_HEAD(&h->new_bgs); smp_mb(); if (cur_trans->blocked && may_wait_transaction(root, type)) { btrfs_commit_transaction(h, root); goto again; } if (num_bytes) { trace_btrfs_space_reservation(root->fs_info, "transaction", h->transid, num_bytes, 1); h->block_rsv = &root->fs_info->trans_block_rsv; h->bytes_reserved = num_bytes; } got_it: btrfs_record_root_in_trans(h, root); if (!current->journal_info && type != TRANS_USERSPACE) current->journal_info = h; return h; } struct btrfs_trans_handle *btrfs_start_transaction(struct btrfs_root *root, int num_items) { return start_transaction(root, num_items, TRANS_START, BTRFS_RESERVE_FLUSH_ALL); } struct btrfs_trans_handle *btrfs_start_transaction_lflush( struct btrfs_root *root, int num_items) { return start_transaction(root, num_items, TRANS_START, BTRFS_RESERVE_FLUSH_LIMIT); } struct btrfs_trans_handle *btrfs_join_transaction(struct btrfs_root *root) { return start_transaction(root, 0, TRANS_JOIN, 0); } struct btrfs_trans_handle *btrfs_join_transaction_nolock(struct btrfs_root *root) { return start_transaction(root, 0, TRANS_JOIN_NOLOCK, 0); } struct btrfs_trans_handle *btrfs_start_ioctl_transaction(struct btrfs_root *root) { return start_transaction(root, 0, TRANS_USERSPACE, 0); } struct btrfs_trans_handle *btrfs_attach_transaction(struct btrfs_root *root) { return start_transaction(root, 0, TRANS_ATTACH, 0); } /* wait for a transaction commit to be fully complete */ static noinline void wait_for_commit(struct btrfs_root *root, struct btrfs_transaction *commit) { wait_event(commit->commit_wait, commit->commit_done); } int btrfs_wait_for_commit(struct btrfs_root *root, u64 transid) { struct btrfs_transaction *cur_trans = NULL, *t; int ret = 0; if (transid) { if (transid <= root->fs_info->last_trans_committed) goto out; ret = -EINVAL; /* find specified transaction */ spin_lock(&root->fs_info->trans_lock); list_for_each_entry(t, &root->fs_info->trans_list, list) { if (t->transid == transid) { cur_trans = t; atomic_inc(&cur_trans->use_count); ret = 0; break; } if (t->transid > transid) { ret = 0; break; } } spin_unlock(&root->fs_info->trans_lock); /* The specified transaction doesn't exist */ if (!cur_trans) goto out; } else { /* find newest transaction that is committing | committed */ spin_lock(&root->fs_info->trans_lock); list_for_each_entry_reverse(t, &root->fs_info->trans_list, list) { if (t->in_commit) { if (t->commit_done) break; cur_trans = t; atomic_inc(&cur_trans->use_count); break; } } spin_unlock(&root->fs_info->trans_lock); if (!cur_trans) goto out; /* nothing committing|committed */ } wait_for_commit(root, cur_trans); put_transaction(cur_trans); out: return ret; } void btrfs_throttle(struct btrfs_root *root) { if (!atomic_read(&root->fs_info->open_ioctl_trans)) wait_current_trans(root); } static int should_end_transaction(struct btrfs_trans_handle *trans, struct btrfs_root *root) { int ret; ret = btrfs_block_rsv_check(root, &root->fs_info->global_block_rsv, 5); return ret ? 1 : 0; } int btrfs_should_end_transaction(struct btrfs_trans_handle *trans, struct btrfs_root *root) { struct btrfs_transaction *cur_trans = trans->transaction; int updates; int err; smp_mb(); if (cur_trans->blocked || cur_trans->delayed_refs.flushing) return 1; updates = trans->delayed_ref_updates; trans->delayed_ref_updates = 0; if (updates) { err = btrfs_run_delayed_refs(trans, root, updates); if (err) /* Error code will also eval true */ return err; } return should_end_transaction(trans, root); } static int __btrfs_end_transaction(struct btrfs_trans_handle *trans, struct btrfs_root *root, int throttle) { struct btrfs_transaction *cur_trans = trans->transaction; struct btrfs_fs_info *info = root->fs_info; int count = 0; int lock = (trans->type != TRANS_JOIN_NOLOCK); int err = 0; if (--trans->use_count) { trans->block_rsv = trans->orig_rsv; return 0; } /* * do the qgroup accounting as early as possible */ err = btrfs_delayed_refs_qgroup_accounting(trans, info); btrfs_trans_release_metadata(trans, root); trans->block_rsv = NULL; /* * the same root has to be passed to start_transaction and * end_transaction. Subvolume quota depends on this. */ WARN_ON(trans->root != root); if (trans->qgroup_reserved) { btrfs_qgroup_free(root, trans->qgroup_reserved); trans->qgroup_reserved = 0; } if (!list_empty(&trans->new_bgs)) btrfs_create_pending_block_groups(trans, root); while (count < 2) { unsigned long cur = trans->delayed_ref_updates; trans->delayed_ref_updates = 0; if (cur && trans->transaction->delayed_refs.num_heads_ready > 64) { trans->delayed_ref_updates = 0; btrfs_run_delayed_refs(trans, root, cur); } else { break; } count++; } btrfs_trans_release_metadata(trans, root); trans->block_rsv = NULL; if (!list_empty(&trans->new_bgs)) btrfs_create_pending_block_groups(trans, root); if (lock && !atomic_read(&root->fs_info->open_ioctl_trans) && should_end_transaction(trans, root)) { trans->transaction->blocked = 1; smp_wmb(); } if (lock && cur_trans->blocked && !cur_trans->in_commit) { if (throttle) { /* * We may race with somebody else here so end up having * to call end_transaction on ourselves again, so inc * our use_count. */ trans->use_count++; return btrfs_commit_transaction(trans, root); } else { wake_up_process(info->transaction_kthread); } } if (trans->type < TRANS_JOIN_NOLOCK) sb_end_intwrite(root->fs_info->sb); WARN_ON(cur_trans != info->running_transaction); WARN_ON(atomic_read(&cur_trans->num_writers) < 1); atomic_dec(&cur_trans->num_writers); smp_mb(); if (waitqueue_active(&cur_trans->writer_wait)) wake_up(&cur_trans->writer_wait); put_transaction(cur_trans); if (current->journal_info == trans) current->journal_info = NULL; if (throttle) btrfs_run_delayed_iputs(root); if (trans->aborted || root->fs_info->fs_state & BTRFS_SUPER_FLAG_ERROR) { err = -EIO; } assert_qgroups_uptodate(trans); memset(trans, 0, sizeof(*trans)); kmem_cache_free(btrfs_trans_handle_cachep, trans); return err; } int btrfs_end_transaction(struct btrfs_trans_handle *trans, struct btrfs_root *root) { int ret; ret = __btrfs_end_transaction(trans, root, 0); if (ret) return ret; return 0; } int btrfs_end_transaction_throttle(struct btrfs_trans_handle *trans, struct btrfs_root *root) { int ret; ret = __btrfs_end_transaction(trans, root, 1); if (ret) return ret; return 0; } int btrfs_end_transaction_dmeta(struct btrfs_trans_handle *trans, struct btrfs_root *root) { return __btrfs_end_transaction(trans, root, 1); } /* * when btree blocks are allocated, they have some corresponding bits set for * them in one of two extent_io trees. This is used to make sure all of * those extents are sent to disk but does not wait on them */ int btrfs_write_marked_extents(struct btrfs_root *root, struct extent_io_tree *dirty_pages, int mark) { int err = 0; int werr = 0; struct address_space *mapping = root->fs_info->btree_inode->i_mapping; struct extent_state *cached_state = NULL; u64 start = 0; u64 end; while (!find_first_extent_bit(dirty_pages, start, &start, &end, mark, &cached_state)) { convert_extent_bit(dirty_pages, start, end, EXTENT_NEED_WAIT, mark, &cached_state, GFP_NOFS); cached_state = NULL; err = filemap_fdatawrite_range(mapping, start, end); if (err) werr = err; cond_resched(); start = end + 1; } if (err) werr = err; return werr; } /* * when btree blocks are allocated, they have some corresponding bits set for * them in one of two extent_io trees. This is used to make sure all of * those extents are on disk for transaction or log commit. We wait * on all the pages and clear them from the dirty pages state tree */ int btrfs_wait_marked_extents(struct btrfs_root *root, struct extent_io_tree *dirty_pages, int mark) { int err = 0; int werr = 0; struct address_space *mapping = root->fs_info->btree_inode->i_mapping; struct extent_state *cached_state = NULL; u64 start = 0; u64 end; while (!find_first_extent_bit(dirty_pages, start, &start, &end, EXTENT_NEED_WAIT, &cached_state)) { clear_extent_bit(dirty_pages, start, end, EXTENT_NEED_WAIT, 0, 0, &cached_state, GFP_NOFS); err = filemap_fdatawait_range(mapping, start, end); if (err) werr = err; cond_resched(); start = end + 1; } if (err) werr = err; return werr; } /* * when btree blocks are allocated, they have some corresponding bits set for * them in one of two extent_io trees. This is used to make sure all of * those extents are on disk for transaction or log commit */ int btrfs_write_and_wait_marked_extents(struct btrfs_root *root, struct extent_io_tree *dirty_pages, int mark) { int ret; int ret2; ret = btrfs_write_marked_extents(root, dirty_pages, mark); ret2 = btrfs_wait_marked_extents(root, dirty_pages, mark); if (ret) return ret; if (ret2) return ret2; return 0; } int btrfs_write_and_wait_transaction(struct btrfs_trans_handle *trans, struct btrfs_root *root) { if (!trans || !trans->transaction) { struct inode *btree_inode; btree_inode = root->fs_info->btree_inode; return filemap_write_and_wait(btree_inode->i_mapping); } return btrfs_write_and_wait_marked_extents(root, &trans->transaction->dirty_pages, EXTENT_DIRTY); } /* * this is used to update the root pointer in the tree of tree roots. * * But, in the case of the extent allocation tree, updating the root * pointer may allocate blocks which may change the root of the extent * allocation tree. * * So, this loops and repeats and makes sure the cowonly root didn't * change while the root pointer was being updated in the metadata. */ static int update_cowonly_root(struct btrfs_trans_handle *trans, struct btrfs_root *root) { int ret; u64 old_root_bytenr; u64 old_root_used; struct btrfs_root *tree_root = root->fs_info->tree_root; old_root_used = btrfs_root_used(&root->root_item); btrfs_write_dirty_block_groups(trans, root); while (1) { old_root_bytenr = btrfs_root_bytenr(&root->root_item); if (old_root_bytenr == root->node->start && old_root_used == btrfs_root_used(&root->root_item)) break; btrfs_set_root_node(&root->root_item, root->node); ret = btrfs_update_root(trans, tree_root, &root->root_key, &root->root_item); if (ret) return ret; old_root_used = btrfs_root_used(&root->root_item); ret = btrfs_write_dirty_block_groups(trans, root); if (ret) return ret; } if (root != root->fs_info->extent_root) switch_commit_root(root); return 0; } /* * update all the cowonly tree roots on disk * * The error handling in this function may not be obvious. Any of the * failures will cause the file system to go offline. We still need * to clean up the delayed refs. */ static noinline int commit_cowonly_roots(struct btrfs_trans_handle *trans, struct btrfs_root *root) { struct btrfs_fs_info *fs_info = root->fs_info; struct list_head *next; struct extent_buffer *eb; int ret; ret = btrfs_run_delayed_refs(trans, root, (unsigned long)-1); if (ret) return ret; eb = btrfs_lock_root_node(fs_info->tree_root); ret = btrfs_cow_block(trans, fs_info->tree_root, eb, NULL, 0, &eb); btrfs_tree_unlock(eb); free_extent_buffer(eb); if (ret) return ret; ret = btrfs_run_delayed_refs(trans, root, (unsigned long)-1); if (ret) return ret; ret = btrfs_run_dev_stats(trans, root->fs_info); WARN_ON(ret); ret = btrfs_run_dev_replace(trans, root->fs_info); WARN_ON(ret); ret = btrfs_run_qgroups(trans, root->fs_info); BUG_ON(ret); /* run_qgroups might have added some more refs */ ret = btrfs_run_delayed_refs(trans, root, (unsigned long)-1); BUG_ON(ret); while (!list_empty(&fs_info->dirty_cowonly_roots)) { next = fs_info->dirty_cowonly_roots.next; list_del_init(next); root = list_entry(next, struct btrfs_root, dirty_list); ret = update_cowonly_root(trans, root); if (ret) return ret; } down_write(&fs_info->extent_commit_sem); switch_commit_root(fs_info->extent_root); up_write(&fs_info->extent_commit_sem); btrfs_after_dev_replace_commit(fs_info); return 0; } /* * dead roots are old snapshots that need to be deleted. This allocates * a dirty root struct and adds it into the list of dead roots that need to * be deleted */ int btrfs_add_dead_root(struct btrfs_root *root) { spin_lock(&root->fs_info->trans_lock); list_add(&root->root_list, &root->fs_info->dead_roots); spin_unlock(&root->fs_info->trans_lock); return 0; } /* * update all the cowonly tree roots on disk */ static noinline int commit_fs_roots(struct btrfs_trans_handle *trans, struct btrfs_root *root) { struct btrfs_root *gang[8]; struct btrfs_fs_info *fs_info = root->fs_info; int i; int ret; int err = 0; spin_lock(&fs_info->fs_roots_radix_lock); while (1) { ret = radix_tree_gang_lookup_tag(&fs_info->fs_roots_radix, (void **)gang, 0, ARRAY_SIZE(gang), BTRFS_ROOT_TRANS_TAG); if (ret == 0) break; for (i = 0; i < ret; i++) { root = gang[i]; radix_tree_tag_clear(&fs_info->fs_roots_radix, (unsigned long)root->root_key.objectid, BTRFS_ROOT_TRANS_TAG); spin_unlock(&fs_info->fs_roots_radix_lock); btrfs_free_log(trans, root); btrfs_update_reloc_root(trans, root); btrfs_orphan_commit_root(trans, root); btrfs_save_ino_cache(root, trans); /* see comments in should_cow_block() */ root->force_cow = 0; smp_wmb(); if (root->commit_root != root->node) { mutex_lock(&root->fs_commit_mutex); switch_commit_root(root); btrfs_unpin_free_ino(root); mutex_unlock(&root->fs_commit_mutex); btrfs_set_root_node(&root->root_item, root->node); } err = btrfs_update_root(trans, fs_info->tree_root, &root->root_key, &root->root_item); spin_lock(&fs_info->fs_roots_radix_lock); if (err) break; } } spin_unlock(&fs_info->fs_roots_radix_lock); return err; } /* * defrag a given btree. If cacheonly == 1, this won't read from the disk, * otherwise every leaf in the btree is read and defragged. */ int btrfs_defrag_root(struct btrfs_root *root, int cacheonly) { struct btrfs_fs_info *info = root->fs_info; struct btrfs_trans_handle *trans; int ret; if (xchg(&root->defrag_running, 1)) return 0; while (1) { trans = btrfs_start_transaction(root, 0); if (IS_ERR(trans)) return PTR_ERR(trans); ret = btrfs_defrag_leaves(trans, root, cacheonly); btrfs_end_transaction(trans, root); btrfs_btree_balance_dirty(info->tree_root); cond_resched(); if (btrfs_fs_closing(root->fs_info) || ret != -EAGAIN) break; } root->defrag_running = 0; return ret; } /* * new snapshots need to be created at a very specific time in the * transaction commit. This does the actual creation */ static noinline int create_pending_snapshot(struct btrfs_trans_handle *trans, struct btrfs_fs_info *fs_info, struct btrfs_pending_snapshot *pending) { struct btrfs_key key; struct btrfs_root_item *new_root_item; struct btrfs_root *tree_root = fs_info->tree_root; struct btrfs_root *root = pending->root; struct btrfs_root *parent_root; struct btrfs_block_rsv *rsv; struct inode *parent_inode; struct btrfs_path *path; struct btrfs_dir_item *dir_item; struct dentry *parent; struct dentry *dentry; struct extent_buffer *tmp; struct extent_buffer *old; struct timespec cur_time = CURRENT_TIME; int ret; u64 to_reserve = 0; u64 index = 0; u64 objectid; u64 root_flags; uuid_le new_uuid; path = btrfs_alloc_path(); if (!path) { ret = pending->error = -ENOMEM; goto path_alloc_fail; } new_root_item = kmalloc(sizeof(*new_root_item), GFP_NOFS); if (!new_root_item) { ret = pending->error = -ENOMEM; goto root_item_alloc_fail; } ret = btrfs_find_free_objectid(tree_root, &objectid); if (ret) { pending->error = ret; goto no_free_objectid; } btrfs_reloc_pre_snapshot(trans, pending, &to_reserve); if (to_reserve > 0) { ret = btrfs_block_rsv_add(root, &pending->block_rsv, to_reserve, BTRFS_RESERVE_NO_FLUSH); if (ret) { pending->error = ret; goto no_free_objectid; } } ret = btrfs_qgroup_inherit(trans, fs_info, root->root_key.objectid, objectid, pending->inherit); if (ret) { pending->error = ret; goto no_free_objectid; } key.objectid = objectid; key.offset = (u64)-1; key.type = BTRFS_ROOT_ITEM_KEY; rsv = trans->block_rsv; trans->block_rsv = &pending->block_rsv; dentry = pending->dentry; parent = dget_parent(dentry); parent_inode = parent->d_inode; parent_root = BTRFS_I(parent_inode)->root; record_root_in_trans(trans, parent_root); /* * insert the directory item */ ret = btrfs_set_inode_index(parent_inode, &index); BUG_ON(ret); /* -ENOMEM */ /* check if there is a file/dir which has the same name. */ dir_item = btrfs_lookup_dir_item(NULL, parent_root, path, btrfs_ino(parent_inode), dentry->d_name.name, dentry->d_name.len, 0); if (dir_item != NULL && !IS_ERR(dir_item)) { pending->error = -EEXIST; goto fail; } else if (IS_ERR(dir_item)) { ret = PTR_ERR(dir_item); btrfs_abort_transaction(trans, root, ret); goto fail; } btrfs_release_path(path); /* * pull in the delayed directory update * and the delayed inode item * otherwise we corrupt the FS during * snapshot */ ret = btrfs_run_delayed_items(trans, root); if (ret) { /* Transaction aborted */ btrfs_abort_transaction(trans, root, ret); goto fail; } record_root_in_trans(trans, root); btrfs_set_root_last_snapshot(&root->root_item, trans->transid); memcpy(new_root_item, &root->root_item, sizeof(*new_root_item)); btrfs_check_and_init_root_item(new_root_item); root_flags = btrfs_root_flags(new_root_item); if (pending->readonly) root_flags |= BTRFS_ROOT_SUBVOL_RDONLY; else root_flags &= ~BTRFS_ROOT_SUBVOL_RDONLY; btrfs_set_root_flags(new_root_item, root_flags); btrfs_set_root_generation_v2(new_root_item, trans->transid); uuid_le_gen(&new_uuid); memcpy(new_root_item->uuid, new_uuid.b, BTRFS_UUID_SIZE); memcpy(new_root_item->parent_uuid, root->root_item.uuid, BTRFS_UUID_SIZE); new_root_item->otime.sec = cpu_to_le64(cur_time.tv_sec); new_root_item->otime.nsec = cpu_to_le32(cur_time.tv_nsec); btrfs_set_root_otransid(new_root_item, trans->transid); memset(&new_root_item->stime, 0, sizeof(new_root_item->stime)); memset(&new_root_item->rtime, 0, sizeof(new_root_item->rtime)); btrfs_set_root_stransid(new_root_item, 0); btrfs_set_root_rtransid(new_root_item, 0); old = btrfs_lock_root_node(root); ret = btrfs_cow_block(trans, root, old, NULL, 0, &old); if (ret) { btrfs_tree_unlock(old); free_extent_buffer(old); btrfs_abort_transaction(trans, root, ret); goto fail; } btrfs_set_lock_blocking(old); ret = btrfs_copy_root(trans, root, old, &tmp, objectid); /* clean up in any case */ btrfs_tree_unlock(old); free_extent_buffer(old); if (ret) { btrfs_abort_transaction(trans, root, ret); goto fail; } /* see comments in should_cow_block() */ root->force_cow = 1; smp_wmb(); btrfs_set_root_node(new_root_item, tmp); /* record when the snapshot was created in key.offset */ key.offset = trans->transid; ret = btrfs_insert_root(trans, tree_root, &key, new_root_item); btrfs_tree_unlock(tmp); free_extent_buffer(tmp); if (ret) { btrfs_abort_transaction(trans, root, ret); goto fail; } /* * insert root back/forward references */ ret = btrfs_add_root_ref(trans, tree_root, objectid, parent_root->root_key.objectid, btrfs_ino(parent_inode), index, dentry->d_name.name, dentry->d_name.len); if (ret) { btrfs_abort_transaction(trans, root, ret); goto fail; } key.offset = (u64)-1; pending->snap = btrfs_read_fs_root_no_name(root->fs_info, &key); if (IS_ERR(pending->snap)) { ret = PTR_ERR(pending->snap); btrfs_abort_transaction(trans, root, ret); goto fail; } ret = btrfs_reloc_post_snapshot(trans, pending); if (ret) { btrfs_abort_transaction(trans, root, ret); goto fail; } ret = btrfs_run_delayed_refs(trans, root, (unsigned long)-1); if (ret) { btrfs_abort_transaction(trans, root, ret); goto fail; } ret = btrfs_insert_dir_item(trans, parent_root, dentry->d_name.name, dentry->d_name.len, parent_inode, &key, BTRFS_FT_DIR, index); /* We have check then name at the beginning, so it is impossible. */ BUG_ON(ret == -EEXIST || ret == -EOVERFLOW); if (ret) { btrfs_abort_transaction(trans, root, ret); goto fail; } btrfs_i_size_write(parent_inode, parent_inode->i_size + dentry->d_name.len * 2); parent_inode->i_mtime = parent_inode->i_ctime = CURRENT_TIME; ret = btrfs_update_inode_fallback(trans, parent_root, parent_inode); if (ret) btrfs_abort_transaction(trans, root, ret); fail: dput(parent); trans->block_rsv = rsv; no_free_objectid: kfree(new_root_item); root_item_alloc_fail: btrfs_free_path(path); path_alloc_fail: btrfs_block_rsv_release(root, &pending->block_rsv, (u64)-1); return ret; } /* * create all the snapshots we've scheduled for creation */ static noinline int create_pending_snapshots(struct btrfs_trans_handle *trans, struct btrfs_fs_info *fs_info) { struct btrfs_pending_snapshot *pending; struct list_head *head = &trans->transaction->pending_snapshots; list_for_each_entry(pending, head, list) create_pending_snapshot(trans, fs_info, pending); return 0; } static void update_super_roots(struct btrfs_root *root) { struct btrfs_root_item *root_item; struct btrfs_super_block *super; super = root->fs_info->super_copy; root_item = &root->fs_info->chunk_root->root_item; super->chunk_root = root_item->bytenr; super->chunk_root_generation = root_item->generation; super->chunk_root_level = root_item->level; root_item = &root->fs_info->tree_root->root_item; super->root = root_item->bytenr; super->generation = root_item->generation; super->root_level = root_item->level; if (btrfs_test_opt(root, SPACE_CACHE)) super->cache_generation = root_item->generation; } int btrfs_transaction_in_commit(struct btrfs_fs_info *info) { int ret = 0; spin_lock(&info->trans_lock); if (info->running_transaction) ret = info->running_transaction->in_commit; spin_unlock(&info->trans_lock); return ret; } int btrfs_transaction_blocked(struct btrfs_fs_info *info) { int ret = 0; spin_lock(&info->trans_lock); if (info->running_transaction) ret = info->running_transaction->blocked; spin_unlock(&info->trans_lock); return ret; } /* * wait for the current transaction commit to start and block subsequent * transaction joins */ static void wait_current_trans_commit_start(struct btrfs_root *root, struct btrfs_transaction *trans) { wait_event(root->fs_info->transaction_blocked_wait, trans->in_commit); } /* * wait for the current transaction to start and then become unblocked. * caller holds ref. */ static void wait_current_trans_commit_start_and_unblock(struct btrfs_root *root, struct btrfs_transaction *trans) { wait_event(root->fs_info->transaction_wait, trans->commit_done || (trans->in_commit && !trans->blocked)); } /* * commit transactions asynchronously. once btrfs_commit_transaction_async * returns, any subsequent transaction will not be allowed to join. */ struct btrfs_async_commit { struct btrfs_trans_handle *newtrans; struct btrfs_root *root; struct delayed_work work; }; static void do_async_commit(struct work_struct *work) { struct btrfs_async_commit *ac = container_of(work, struct btrfs_async_commit, work.work); /* * We've got freeze protection passed with the transaction. * Tell lockdep about it. */ if (ac->newtrans->type < TRANS_JOIN_NOLOCK) rwsem_acquire_read( &ac->root->fs_info->sb->s_writers.lock_map[SB_FREEZE_FS-1], 0, 1, _THIS_IP_); current->journal_info = ac->newtrans; btrfs_commit_transaction(ac->newtrans, ac->root); kfree(ac); } int btrfs_commit_transaction_async(struct btrfs_trans_handle *trans, struct btrfs_root *root, int wait_for_unblock) { struct btrfs_async_commit *ac; struct btrfs_transaction *cur_trans; ac = kmalloc(sizeof(*ac), GFP_NOFS); if (!ac) return -ENOMEM; INIT_DELAYED_WORK(&ac->work, do_async_commit); ac->root = root; ac->newtrans = btrfs_join_transaction(root); if (IS_ERR(ac->newtrans)) { int err = PTR_ERR(ac->newtrans); kfree(ac); return err; } /* take transaction reference */ cur_trans = trans->transaction; atomic_inc(&cur_trans->use_count); btrfs_end_transaction(trans, root); /* * Tell lockdep we've released the freeze rwsem, since the * async commit thread will be the one to unlock it. */ if (trans->type < TRANS_JOIN_NOLOCK) rwsem_release( &root->fs_info->sb->s_writers.lock_map[SB_FREEZE_FS-1], 1, _THIS_IP_); schedule_delayed_work(&ac->work, 0); /* wait for transaction to start and unblock */ if (wait_for_unblock) wait_current_trans_commit_start_and_unblock(root, cur_trans); else wait_current_trans_commit_start(root, cur_trans); if (current->journal_info == trans) current->journal_info = NULL; put_transaction(cur_trans); return 0; } static void cleanup_transaction(struct btrfs_trans_handle *trans, struct btrfs_root *root, int err) { struct btrfs_transaction *cur_trans = trans->transaction; WARN_ON(trans->use_count > 1); btrfs_abort_transaction(trans, root, err); spin_lock(&root->fs_info->trans_lock); list_del_init(&cur_trans->list); if (cur_trans == root->fs_info->running_transaction) { root->fs_info->running_transaction = NULL; root->fs_info->trans_no_join = 0; } spin_unlock(&root->fs_info->trans_lock); btrfs_cleanup_one_transaction(trans->transaction, root); put_transaction(cur_trans); put_transaction(cur_trans); trace_btrfs_transaction_commit(root); btrfs_scrub_continue(root); if (current->journal_info == trans) current->journal_info = NULL; kmem_cache_free(btrfs_trans_handle_cachep, trans); } static int btrfs_flush_all_pending_stuffs(struct btrfs_trans_handle *trans, struct btrfs_root *root) { int flush_on_commit = btrfs_test_opt(root, FLUSHONCOMMIT); int snap_pending = 0; int ret; if (!flush_on_commit) { spin_lock(&root->fs_info->trans_lock); if (!list_empty(&trans->transaction->pending_snapshots)) snap_pending = 1; spin_unlock(&root->fs_info->trans_lock); } if (flush_on_commit || snap_pending) { btrfs_start_delalloc_inodes(root, 1); btrfs_wait_ordered_extents(root, 1); } ret = btrfs_run_delayed_items(trans, root); if (ret) return ret; /* * running the delayed items may have added new refs. account * them now so that they hinder processing of more delayed refs * as little as possible. */ btrfs_delayed_refs_qgroup_accounting(trans, root->fs_info); /* * rename don't use btrfs_join_transaction, so, once we * set the transaction to blocked above, we aren't going * to get any new ordered operations. We can safely run * it here and no for sure that nothing new will be added * to the list */ btrfs_run_ordered_operations(root, 1); return 0; } /* * btrfs_transaction state sequence: * in_commit = 0, blocked = 0 (initial) * in_commit = 1, blocked = 1 * blocked = 0 * commit_done = 1 */ int btrfs_commit_transaction(struct btrfs_trans_handle *trans, struct btrfs_root *root) { unsigned long joined = 0; struct btrfs_transaction *cur_trans = trans->transaction; struct btrfs_transaction *prev_trans = NULL; DEFINE_WAIT(wait); int ret; int should_grow = 0; unsigned long now = get_seconds(); ret = btrfs_run_ordered_operations(root, 0); if (ret) { btrfs_abort_transaction(trans, root, ret); goto cleanup_transaction; } if (cur_trans->aborted) { ret = cur_trans->aborted; goto cleanup_transaction; } /* make a pass through all the delayed refs we have so far * any runnings procs may add more while we are here */ ret = btrfs_run_delayed_refs(trans, root, 0); if (ret) goto cleanup_transaction; btrfs_trans_release_metadata(trans, root); trans->block_rsv = NULL; cur_trans = trans->transaction; /* * set the flushing flag so procs in this transaction have to * start sending their work down. */ cur_trans->delayed_refs.flushing = 1; if (!list_empty(&trans->new_bgs)) btrfs_create_pending_block_groups(trans, root); ret = btrfs_run_delayed_refs(trans, root, 0); if (ret) goto cleanup_transaction; spin_lock(&cur_trans->commit_lock); if (cur_trans->in_commit) { spin_unlock(&cur_trans->commit_lock); atomic_inc(&cur_trans->use_count); ret = btrfs_end_transaction(trans, root); wait_for_commit(root, cur_trans); put_transaction(cur_trans); return ret; } trans->transaction->in_commit = 1; trans->transaction->blocked = 1; spin_unlock(&cur_trans->commit_lock); wake_up(&root->fs_info->transaction_blocked_wait); spin_lock(&root->fs_info->trans_lock); if (cur_trans->list.prev != &root->fs_info->trans_list) { prev_trans = list_entry(cur_trans->list.prev, struct btrfs_transaction, list); if (!prev_trans->commit_done) { atomic_inc(&prev_trans->use_count); spin_unlock(&root->fs_info->trans_lock); wait_for_commit(root, prev_trans); put_transaction(prev_trans); } else { spin_unlock(&root->fs_info->trans_lock); } } else { spin_unlock(&root->fs_info->trans_lock); } if (!btrfs_test_opt(root, SSD) && (now < cur_trans->start_time || now - cur_trans->start_time < 1)) should_grow = 1; do { joined = cur_trans->num_joined; WARN_ON(cur_trans != trans->transaction); ret = btrfs_flush_all_pending_stuffs(trans, root); if (ret) goto cleanup_transaction; prepare_to_wait(&cur_trans->writer_wait, &wait, TASK_UNINTERRUPTIBLE); if (atomic_read(&cur_trans->num_writers) > 1) schedule_timeout(MAX_SCHEDULE_TIMEOUT); else if (should_grow) schedule_timeout(1); finish_wait(&cur_trans->writer_wait, &wait); } while (atomic_read(&cur_trans->num_writers) > 1 || (should_grow && cur_trans->num_joined != joined)); ret = btrfs_flush_all_pending_stuffs(trans, root); if (ret) goto cleanup_transaction; /* * Ok now we need to make sure to block out any other joins while we * commit the transaction. We could have started a join before setting * no_join so make sure to wait for num_writers to == 1 again. */ spin_lock(&root->fs_info->trans_lock); root->fs_info->trans_no_join = 1; spin_unlock(&root->fs_info->trans_lock); wait_event(cur_trans->writer_wait, atomic_read(&cur_trans->num_writers) == 1); /* * the reloc mutex makes sure that we stop * the balancing code from coming in and moving * extents around in the middle of the commit */ mutex_lock(&root->fs_info->reloc_mutex); /* * We needn't worry about the delayed items because we will * deal with them in create_pending_snapshot(), which is the * core function of the snapshot creation. */ ret = create_pending_snapshots(trans, root->fs_info); if (ret) { mutex_unlock(&root->fs_info->reloc_mutex); goto cleanup_transaction; } /* * We insert the dir indexes of the snapshots and update the inode * of the snapshots' parents after the snapshot creation, so there * are some delayed items which are not dealt with. Now deal with * them. * * We needn't worry that this operation will corrupt the snapshots, * because all the tree which are snapshoted will be forced to COW * the nodes and leaves. */ ret = btrfs_run_delayed_items(trans, root); if (ret) { mutex_unlock(&root->fs_info->reloc_mutex); goto cleanup_transaction; } ret = btrfs_run_delayed_refs(trans, root, (unsigned long)-1); if (ret) { mutex_unlock(&root->fs_info->reloc_mutex); goto cleanup_transaction; } /* * make sure none of the code above managed to slip in a * delayed item */ btrfs_assert_delayed_root_empty(root); WARN_ON(cur_trans != trans->transaction); btrfs_scrub_pause(root); /* btrfs_commit_tree_roots is responsible for getting the * various roots consistent with each other. Every pointer * in the tree of tree roots has to point to the most up to date * root for every subvolume and other tree. So, we have to keep * the tree logging code from jumping in and changing any * of the trees. * * At this point in the commit, there can't be any tree-log * writers, but a little lower down we drop the trans mutex * and let new people in. By holding the tree_log_mutex * from now until after the super is written, we avoid races * with the tree-log code. */ mutex_lock(&root->fs_info->tree_log_mutex); ret = commit_fs_roots(trans, root); if (ret) { mutex_unlock(&root->fs_info->tree_log_mutex); mutex_unlock(&root->fs_info->reloc_mutex); goto cleanup_transaction; } /* commit_fs_roots gets rid of all the tree log roots, it is now * safe to free the root of tree log roots */ btrfs_free_log_root_tree(trans, root->fs_info); ret = commit_cowonly_roots(trans, root); if (ret) { mutex_unlock(&root->fs_info->tree_log_mutex); mutex_unlock(&root->fs_info->reloc_mutex); goto cleanup_transaction; } btrfs_prepare_extent_commit(trans, root); cur_trans = root->fs_info->running_transaction; btrfs_set_root_node(&root->fs_info->tree_root->root_item, root->fs_info->tree_root->node); switch_commit_root(root->fs_info->tree_root); btrfs_set_root_node(&root->fs_info->chunk_root->root_item, root->fs_info->chunk_root->node); switch_commit_root(root->fs_info->chunk_root); assert_qgroups_uptodate(trans); update_super_roots(root); if (!root->fs_info->log_root_recovering) { btrfs_set_super_log_root(root->fs_info->super_copy, 0); btrfs_set_super_log_root_level(root->fs_info->super_copy, 0); } memcpy(root->fs_info->super_for_commit, root->fs_info->super_copy, sizeof(*root->fs_info->super_copy)); trans->transaction->blocked = 0; spin_lock(&root->fs_info->trans_lock); root->fs_info->running_transaction = NULL; root->fs_info->trans_no_join = 0; spin_unlock(&root->fs_info->trans_lock); mutex_unlock(&root->fs_info->reloc_mutex); wake_up(&root->fs_info->transaction_wait); ret = btrfs_write_and_wait_transaction(trans, root); if (ret) { btrfs_error(root->fs_info, ret, "Error while writing out transaction."); mutex_unlock(&root->fs_info->tree_log_mutex); goto cleanup_transaction; } ret = write_ctree_super(trans, root, 0); if (ret) { mutex_unlock(&root->fs_info->tree_log_mutex); goto cleanup_transaction; } /* * the super is written, we can safely allow the tree-loggers * to go about their business */ mutex_unlock(&root->fs_info->tree_log_mutex); btrfs_finish_extent_commit(trans, root); cur_trans->commit_done = 1; root->fs_info->last_trans_committed = cur_trans->transid; wake_up(&cur_trans->commit_wait); spin_lock(&root->fs_info->trans_lock); list_del_init(&cur_trans->list); spin_unlock(&root->fs_info->trans_lock); put_transaction(cur_trans); put_transaction(cur_trans); if (trans->type < TRANS_JOIN_NOLOCK) sb_end_intwrite(root->fs_info->sb); trace_btrfs_transaction_commit(root); btrfs_scrub_continue(root); if (current->journal_info == trans) current->journal_info = NULL; kmem_cache_free(btrfs_trans_handle_cachep, trans); if (current != root->fs_info->transaction_kthread) btrfs_run_delayed_iputs(root); return ret; cleanup_transaction: btrfs_trans_release_metadata(trans, root); trans->block_rsv = NULL; btrfs_printk(root->fs_info, "Skipping commit of aborted transaction.\n"); // WARN_ON(1); if (current->journal_info == trans) current->journal_info = NULL; cleanup_transaction(trans, root, ret); return ret; } /* * interface function to delete all the snapshots we have scheduled for deletion */ int btrfs_clean_old_snapshots(struct btrfs_root *root) { LIST_HEAD(list); struct btrfs_fs_info *fs_info = root->fs_info; spin_lock(&fs_info->trans_lock); list_splice_init(&fs_info->dead_roots, &list); spin_unlock(&fs_info->trans_lock); while (!list_empty(&list)) { int ret; root = list_entry(list.next, struct btrfs_root, root_list); list_del(&root->root_list); btrfs_kill_all_delayed_nodes(root); if (btrfs_header_backref_rev(root->node) < BTRFS_MIXED_BACKREF_REV) ret = btrfs_drop_snapshot(root, NULL, 0, 0); else ret =btrfs_drop_snapshot(root, NULL, 1, 0); BUG_ON(ret < 0); } return 0; }
./CrossVul/dataset_final_sorted/CWE-310/c/good_3783_4
crossvul-cpp_data_bad_5867_0
/* X-Chat * Copyright (C) 1998 Peter Zelezny. * * 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 St, Fifth Floor, Boston, MA 02110-1301, USA * * MS Proxy (ISA server) support is (c) 2006 Pavel Fedin <sonic_amiga@rambler.ru> * based on Dante source code * Copyright (c) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 * Inferno Nettverk A/S, Norway. All rights reserved. */ /*#define DEBUG_MSPROXY*/ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <fcntl.h> #define WANTSOCKET #define WANTARPA #include "inet.h" #ifdef WIN32 #include <winbase.h> #include <io.h> #else #include <signal.h> #include <sys/wait.h> #include <unistd.h> #endif #include "hexchat.h" #include "fe.h" #include "cfgfiles.h" #include "network.h" #include "notify.h" #include "hexchatc.h" #include "inbound.h" #include "outbound.h" #include "text.h" #include "util.h" #include "url.h" #include "proto-irc.h" #include "servlist.h" #include "server.h" #ifdef USE_OPENSSL #include <openssl/ssl.h> /* SSL_() */ #include <openssl/err.h> /* ERR_() */ #include "ssl.h" #endif #ifdef USE_MSPROXY #include "msproxy.h" #endif #ifdef WIN32 #include "identd.h" #endif #ifdef USE_LIBPROXY #include <proxy.h> #endif #ifdef USE_OPENSSL /* local variables */ static struct session *g_sess = NULL; #endif static GSList *away_list = NULL; GSList *serv_list = NULL; static void auto_reconnect (server *serv, int send_quit, int err); static void server_disconnect (session * sess, int sendquit, int err); static int server_cleanup (server * serv); static void server_connect (server *serv, char *hostname, int port, int no_login); #ifdef USE_LIBPROXY extern pxProxyFactory *libproxy_factory; #endif /* actually send to the socket. This might do a character translation or send via SSL. server/dcc both use this function. */ int tcp_send_real (void *ssl, int sok, char *encoding, int using_irc, char *buf, int len) { int ret; char *locale; gsize loc_len; if (encoding == NULL) /* system */ { locale = NULL; if (!prefs.utf8_locale) { const gchar *charset; g_get_charset (&charset); locale = g_convert_with_fallback (buf, len, charset, "UTF-8", "?", 0, &loc_len, 0); } } else { if (using_irc) /* using "IRC" encoding (CP1252/UTF-8 hybrid) */ /* if all chars fit inside CP1252, use that. Otherwise this returns NULL and we send UTF-8. */ locale = g_convert (buf, len, "CP1252", "UTF-8", 0, &loc_len, 0); else locale = g_convert_with_fallback (buf, len, encoding, "UTF-8", "?", 0, &loc_len, 0); } if (locale) { len = loc_len; #ifdef USE_OPENSSL if (!ssl) ret = send (sok, locale, len, 0); else ret = _SSL_send (ssl, locale, len); #else ret = send (sok, locale, len, 0); #endif g_free (locale); } else { #ifdef USE_OPENSSL if (!ssl) ret = send (sok, buf, len, 0); else ret = _SSL_send (ssl, buf, len); #else ret = send (sok, buf, len, 0); #endif } return ret; } static int server_send_real (server *serv, char *buf, int len) { fe_add_rawlog (serv, buf, len, TRUE); url_check_line (buf, len); return tcp_send_real (serv->ssl, serv->sok, serv->encoding, serv->using_irc, buf, len); } /* new throttling system, uses the same method as the Undernet ircu2.10 server; under test, a 200-line paste didn't flood off the client */ static int tcp_send_queue (server *serv) { char *buf, *p; int len, i, pri; GSList *list; time_t now = time (0); /* did the server close since the timeout was added? */ if (!is_server (serv)) return 0; /* try priority 2,1,0 */ pri = 2; while (pri >= 0) { list = serv->outbound_queue; while (list) { buf = (char *) list->data; if (buf[0] == pri) { buf++; /* skip the priority byte */ len = strlen (buf); if (serv->next_send < now) serv->next_send = now; if (serv->next_send - now >= 10) { /* check for clock skew */ if (now >= serv->prev_now) return 1; /* don't remove the timeout handler */ /* it is skewed, reset to something sane */ serv->next_send = now; } for (p = buf, i = len; i && *p != ' '; p++, i--); serv->next_send += (2 + i / 120); serv->sendq_len -= len; serv->prev_now = now; fe_set_throttle (serv); server_send_real (serv, buf, len); buf--; serv->outbound_queue = g_slist_remove (serv->outbound_queue, buf); free (buf); list = serv->outbound_queue; } else { list = list->next; } } /* now try pri 0 */ pri--; } return 0; /* remove the timeout handler */ } int tcp_send_len (server *serv, char *buf, int len) { char *dbuf; int noqueue = !serv->outbound_queue; if (!prefs.hex_net_throttle) return server_send_real (serv, buf, len); dbuf = malloc (len + 2); /* first byte is the priority */ dbuf[0] = 2; /* pri 2 for most things */ memcpy (dbuf + 1, buf, len); dbuf[len + 1] = 0; /* privmsg and notice get a lower priority */ if (g_ascii_strncasecmp (dbuf + 1, "PRIVMSG", 7) == 0 || g_ascii_strncasecmp (dbuf + 1, "NOTICE", 6) == 0) { dbuf[0] = 1; } else { /* WHO/MODE get the lowest priority */ if (g_ascii_strncasecmp (dbuf + 1, "WHO ", 4) == 0 || /* but only MODE queries, not changes */ (g_ascii_strncasecmp (dbuf + 1, "MODE", 4) == 0 && strchr (dbuf, '-') == NULL && strchr (dbuf, '+') == NULL)) dbuf[0] = 0; } serv->outbound_queue = g_slist_append (serv->outbound_queue, dbuf); serv->sendq_len += len; /* tcp_send_queue uses strlen */ if (tcp_send_queue (serv) && noqueue) fe_timeout_add (500, tcp_send_queue, serv); return 1; } /*int tcp_send (server *serv, char *buf) { return tcp_send_len (serv, buf, strlen (buf)); }*/ void tcp_sendf (server *serv, const char *fmt, ...) { va_list args; /* keep this buffer in BSS. Converting UTF-8 to ISO-8859-x might make the string shorter, so allow alot more than 512 for now. */ static char send_buf[1540]; /* good code hey (no it's not overflowable) */ int len; va_start (args, fmt); len = vsnprintf (send_buf, sizeof (send_buf) - 1, fmt, args); va_end (args); send_buf[sizeof (send_buf) - 1] = '\0'; if (len < 0 || len > (sizeof (send_buf) - 1)) len = strlen (send_buf); tcp_send_len (serv, send_buf, len); } static int close_socket_cb (gpointer sok) { closesocket (GPOINTER_TO_INT (sok)); return 0; } static void close_socket (int sok) { /* close the socket in 5 seconds so the QUIT message is not lost */ fe_timeout_add (5000, close_socket_cb, GINT_TO_POINTER (sok)); } /* handle 1 line of text received from the server */ static void server_inline (server *serv, char *line, int len) { char *utf_line_allocated = NULL; /* Checks whether we're set to use UTF-8 charset */ if (serv->using_irc || /* 1. using CP1252/UTF-8 Hybrid */ (serv->encoding == NULL && prefs.utf8_locale) || /* OR 2. using system default->UTF-8 */ (serv->encoding != NULL && /* OR 3. explicitly set to UTF-8 */ (g_ascii_strcasecmp (serv->encoding, "UTF8") == 0 || g_ascii_strcasecmp (serv->encoding, "UTF-8") == 0))) { /* The user has the UTF-8 charset set, either via /charset command or from his UTF-8 locale. Thus, we first try the UTF-8 charset, and if we fail to convert, we assume it to be ISO-8859-1 (see text_validate). */ utf_line_allocated = text_validate (&line, &len); } else { /* Since the user has an explicit charset set, either via /charset command or from his non-UTF8 locale, we don't fallback to ISO-8859-1 and instead try to remove errnoeous octets till the string is convertable in the said charset. */ const char *encoding = NULL; if (serv->encoding != NULL) encoding = serv->encoding; else g_get_charset (&encoding); if (encoding != NULL) { char *conv_line; /* holds a copy of the original string */ int conv_len; /* tells g_convert how much of line to convert */ gsize utf_len; gsize read_len; GError *err; gboolean retry; conv_line = g_malloc (len + 1); memcpy (conv_line, line, len); conv_line[len] = 0; conv_len = len; /* if CP1255, convert it with the NUL terminator. Works around SF bug #1122089 */ if (serv->using_cp1255) conv_len++; do { err = NULL; retry = FALSE; utf_line_allocated = g_convert_with_fallback (conv_line, conv_len, "UTF-8", encoding, "?", &read_len, &utf_len, &err); if (err != NULL) { if (err->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE && conv_len > (read_len + 1)) { /* Make our best bet by removing the erroneous char. This will work for casual 8-bit strings with non-standard chars. */ memmove (conv_line + read_len, conv_line + read_len + 1, conv_len - read_len -1); conv_len--; retry = TRUE; } g_error_free (err); } } while (retry); g_free (conv_line); /* If any conversion has occured at all. Conversion might fail due to errors other than invalid sequences, e.g. unknown charset. */ if (utf_line_allocated != NULL) { line = utf_line_allocated; len = utf_len; if (serv->using_cp1255 && len > 0) len--; } else { /* If all fails, treat as UTF-8 with fallback to ISO-8859-1. */ utf_line_allocated = text_validate (&line, &len); } } } fe_add_rawlog (serv, line, len, FALSE); /* let proto-irc.c handle it */ serv->p_inline (serv, line, len); if (utf_line_allocated != NULL) /* only if a special copy was allocated */ g_free (utf_line_allocated); } /* read data from socket */ static gboolean server_read (GIOChannel *source, GIOCondition condition, server *serv) { int sok = serv->sok; int error, i, len; char lbuf[2050]; while (1) { #ifdef USE_OPENSSL if (!serv->ssl) #endif len = recv (sok, lbuf, sizeof (lbuf) - 2, 0); #ifdef USE_OPENSSL else len = _SSL_recv (serv->ssl, lbuf, sizeof (lbuf) - 2); #endif if (len < 1) { error = 0; if (len < 0) { if (would_block ()) return TRUE; error = sock_error (); } if (!serv->end_of_motd) { server_disconnect (serv->server_session, FALSE, error); if (!servlist_cycle (serv)) { if (prefs.hex_net_auto_reconnect) auto_reconnect (serv, FALSE, error); } } else { if (prefs.hex_net_auto_reconnect) auto_reconnect (serv, FALSE, error); else server_disconnect (serv->server_session, FALSE, error); } return TRUE; } i = 0; lbuf[len] = 0; while (i < len) { switch (lbuf[i]) { case '\r': break; case '\n': serv->linebuf[serv->pos] = 0; server_inline (serv, serv->linebuf, serv->pos); serv->pos = 0; break; default: serv->linebuf[serv->pos] = lbuf[i]; if (serv->pos >= (sizeof (serv->linebuf) - 1)) fprintf (stderr, "*** HEXCHAT WARNING: Buffer overflow - shit server!\n"); else serv->pos++; } i++; } } } static void server_connected (server * serv) { prefs.wait_on_exit = TRUE; serv->ping_recv = time (0); serv->lag_sent = 0; serv->connected = TRUE; set_nonblocking (serv->sok); serv->iotag = fe_input_add (serv->sok, FIA_READ|FIA_EX, server_read, serv); if (!serv->no_login) { EMIT_SIGNAL (XP_TE_CONNECTED, serv->server_session, NULL, NULL, NULL, NULL, 0); if (serv->network) { serv->p_login (serv, (!(((ircnet *)serv->network)->flags & FLAG_USE_GLOBAL) && (((ircnet *)serv->network)->user)) ? (((ircnet *)serv->network)->user) : prefs.hex_irc_user_name, (!(((ircnet *)serv->network)->flags & FLAG_USE_GLOBAL) && (((ircnet *)serv->network)->real)) ? (((ircnet *)serv->network)->real) : prefs.hex_irc_real_name); } else { serv->p_login (serv, prefs.hex_irc_user_name, prefs.hex_irc_real_name); } } else { EMIT_SIGNAL (XP_TE_SERVERCONNECTED, serv->server_session, NULL, NULL, NULL, NULL, 0); } server_set_name (serv, serv->servername); fe_server_event (serv, FE_SE_CONNECT, 0); } #ifdef WIN32 static gboolean server_close_pipe (int *pipefd) /* see comments below */ { close (pipefd[0]); /* close WRITE end first to cause an EOF on READ */ close (pipefd[1]); /* in giowin32, and end that thread. */ free (pipefd); return FALSE; } #endif static void server_stopconnecting (server * serv) { if (serv->iotag) { fe_input_remove (serv->iotag); serv->iotag = 0; } if (serv->joindelay_tag) { fe_timeout_remove (serv->joindelay_tag); serv->joindelay_tag = 0; } #ifndef WIN32 /* kill the child process trying to connect */ kill (serv->childpid, SIGKILL); waitpid (serv->childpid, NULL, 0); close (serv->childwrite); close (serv->childread); #else PostThreadMessage (serv->childpid, WM_QUIT, 0, 0); { /* if we close the pipe now, giowin32 will crash. */ int *pipefd = malloc (sizeof (int) * 2); pipefd[0] = serv->childwrite; pipefd[1] = serv->childread; g_idle_add ((GSourceFunc)server_close_pipe, pipefd); } #endif #ifdef USE_OPENSSL if (serv->ssl_do_connect_tag) { fe_timeout_remove (serv->ssl_do_connect_tag); serv->ssl_do_connect_tag = 0; } #endif fe_progressbar_end (serv); serv->connecting = FALSE; fe_server_event (serv, FE_SE_DISCONNECT, 0); } #ifdef USE_OPENSSL #define SSLTMOUT 90 /* seconds */ static void ssl_cb_info (SSL * s, int where, int ret) { /* char buf[128];*/ return; /* FIXME: make debug level adjustable in serverlist or settings */ /* snprintf (buf, sizeof (buf), "%s (%d)", SSL_state_string_long (s), where); if (g_sess) EMIT_SIGNAL (XP_TE_SSLMESSAGE, g_sess, buf, NULL, NULL, NULL, 0); else fprintf (stderr, "%s\n", buf);*/ } static int ssl_cb_verify (int ok, X509_STORE_CTX * ctx) { char subject[256]; char issuer[256]; char buf[512]; X509_NAME_oneline (X509_get_subject_name (ctx->current_cert), subject, sizeof (subject)); X509_NAME_oneline (X509_get_issuer_name (ctx->current_cert), issuer, sizeof (issuer)); snprintf (buf, sizeof (buf), "* Subject: %s", subject); EMIT_SIGNAL (XP_TE_SSLMESSAGE, g_sess, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), "* Issuer: %s", issuer); EMIT_SIGNAL (XP_TE_SSLMESSAGE, g_sess, buf, NULL, NULL, NULL, 0); return (TRUE); /* always ok */ } static int ssl_do_connect (server * serv) { char buf[128]; g_sess = serv->server_session; if (SSL_connect (serv->ssl) <= 0) { char err_buf[128]; int err; g_sess = NULL; if ((err = ERR_get_error ()) > 0) { ERR_error_string (err, err_buf); snprintf (buf, sizeof (buf), "(%d) %s", err, err_buf); EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); if (ERR_GET_REASON (err) == SSL_R_WRONG_VERSION_NUMBER) PrintText (serv->server_session, _("Are you sure this is a SSL capable server and port?\n")); server_cleanup (serv); if (prefs.hex_net_auto_reconnectonfail) auto_reconnect (serv, FALSE, -1); return (0); /* remove it (0) */ } } g_sess = NULL; if (SSL_is_init_finished (serv->ssl)) { struct cert_info cert_info; struct chiper_info *chiper_info; int verify_error; int i; if (!_SSL_get_cert_info (&cert_info, serv->ssl)) { snprintf (buf, sizeof (buf), "* Certification info:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Subject:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); for (i = 0; cert_info.subject_word[i]; i++) { snprintf (buf, sizeof (buf), " %s", cert_info.subject_word[i]); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } snprintf (buf, sizeof (buf), " Issuer:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); for (i = 0; cert_info.issuer_word[i]; i++) { snprintf (buf, sizeof (buf), " %s", cert_info.issuer_word[i]); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } snprintf (buf, sizeof (buf), " Public key algorithm: %s (%d bits)", cert_info.algorithm, cert_info.algorithm_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); /*if (cert_info.rsa_tmp_bits) { snprintf (buf, sizeof (buf), " Public key algorithm uses ephemeral key with %d bits", cert_info.rsa_tmp_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); }*/ snprintf (buf, sizeof (buf), " Sign algorithm %s", cert_info.sign_algorithm/*, cert_info.sign_algorithm_bits*/); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Valid since %s to %s", cert_info.notbefore, cert_info.notafter); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } else { snprintf (buf, sizeof (buf), " * No Certificate"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); } chiper_info = _SSL_get_cipher_info (serv->ssl); /* static buffer */ snprintf (buf, sizeof (buf), "* Cipher info:"); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); snprintf (buf, sizeof (buf), " Version: %s, cipher %s (%u bits)", chiper_info->version, chiper_info->chiper, chiper_info->chiper_bits); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); verify_error = SSL_get_verify_result (serv->ssl); switch (verify_error) { case X509_V_OK: /* snprintf (buf, sizeof (buf), "* Verify OK (?)"); */ /* EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); */ break; case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: case X509_V_ERR_CERT_HAS_EXPIRED: if (serv->accept_invalid_cert) { snprintf (buf, sizeof (buf), "* Verify E: %s.? (%d) -- Ignored", X509_verify_cert_error_string (verify_error), verify_error); EMIT_SIGNAL (XP_TE_SSLMESSAGE, serv->server_session, buf, NULL, NULL, NULL, 0); break; } default: snprintf (buf, sizeof (buf), "%s.? (%d)", X509_verify_cert_error_string (verify_error), verify_error); EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); server_cleanup (serv); return (0); } server_stopconnecting (serv); /* activate gtk poll */ server_connected (serv); return (0); /* remove it (0) */ } else { if (serv->ssl->session && serv->ssl->session->time + SSLTMOUT < time (NULL)) { snprintf (buf, sizeof (buf), "SSL handshake timed out"); EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, buf, NULL, NULL, NULL, 0); server_cleanup (serv); /* ->connecting = FALSE */ if (prefs.hex_net_auto_reconnectonfail) auto_reconnect (serv, FALSE, -1); return (0); /* remove it (0) */ } return (1); /* call it more (1) */ } } #endif static int timeout_auto_reconnect (server *serv) { if (is_server (serv)) /* make sure it hasnt been closed during the delay */ { serv->recondelay_tag = 0; if (!serv->connected && !serv->connecting && serv->server_session) { server_connect (serv, serv->hostname, serv->port, FALSE); } } return 0; /* returning 0 should remove the timeout handler */ } static void auto_reconnect (server *serv, int send_quit, int err) { session *s; GSList *list; int del; if (serv->server_session == NULL) return; list = sess_list; while (list) /* make sure auto rejoin can work */ { s = list->data; if (s->type == SESS_CHANNEL && s->channel[0]) { strcpy (s->waitchannel, s->channel); strcpy (s->willjoinchannel, s->channel); } list = list->next; } if (serv->connected) server_disconnect (serv->server_session, send_quit, err); del = prefs.hex_net_reconnect_delay * 1000; if (del < 1000) del = 500; /* so it doesn't block the gui */ #ifndef WIN32 if (err == -1 || err == 0 || err == ECONNRESET || err == ETIMEDOUT) #else if (err == -1 || err == 0 || err == WSAECONNRESET || err == WSAETIMEDOUT) #endif serv->reconnect_away = serv->is_away; /* is this server in a reconnect delay? remove it! */ if (serv->recondelay_tag) { fe_timeout_remove (serv->recondelay_tag); serv->recondelay_tag = 0; } serv->recondelay_tag = fe_timeout_add (del, timeout_auto_reconnect, serv); fe_server_event (serv, FE_SE_RECONDELAY, del); } static void server_flush_queue (server *serv) { list_free (&serv->outbound_queue); serv->sendq_len = 0; fe_set_throttle (serv); } /* connect() successed */ static void server_connect_success (server *serv) { #ifdef USE_OPENSSL #define SSLDOCONNTMOUT 300 if (serv->use_ssl) { char *err; /* it'll be a memory leak, if connection isn't terminated by server_cleanup() */ serv->ssl = _SSL_socket (serv->ctx, serv->sok); if ((err = _SSL_set_verify (serv->ctx, ssl_cb_verify, NULL))) { EMIT_SIGNAL (XP_TE_CONNFAIL, serv->server_session, err, NULL, NULL, NULL, 0); server_cleanup (serv); /* ->connecting = FALSE */ return; } /* FIXME: it'll be needed by new servers */ /* send(serv->sok, "STLS\r\n", 6, 0); sleep(1); */ set_nonblocking (serv->sok); serv->ssl_do_connect_tag = fe_timeout_add (SSLDOCONNTMOUT, ssl_do_connect, serv); return; } serv->ssl = NULL; #endif server_stopconnecting (serv); /* ->connecting = FALSE */ /* activate glib poll */ server_connected (serv); } /* receive info from the child-process about connection progress */ static gboolean server_read_child (GIOChannel *source, GIOCondition condition, server *serv) { session *sess = serv->server_session; char tbuf[128]; char outbuf[512]; char host[100]; char ip[100]; #ifdef USE_MSPROXY char *p; #endif waitline2 (source, tbuf, sizeof tbuf); switch (tbuf[0]) { case '0': /* print some text */ waitline2 (source, tbuf, sizeof tbuf); PrintText (serv->server_session, tbuf); break; case '1': /* unknown host */ server_stopconnecting (serv); closesocket (serv->sok4); if (serv->proxy_sok4 != -1) closesocket (serv->proxy_sok4); #ifdef USE_IPV6 if (serv->sok6 != -1) closesocket (serv->sok6); if (serv->proxy_sok6 != -1) closesocket (serv->proxy_sok6); #endif EMIT_SIGNAL (XP_TE_UKNHOST, sess, NULL, NULL, NULL, NULL, 0); if (!servlist_cycle (serv)) if (prefs.hex_net_auto_reconnectonfail) auto_reconnect (serv, FALSE, -1); break; case '2': /* connection failed */ waitline2 (source, tbuf, sizeof tbuf); server_stopconnecting (serv); closesocket (serv->sok4); if (serv->proxy_sok4 != -1) closesocket (serv->proxy_sok4); #ifdef USE_IPV6 if (serv->sok6 != -1) closesocket (serv->sok6); if (serv->proxy_sok6 != -1) closesocket (serv->proxy_sok6); #endif EMIT_SIGNAL (XP_TE_CONNFAIL, sess, errorstring (atoi (tbuf)), NULL, NULL, NULL, 0); if (!servlist_cycle (serv)) if (prefs.hex_net_auto_reconnectonfail) auto_reconnect (serv, FALSE, -1); break; case '3': /* gethostbyname finished */ waitline2 (source, host, sizeof host); waitline2 (source, ip, sizeof ip); waitline2 (source, outbuf, sizeof outbuf); EMIT_SIGNAL (XP_TE_CONNECT, sess, host, ip, outbuf, NULL, 0); #ifdef WIN32 if (prefs.hex_identd) { if (serv->network && ((ircnet *)serv->network)->user) { identd_start (((ircnet *)serv->network)->user); } else { identd_start (prefs.hex_irc_user_name); } } #else snprintf (outbuf, sizeof (outbuf), "%s/auth/xchat_auth", g_get_home_dir ()); if (access (outbuf, X_OK) == 0) { snprintf (outbuf, sizeof (outbuf), "exec -d %s/auth/xchat_auth %s", g_get_home_dir (), prefs.hex_irc_user_name); handle_command (serv->server_session, outbuf, FALSE); } #endif break; case '4': /* success */ waitline2 (source, tbuf, sizeof (tbuf)); #ifdef USE_MSPROXY serv->sok = strtol (tbuf, &p, 10); if (*p++ == ' ') { serv->proxy_sok = strtol (p, &p, 10); serv->msp_state.clientid = strtol (++p, &p, 10); serv->msp_state.serverid = strtol (++p, &p, 10); serv->msp_state.seq_sent = atoi (++p); } else serv->proxy_sok = -1; #ifdef DEBUG_MSPROXY printf ("Parent got main socket: %d, proxy socket: %d\n", serv->sok, serv->proxy_sok); printf ("Client ID 0x%08x server ID 0x%08x seq_sent %d\n", serv->msp_state.clientid, serv->msp_state.serverid, serv->msp_state.seq_sent); #endif #else serv->sok = atoi (tbuf); #endif #ifdef USE_IPV6 /* close the one we didn't end up using */ if (serv->sok == serv->sok4) closesocket (serv->sok6); else closesocket (serv->sok4); if (serv->proxy_sok != -1) { if (serv->proxy_sok == serv->proxy_sok4) closesocket (serv->proxy_sok6); else closesocket (serv->proxy_sok4); } #endif server_connect_success (serv); break; case '5': /* prefs ip discovered */ waitline2 (source, tbuf, sizeof tbuf); prefs.local_ip = inet_addr (tbuf); break; case '7': /* gethostbyname (prefs.hex_net_bind_host) failed */ sprintf (outbuf, _("Cannot resolve hostname %s\nCheck your IP Settings!\n"), prefs.hex_net_bind_host); PrintText (sess, outbuf); break; case '8': PrintText (sess, _("Proxy traversal failed.\n")); server_disconnect (sess, FALSE, -1); break; case '9': waitline2 (source, tbuf, sizeof tbuf); EMIT_SIGNAL (XP_TE_SERVERLOOKUP, sess, tbuf, NULL, NULL, NULL, 0); break; } return TRUE; } /* kill all sockets & iotags of a server. Stop a connection attempt, or disconnect if already connected. */ static int server_cleanup (server * serv) { fe_set_lag (serv, 0); if (serv->iotag) { fe_input_remove (serv->iotag); serv->iotag = 0; } if (serv->joindelay_tag) { fe_timeout_remove (serv->joindelay_tag); serv->joindelay_tag = 0; } #ifdef USE_OPENSSL if (serv->ssl) { SSL_shutdown (serv->ssl); SSL_free (serv->ssl); serv->ssl = NULL; } #endif if (serv->connecting) { server_stopconnecting (serv); closesocket (serv->sok4); if (serv->proxy_sok4 != -1) closesocket (serv->proxy_sok4); if (serv->sok6 != -1) closesocket (serv->sok6); if (serv->proxy_sok6 != -1) closesocket (serv->proxy_sok6); return 1; } if (serv->connected) { close_socket (serv->sok); if (serv->proxy_sok) close_socket (serv->proxy_sok); serv->connected = FALSE; serv->end_of_motd = FALSE; return 2; } /* is this server in a reconnect delay? remove it! */ if (serv->recondelay_tag) { fe_timeout_remove (serv->recondelay_tag); serv->recondelay_tag = 0; return 3; } return 0; } static void server_disconnect (session * sess, int sendquit, int err) { server *serv = sess->server; GSList *list; char tbuf[64]; gboolean shutup = FALSE; /* send our QUIT reason */ if (sendquit && serv->connected) { server_sendquit (sess); } fe_server_event (serv, FE_SE_DISCONNECT, 0); /* close all sockets & io tags */ switch (server_cleanup (serv)) { case 0: /* it wasn't even connected! */ notc_msg (sess); return; case 1: /* it was in the process of connecting */ sprintf (tbuf, "%d", sess->server->childpid); EMIT_SIGNAL (XP_TE_STOPCONNECT, sess, tbuf, NULL, NULL, NULL, 0); return; case 3: shutup = TRUE; /* won't print "disconnected" in channels */ } server_flush_queue (serv); list = sess_list; while (list) { sess = (struct session *) list->data; if (sess->server == serv) { if (!shutup || sess->type == SESS_SERVER) /* print "Disconnected" to each window using this server */ EMIT_SIGNAL (XP_TE_DISCON, sess, errorstring (err), NULL, NULL, NULL, 0); if (!sess->channel[0] || sess->type == SESS_CHANNEL) clear_channel (sess); } list = list->next; } serv->pos = 0; serv->motd_skipped = FALSE; serv->no_login = FALSE; serv->servername[0] = 0; serv->lag_sent = 0; notify_cleanup (); } /* send a "print text" command to the parent process - MUST END IN \n! */ static void proxy_error (int fd, char *msg) { write (fd, "0\n", 2); write (fd, msg, strlen (msg)); } struct sock_connect { char version; char type; guint16 port; guint32 address; char username[10]; }; /* traverse_socks() returns: * 0 success * * 1 socks traversal failed */ static int traverse_socks (int print_fd, int sok, char *serverAddr, int port) { struct sock_connect sc; unsigned char buf[256]; sc.version = 4; sc.type = 1; sc.port = htons (port); sc.address = inet_addr (serverAddr); strncpy (sc.username, prefs.hex_irc_user_name, 9); send (sok, (char *) &sc, 8 + strlen (sc.username) + 1, 0); buf[1] = 0; recv (sok, buf, 10, 0); if (buf[1] == 90) return 0; snprintf (buf, sizeof (buf), "SOCKS\tServer reported error %d,%d.\n", buf[0], buf[1]); proxy_error (print_fd, buf); return 1; } struct sock5_connect1 { char version; char nmethods; char method; }; static int traverse_socks5 (int print_fd, int sok, char *serverAddr, int port) { struct sock5_connect1 sc1; unsigned char *sc2; unsigned int packetlen, addrlen; unsigned char buf[260]; int auth = prefs.hex_net_proxy_auth && prefs.hex_net_proxy_user[0] && prefs.hex_net_proxy_pass[0]; sc1.version = 5; sc1.nmethods = 1; if (auth) sc1.method = 2; /* Username/Password Authentication (UPA) */ else sc1.method = 0; /* NO Authentication */ send (sok, (char *) &sc1, 3, 0); if (recv (sok, buf, 2, 0) != 2) goto read_error; if (buf[0] != 5) { proxy_error (print_fd, "SOCKS\tServer is not socks version 5.\n"); return 1; } /* did the server say no auth required? */ if (buf[1] == 0) auth = 0; if (auth) { int len_u=0, len_p=0; /* authentication sub-negotiation (RFC1929) */ if (buf[1] != 2) /* UPA not supported by server */ { proxy_error (print_fd, "SOCKS\tServer doesn't support UPA authentication.\n"); return 1; } memset (buf, 0, sizeof(buf)); /* form the UPA request */ len_u = strlen (prefs.hex_net_proxy_user); len_p = strlen (prefs.hex_net_proxy_pass); buf[0] = 1; buf[1] = len_u; memcpy (buf + 2, prefs.hex_net_proxy_user, len_u); buf[2 + len_u] = len_p; memcpy (buf + 3 + len_u, prefs.hex_net_proxy_pass, len_p); send (sok, buf, 3 + len_u + len_p, 0); if ( recv (sok, buf, 2, 0) != 2 ) goto read_error; if ( buf[1] != 0 ) { proxy_error (print_fd, "SOCKS\tAuthentication failed. " "Is username and password correct?\n"); return 1; /* UPA failed! */ } } else { if (buf[1] != 0) { proxy_error (print_fd, "SOCKS\tAuthentication required but disabled in settings.\n"); return 1; } } addrlen = strlen (serverAddr); packetlen = 4 + 1 + addrlen + 2; sc2 = malloc (packetlen); sc2[0] = 5; /* version */ sc2[1] = 1; /* command */ sc2[2] = 0; /* reserved */ sc2[3] = 3; /* address type */ sc2[4] = (unsigned char) addrlen; /* hostname length */ memcpy (sc2 + 5, serverAddr, addrlen); *((unsigned short *) (sc2 + 5 + addrlen)) = htons (port); send (sok, sc2, packetlen, 0); free (sc2); /* consume all of the reply */ if (recv (sok, buf, 4, 0) != 4) goto read_error; if (buf[0] != 5 || buf[1] != 0) { if (buf[1] == 2) snprintf (buf, sizeof (buf), "SOCKS\tProxy refused to connect to host (not allowed).\n"); else snprintf (buf, sizeof (buf), "SOCKS\tProxy failed to connect to host (error %d).\n", buf[1]); proxy_error (print_fd, buf); return 1; } if (buf[3] == 1) /* IPV4 32bit address */ { if (recv (sok, buf, 6, 0) != 6) goto read_error; } else if (buf[3] == 4) /* IPV6 128bit address */ { if (recv (sok, buf, 18, 0) != 18) goto read_error; } else if (buf[3] == 3) /* string, 1st byte is size */ { if (recv (sok, buf, 1, 0) != 1) /* read the string size */ goto read_error; packetlen = buf[0] + 2; /* can't exceed 260 */ if (recv (sok, buf, packetlen, 0) != packetlen) goto read_error; } return 0; /* success */ read_error: proxy_error (print_fd, "SOCKS\tRead error from server.\n"); return 1; } static int traverse_wingate (int print_fd, int sok, char *serverAddr, int port) { char buf[128]; snprintf (buf, sizeof (buf), "%s %d\r\n", serverAddr, port); send (sok, buf, strlen (buf), 0); return 0; } /* stuff for HTTP auth is here */ static void three_to_four (char *from, char *to) { static const char tab64[64]= { 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P', 'Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f', 'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v', 'w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/' }; to[0] = tab64 [ (from[0] >> 2) & 63 ]; to[1] = tab64 [ ((from[0] << 4) | (from[1] >> 4)) & 63 ]; to[2] = tab64 [ ((from[1] << 2) | (from[2] >> 6)) & 63 ]; to[3] = tab64 [ from[2] & 63 ]; }; void base64_encode (char *to, char *from, unsigned int len) { while (len >= 3) { three_to_four (from, to); len -= 3; from += 3; to += 4; } if (len) { char three[3] = {0,0,0}; unsigned int i; for (i = 0; i < len; i++) { three[i] = *from++; } three_to_four (three, to); if (len == 1) { to[2] = to[3] = '='; } else if (len == 2) { to[3] = '='; } to += 4; }; to[0] = 0; } static int http_read_line (int print_fd, int sok, char *buf, int len) { len = waitline (sok, buf, len, TRUE); if (len >= 1) { /* print the message out (send it to the parent process) */ write (print_fd, "0\n", 2); if (buf[len-1] == '\r') { buf[len-1] = '\n'; write (print_fd, buf, len); } else { write (print_fd, buf, len); write (print_fd, "\n", 1); } } return len; } static int traverse_http (int print_fd, int sok, char *serverAddr, int port) { char buf[512]; char auth_data[256]; char auth_data2[252]; int n, n2; n = snprintf (buf, sizeof (buf), "CONNECT %s:%d HTTP/1.0\r\n", serverAddr, port); if (prefs.hex_net_proxy_auth) { n2 = snprintf (auth_data2, sizeof (auth_data2), "%s:%s", prefs.hex_net_proxy_user, prefs.hex_net_proxy_pass); base64_encode (auth_data, auth_data2, n2); n += snprintf (buf+n, sizeof (buf)-n, "Proxy-Authorization: Basic %s\r\n", auth_data); } n += snprintf (buf+n, sizeof (buf)-n, "\r\n"); send (sok, buf, n, 0); n = http_read_line (print_fd, sok, buf, sizeof (buf)); /* "HTTP/1.0 200 OK" */ if (n < 12) return 1; if (memcmp (buf, "HTTP/", 5) || memcmp (buf + 9, "200", 3)) return 1; while (1) { /* read until blank line */ n = http_read_line (print_fd, sok, buf, sizeof (buf)); if (n < 1 || (n == 1 && buf[0] == '\n')) break; } return 0; } static int traverse_proxy (int proxy_type, int print_fd, int sok, char *ip, int port, struct msproxy_state_t *state, netstore *ns_proxy, int csok4, int csok6, int *csok, char bound) { switch (proxy_type) { case 1: return traverse_wingate (print_fd, sok, ip, port); case 2: return traverse_socks (print_fd, sok, ip, port); case 3: return traverse_socks5 (print_fd, sok, ip, port); case 4: return traverse_http (print_fd, sok, ip, port); #ifdef USE_MSPROXY case 5: return traverse_msproxy (sok, ip, port, state, ns_proxy, csok4, csok6, csok, bound); #endif } return 1; } /* this is the child process making the connection attempt */ static int server_child (server * serv) { netstore *ns_server; netstore *ns_proxy = NULL; netstore *ns_local; int port = serv->port; int error; int sok, psok; char *hostname = serv->hostname; char *real_hostname = NULL; char *ip; char *proxy_ip = NULL; char *local_ip; int connect_port; char buf[512]; char bound = 0; int proxy_type = 0; char *proxy_host = NULL; int proxy_port; ns_server = net_store_new (); /* is a hostname set? - bind to it */ if (prefs.hex_net_bind_host[0]) { ns_local = net_store_new (); local_ip = net_resolve (ns_local, prefs.hex_net_bind_host, 0, &real_hostname); if (local_ip != NULL) { snprintf (buf, sizeof (buf), "5\n%s\n", local_ip); write (serv->childwrite, buf, strlen (buf)); net_bind (ns_local, serv->sok4, serv->sok6); bound = 1; } else { write (serv->childwrite, "7\n", 2); } net_store_destroy (ns_local); } if (!serv->dont_use_proxy) /* blocked in serverlist? */ { if (FALSE) ; #ifdef USE_LIBPROXY else if (prefs.hex_net_proxy_type == 5) { char **proxy_list; char *url, *proxy; url = g_strdup_printf ("irc://%s:%d", hostname, port); proxy_list = px_proxy_factory_get_proxies (libproxy_factory, url); if (proxy_list) { /* can use only one */ proxy = proxy_list[0]; if (!strncmp (proxy, "direct", 6)) proxy_type = 0; else if (!strncmp (proxy, "http", 4)) proxy_type = 4; else if (!strncmp (proxy, "socks5", 6)) proxy_type = 3; else if (!strncmp (proxy, "socks", 5)) proxy_type = 2; } if (proxy_type) { char *c; c = strchr (proxy, ':') + 3; proxy_host = strdup (c); c = strchr (proxy_host, ':'); *c = '\0'; proxy_port = atoi (c + 1); } g_strfreev (proxy_list); g_free (url); } #endif else if (prefs.hex_net_proxy_host[0] && prefs.hex_net_proxy_type > 0 && prefs.hex_net_proxy_use != 2) /* proxy is NOT dcc-only */ { proxy_type = prefs.hex_net_proxy_type; proxy_host = strdup (prefs.hex_net_proxy_host); proxy_port = prefs.hex_net_proxy_port; } } serv->proxy_type = proxy_type; /* first resolve where we want to connect to */ if (proxy_type > 0) { snprintf (buf, sizeof (buf), "9\n%s\n", proxy_host); write (serv->childwrite, buf, strlen (buf)); ip = net_resolve (ns_server, proxy_host, proxy_port, &real_hostname); free (proxy_host); if (!ip) { write (serv->childwrite, "1\n", 2); goto xit; } connect_port = proxy_port; /* if using socks4 or MS Proxy, attempt to resolve ip for irc server */ if ((proxy_type == 2) || (proxy_type == 5)) { ns_proxy = net_store_new (); proxy_ip = net_resolve (ns_proxy, hostname, port, &real_hostname); if (!proxy_ip) { write (serv->childwrite, "1\n", 2); goto xit; } } else /* otherwise we can just use the hostname */ proxy_ip = strdup (hostname); } else { ip = net_resolve (ns_server, hostname, port, &real_hostname); if (!ip) { write (serv->childwrite, "1\n", 2); goto xit; } connect_port = port; } snprintf (buf, sizeof (buf), "3\n%s\n%s\n%d\n", real_hostname, ip, connect_port); write (serv->childwrite, buf, strlen (buf)); if (!serv->dont_use_proxy && (proxy_type == 5)) error = net_connect (ns_server, serv->proxy_sok4, serv->proxy_sok6, &psok); else { error = net_connect (ns_server, serv->sok4, serv->sok6, &sok); psok = sok; } if (error != 0) { snprintf (buf, sizeof (buf), "2\n%d\n", sock_error ()); write (serv->childwrite, buf, strlen (buf)); } else { /* connect succeeded */ if (proxy_ip) { switch (traverse_proxy (proxy_type, serv->childwrite, psok, proxy_ip, port, &serv->msp_state, ns_proxy, serv->sok4, serv->sok6, &sok, bound)) { case 0: /* success */ #ifdef USE_MSPROXY if (!serv->dont_use_proxy && (proxy_type == 5)) snprintf (buf, sizeof (buf), "4\n%d %d %d %d %d\n", sok, psok, serv->msp_state.clientid, serv->msp_state.serverid, serv->msp_state.seq_sent); else #endif snprintf (buf, sizeof (buf), "4\n%d\n", sok); /* success */ write (serv->childwrite, buf, strlen (buf)); break; case 1: /* socks traversal failed */ write (serv->childwrite, "8\n", 2); break; } } else { snprintf (buf, sizeof (buf), "4\n%d\n", sok); /* success */ write (serv->childwrite, buf, strlen (buf)); } } xit: #if defined (USE_IPV6) || defined (WIN32) /* this is probably not needed */ net_store_destroy (ns_server); if (ns_proxy) net_store_destroy (ns_proxy); #endif /* no need to free ip/real_hostname, this process is exiting */ #ifdef WIN32 /* under win32 we use a thread -> shared memory, must free! */ if (proxy_ip) free (proxy_ip); if (ip) free (ip); if (real_hostname) free (real_hostname); #endif return 0; /* cppcheck-suppress memleak */ } static void server_connect (server *serv, char *hostname, int port, int no_login) { int pid, read_des[2]; session *sess = serv->server_session; #ifdef USE_OPENSSL if (!serv->ctx && serv->use_ssl) { if (!(serv->ctx = _SSL_context_init (ssl_cb_info, FALSE))) { fprintf (stderr, "_SSL_context_init failed\n"); exit (1); } } #endif if (!hostname[0]) return; if (port < 0) { /* use default port for this server type */ port = 6667; #ifdef USE_OPENSSL if (serv->use_ssl) port = 6697; #endif } port &= 0xffff; /* wrap around */ if (serv->connected || serv->connecting || serv->recondelay_tag) server_disconnect (sess, TRUE, -1); fe_progressbar_start (sess); EMIT_SIGNAL (XP_TE_SERVERLOOKUP, sess, hostname, NULL, NULL, NULL, 0); safe_strcpy (serv->servername, hostname, sizeof (serv->servername)); /* overlap illegal in strncpy */ if (hostname != serv->hostname) safe_strcpy (serv->hostname, hostname, sizeof (serv->hostname)); #ifdef USE_OPENSSL if (serv->use_ssl) { char *cert_file; serv->have_cert = FALSE; /* first try network specific cert/key */ cert_file = g_strdup_printf ("%s" G_DIR_SEPARATOR_S "certs" G_DIR_SEPARATOR_S "%s.pem", get_xdir (), server_get_network (serv, TRUE)); if (SSL_CTX_use_certificate_file (serv->ctx, cert_file, SSL_FILETYPE_PEM) == 1) { if (SSL_CTX_use_PrivateKey_file (serv->ctx, cert_file, SSL_FILETYPE_PEM) == 1) serv->have_cert = TRUE; } else { /* if that doesn't exist, try <config>/certs/client.pem */ cert_file = g_build_filename (get_xdir (), "certs", "client.pem", NULL); if (SSL_CTX_use_certificate_file (serv->ctx, cert_file, SSL_FILETYPE_PEM) == 1) { if (SSL_CTX_use_PrivateKey_file (serv->ctx, cert_file, SSL_FILETYPE_PEM) == 1) serv->have_cert = TRUE; } } g_free (cert_file); } #endif server_set_defaults (serv); serv->connecting = TRUE; serv->port = port; serv->no_login = no_login; fe_server_event (serv, FE_SE_CONNECTING, 0); fe_set_away (serv); server_flush_queue (serv); #ifdef WIN32 if (_pipe (read_des, 4096, _O_BINARY) < 0) #else if (pipe (read_des) < 0) #endif return; #ifdef __EMX__ /* os/2 */ setmode (read_des[0], O_BINARY); setmode (read_des[1], O_BINARY); #endif serv->childread = read_des[0]; serv->childwrite = read_des[1]; /* create both sockets now, drop one later */ net_sockets (&serv->sok4, &serv->sok6); #ifdef USE_MSPROXY /* In case of MS Proxy we have a separate UDP control connection */ if (!serv->dont_use_proxy && (serv->proxy_type == 5)) udp_sockets (&serv->proxy_sok4, &serv->proxy_sok6); else #endif { serv->proxy_sok4 = -1; serv->proxy_sok6 = -1; } #ifdef WIN32 CloseHandle (CreateThread (NULL, 0, (LPTHREAD_START_ROUTINE)server_child, serv, 0, (DWORD *)&pid)); #else #ifdef LOOKUPD /* CL: net_resolve calls rand() when LOOKUPD is set, so prepare a different * seed for each child. This method gives a bigger variation in seed values * than calling srand(time(0)) in the child itself. */ rand(); #endif switch (pid = fork ()) { case -1: return; case 0: /* this is the child */ setuid (getuid ()); server_child (serv); _exit (0); } #endif serv->childpid = pid; #ifdef WIN32 serv->iotag = fe_input_add (serv->childread, FIA_READ|FIA_FD, server_read_child, #else serv->iotag = fe_input_add (serv->childread, FIA_READ, server_read_child, #endif serv); } void server_fill_her_up (server *serv) { serv->connect = server_connect; serv->disconnect = server_disconnect; serv->cleanup = server_cleanup; serv->flush_queue = server_flush_queue; serv->auto_reconnect = auto_reconnect; proto_fill_her_up (serv); } void server_set_encoding (server *serv, char *new_encoding) { char *space; if (serv->encoding) { free (serv->encoding); /* can be left as NULL to indicate system encoding */ serv->encoding = NULL; serv->using_cp1255 = FALSE; serv->using_irc = FALSE; } if (new_encoding) { serv->encoding = strdup (new_encoding); /* the serverlist GUI might have added a space and short description - remove it. */ space = strchr (serv->encoding, ' '); if (space) space[0] = 0; /* server_inline() uses these flags */ if (!g_ascii_strcasecmp (serv->encoding, "CP1255") || !g_ascii_strcasecmp (serv->encoding, "WINDOWS-1255")) serv->using_cp1255 = TRUE; else if (!g_ascii_strcasecmp (serv->encoding, "IRC")) serv->using_irc = TRUE; } } server * server_new (void) { static int id = 0; server *serv; serv = malloc (sizeof (struct server)); memset (serv, 0, sizeof (struct server)); /* use server.c and proto-irc.c functions */ server_fill_her_up (serv); serv->id = id++; serv->sok = -1; strcpy (serv->nick, prefs.hex_irc_nick1); server_set_defaults (serv); serv_list = g_slist_prepend (serv_list, serv); fe_new_server (serv); return serv; } int is_server (server *serv) { return g_slist_find (serv_list, serv) ? 1 : 0; } void server_set_defaults (server *serv) { if (serv->chantypes) free (serv->chantypes); if (serv->chanmodes) free (serv->chanmodes); if (serv->nick_prefixes) free (serv->nick_prefixes); if (serv->nick_modes) free (serv->nick_modes); serv->chantypes = strdup ("#&!+"); serv->chanmodes = strdup ("beI,k,l"); serv->nick_prefixes = strdup ("@%+"); serv->nick_modes = strdup ("ohv"); serv->nickcount = 1; serv->end_of_motd = FALSE; serv->is_away = FALSE; serv->supports_watch = FALSE; serv->supports_monitor = FALSE; serv->bad_prefix = FALSE; serv->use_who = TRUE; serv->have_namesx = FALSE; serv->have_awaynotify = FALSE; serv->have_uhnames = FALSE; serv->have_whox = FALSE; serv->have_idmsg = FALSE; serv->have_accnotify = FALSE; serv->have_extjoin = FALSE; serv->have_server_time = FALSE; serv->have_sasl = FALSE; serv->have_except = FALSE; serv->have_invite = FALSE; } char * server_get_network (server *serv, gboolean fallback) { /* check the network list */ if (serv->network) return ((ircnet *)serv->network)->name; /* check the network name given in 005 NETWORK=... */ if (serv->server_session && *serv->server_session->channel) return serv->server_session->channel; if (fallback) return serv->servername; return NULL; } void server_set_name (server *serv, char *name) { GSList *list = sess_list; session *sess; if (name[0] == 0) name = serv->hostname; /* strncpy parameters must NOT overlap */ if (name != serv->servername) { safe_strcpy (serv->servername, name, sizeof (serv->servername)); } while (list) { sess = (session *) list->data; if (sess->server == serv) fe_set_title (sess); list = list->next; } if (serv->server_session->type == SESS_SERVER) { if (serv->network) { safe_strcpy (serv->server_session->channel, ((ircnet *)serv->network)->name, CHANLEN); } else { safe_strcpy (serv->server_session->channel, name, CHANLEN); } fe_set_channel (serv->server_session); } } struct away_msg * server_away_find_message (server *serv, char *nick) { struct away_msg *away; GSList *list = away_list; while (list) { away = (struct away_msg *) list->data; if (away->server == serv && !serv->p_cmp (nick, away->nick)) return away; list = list->next; } return NULL; } static void server_away_free_messages (server *serv) { GSList *list, *next; struct away_msg *away; list = away_list; while (list) { away = list->data; next = list->next; if (away->server == serv) { away_list = g_slist_remove (away_list, away); if (away->message) free (away->message); free (away); next = away_list; } list = next; } } void server_away_save_message (server *serv, char *nick, char *msg) { struct away_msg *away = server_away_find_message (serv, nick); if (away) /* Change message for known user */ { if (away->message) free (away->message); away->message = strdup (msg); } else /* Create brand new entry */ { away = malloc (sizeof (struct away_msg)); if (away) { away->server = serv; safe_strcpy (away->nick, nick, sizeof (away->nick)); away->message = strdup (msg); away_list = g_slist_prepend (away_list, away); } } } void server_free (server *serv) { serv->cleanup (serv); serv_list = g_slist_remove (serv_list, serv); dcc_notify_kill (serv); serv->flush_queue (serv); server_away_free_messages (serv); free (serv->nick_modes); free (serv->nick_prefixes); free (serv->chanmodes); free (serv->chantypes); if (serv->bad_nick_prefixes) free (serv->bad_nick_prefixes); if (serv->last_away_reason) free (serv->last_away_reason); if (serv->encoding) free (serv->encoding); if (serv->favlist) g_slist_free_full (serv->favlist, (GDestroyNotify) servlist_favchan_free); #ifdef USE_OPENSSL if (serv->ctx) _SSL_context_free (serv->ctx); #endif fe_server_callback (serv); free (serv); notify_cleanup (); }
./CrossVul/dataset_final_sorted/CWE-310/c/bad_5867_0
crossvul-cpp_data_good_5666_3
/* * Block chaining cipher operations. * * Generic encrypt/decrypt wrapper for ciphers, handles operations across * multiple page boundaries by using temporary blocks. In user context, * the kernel is given a chance to schedule us once per page. * * Copyright (c) 2006 Herbert Xu <herbert@gondor.apana.org.au> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include <crypto/internal/skcipher.h> #include <crypto/scatterwalk.h> #include <linux/errno.h> #include <linux/hardirq.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/scatterlist.h> #include <linux/seq_file.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/cryptouser.h> #include <net/netlink.h> #include "internal.h" enum { BLKCIPHER_WALK_PHYS = 1 << 0, BLKCIPHER_WALK_SLOW = 1 << 1, BLKCIPHER_WALK_COPY = 1 << 2, BLKCIPHER_WALK_DIFF = 1 << 3, }; static int blkcipher_walk_next(struct blkcipher_desc *desc, struct blkcipher_walk *walk); static int blkcipher_walk_first(struct blkcipher_desc *desc, struct blkcipher_walk *walk); static inline void blkcipher_map_src(struct blkcipher_walk *walk) { walk->src.virt.addr = scatterwalk_map(&walk->in); } static inline void blkcipher_map_dst(struct blkcipher_walk *walk) { walk->dst.virt.addr = scatterwalk_map(&walk->out); } static inline void blkcipher_unmap_src(struct blkcipher_walk *walk) { scatterwalk_unmap(walk->src.virt.addr); } static inline void blkcipher_unmap_dst(struct blkcipher_walk *walk) { scatterwalk_unmap(walk->dst.virt.addr); } /* Get a spot of the specified length that does not straddle a page. * The caller needs to ensure that there is enough space for this operation. */ static inline u8 *blkcipher_get_spot(u8 *start, unsigned int len) { u8 *end_page = (u8 *)(((unsigned long)(start + len - 1)) & PAGE_MASK); return max(start, end_page); } static inline unsigned int blkcipher_done_slow(struct crypto_blkcipher *tfm, struct blkcipher_walk *walk, unsigned int bsize) { u8 *addr; unsigned int alignmask = crypto_blkcipher_alignmask(tfm); addr = (u8 *)ALIGN((unsigned long)walk->buffer, alignmask + 1); addr = blkcipher_get_spot(addr, bsize); scatterwalk_copychunks(addr, &walk->out, bsize, 1); return bsize; } static inline unsigned int blkcipher_done_fast(struct blkcipher_walk *walk, unsigned int n) { if (walk->flags & BLKCIPHER_WALK_COPY) { blkcipher_map_dst(walk); memcpy(walk->dst.virt.addr, walk->page, n); blkcipher_unmap_dst(walk); } else if (!(walk->flags & BLKCIPHER_WALK_PHYS)) { if (walk->flags & BLKCIPHER_WALK_DIFF) blkcipher_unmap_dst(walk); blkcipher_unmap_src(walk); } scatterwalk_advance(&walk->in, n); scatterwalk_advance(&walk->out, n); return n; } int blkcipher_walk_done(struct blkcipher_desc *desc, struct blkcipher_walk *walk, int err) { struct crypto_blkcipher *tfm = desc->tfm; unsigned int nbytes = 0; if (likely(err >= 0)) { unsigned int n = walk->nbytes - err; if (likely(!(walk->flags & BLKCIPHER_WALK_SLOW))) n = blkcipher_done_fast(walk, n); else if (WARN_ON(err)) { err = -EINVAL; goto err; } else n = blkcipher_done_slow(tfm, walk, n); nbytes = walk->total - n; err = 0; } scatterwalk_done(&walk->in, 0, nbytes); scatterwalk_done(&walk->out, 1, nbytes); err: walk->total = nbytes; walk->nbytes = nbytes; if (nbytes) { crypto_yield(desc->flags); return blkcipher_walk_next(desc, walk); } if (walk->iv != desc->info) memcpy(desc->info, walk->iv, crypto_blkcipher_ivsize(tfm)); if (walk->buffer != walk->page) kfree(walk->buffer); if (walk->page) free_page((unsigned long)walk->page); return err; } EXPORT_SYMBOL_GPL(blkcipher_walk_done); static inline int blkcipher_next_slow(struct blkcipher_desc *desc, struct blkcipher_walk *walk, unsigned int bsize, unsigned int alignmask) { unsigned int n; unsigned aligned_bsize = ALIGN(bsize, alignmask + 1); if (walk->buffer) goto ok; walk->buffer = walk->page; if (walk->buffer) goto ok; n = aligned_bsize * 3 - (alignmask + 1) + (alignmask & ~(crypto_tfm_ctx_alignment() - 1)); walk->buffer = kmalloc(n, GFP_ATOMIC); if (!walk->buffer) return blkcipher_walk_done(desc, walk, -ENOMEM); ok: walk->dst.virt.addr = (u8 *)ALIGN((unsigned long)walk->buffer, alignmask + 1); walk->dst.virt.addr = blkcipher_get_spot(walk->dst.virt.addr, bsize); walk->src.virt.addr = blkcipher_get_spot(walk->dst.virt.addr + aligned_bsize, bsize); scatterwalk_copychunks(walk->src.virt.addr, &walk->in, bsize, 0); walk->nbytes = bsize; walk->flags |= BLKCIPHER_WALK_SLOW; return 0; } static inline int blkcipher_next_copy(struct blkcipher_walk *walk) { u8 *tmp = walk->page; blkcipher_map_src(walk); memcpy(tmp, walk->src.virt.addr, walk->nbytes); blkcipher_unmap_src(walk); walk->src.virt.addr = tmp; walk->dst.virt.addr = tmp; return 0; } static inline int blkcipher_next_fast(struct blkcipher_desc *desc, struct blkcipher_walk *walk) { unsigned long diff; walk->src.phys.page = scatterwalk_page(&walk->in); walk->src.phys.offset = offset_in_page(walk->in.offset); walk->dst.phys.page = scatterwalk_page(&walk->out); walk->dst.phys.offset = offset_in_page(walk->out.offset); if (walk->flags & BLKCIPHER_WALK_PHYS) return 0; diff = walk->src.phys.offset - walk->dst.phys.offset; diff |= walk->src.virt.page - walk->dst.virt.page; blkcipher_map_src(walk); walk->dst.virt.addr = walk->src.virt.addr; if (diff) { walk->flags |= BLKCIPHER_WALK_DIFF; blkcipher_map_dst(walk); } return 0; } static int blkcipher_walk_next(struct blkcipher_desc *desc, struct blkcipher_walk *walk) { struct crypto_blkcipher *tfm = desc->tfm; unsigned int alignmask = crypto_blkcipher_alignmask(tfm); unsigned int bsize; unsigned int n; int err; n = walk->total; if (unlikely(n < crypto_blkcipher_blocksize(tfm))) { desc->flags |= CRYPTO_TFM_RES_BAD_BLOCK_LEN; return blkcipher_walk_done(desc, walk, -EINVAL); } walk->flags &= ~(BLKCIPHER_WALK_SLOW | BLKCIPHER_WALK_COPY | BLKCIPHER_WALK_DIFF); if (!scatterwalk_aligned(&walk->in, alignmask) || !scatterwalk_aligned(&walk->out, alignmask)) { walk->flags |= BLKCIPHER_WALK_COPY; if (!walk->page) { walk->page = (void *)__get_free_page(GFP_ATOMIC); if (!walk->page) n = 0; } } bsize = min(walk->blocksize, n); n = scatterwalk_clamp(&walk->in, n); n = scatterwalk_clamp(&walk->out, n); if (unlikely(n < bsize)) { err = blkcipher_next_slow(desc, walk, bsize, alignmask); goto set_phys_lowmem; } walk->nbytes = n; if (walk->flags & BLKCIPHER_WALK_COPY) { err = blkcipher_next_copy(walk); goto set_phys_lowmem; } return blkcipher_next_fast(desc, walk); set_phys_lowmem: if (walk->flags & BLKCIPHER_WALK_PHYS) { walk->src.phys.page = virt_to_page(walk->src.virt.addr); walk->dst.phys.page = virt_to_page(walk->dst.virt.addr); walk->src.phys.offset &= PAGE_SIZE - 1; walk->dst.phys.offset &= PAGE_SIZE - 1; } return err; } static inline int blkcipher_copy_iv(struct blkcipher_walk *walk, struct crypto_blkcipher *tfm, unsigned int alignmask) { unsigned bs = walk->blocksize; unsigned int ivsize = crypto_blkcipher_ivsize(tfm); unsigned aligned_bs = ALIGN(bs, alignmask + 1); unsigned int size = aligned_bs * 2 + ivsize + max(aligned_bs, ivsize) - (alignmask + 1); u8 *iv; size += alignmask & ~(crypto_tfm_ctx_alignment() - 1); walk->buffer = kmalloc(size, GFP_ATOMIC); if (!walk->buffer) return -ENOMEM; iv = (u8 *)ALIGN((unsigned long)walk->buffer, alignmask + 1); iv = blkcipher_get_spot(iv, bs) + aligned_bs; iv = blkcipher_get_spot(iv, bs) + aligned_bs; iv = blkcipher_get_spot(iv, ivsize); walk->iv = memcpy(iv, walk->iv, ivsize); return 0; } int blkcipher_walk_virt(struct blkcipher_desc *desc, struct blkcipher_walk *walk) { walk->flags &= ~BLKCIPHER_WALK_PHYS; walk->blocksize = crypto_blkcipher_blocksize(desc->tfm); return blkcipher_walk_first(desc, walk); } EXPORT_SYMBOL_GPL(blkcipher_walk_virt); int blkcipher_walk_phys(struct blkcipher_desc *desc, struct blkcipher_walk *walk) { walk->flags |= BLKCIPHER_WALK_PHYS; walk->blocksize = crypto_blkcipher_blocksize(desc->tfm); return blkcipher_walk_first(desc, walk); } EXPORT_SYMBOL_GPL(blkcipher_walk_phys); static int blkcipher_walk_first(struct blkcipher_desc *desc, struct blkcipher_walk *walk) { struct crypto_blkcipher *tfm = desc->tfm; unsigned int alignmask = crypto_blkcipher_alignmask(tfm); if (WARN_ON_ONCE(in_irq())) return -EDEADLK; walk->nbytes = walk->total; if (unlikely(!walk->total)) return 0; walk->buffer = NULL; walk->iv = desc->info; if (unlikely(((unsigned long)walk->iv & alignmask))) { int err = blkcipher_copy_iv(walk, tfm, alignmask); if (err) return err; } scatterwalk_start(&walk->in, walk->in.sg); scatterwalk_start(&walk->out, walk->out.sg); walk->page = NULL; return blkcipher_walk_next(desc, walk); } int blkcipher_walk_virt_block(struct blkcipher_desc *desc, struct blkcipher_walk *walk, unsigned int blocksize) { walk->flags &= ~BLKCIPHER_WALK_PHYS; walk->blocksize = blocksize; return blkcipher_walk_first(desc, walk); } EXPORT_SYMBOL_GPL(blkcipher_walk_virt_block); static int setkey_unaligned(struct crypto_tfm *tfm, const u8 *key, unsigned int keylen) { struct blkcipher_alg *cipher = &tfm->__crt_alg->cra_blkcipher; unsigned long alignmask = crypto_tfm_alg_alignmask(tfm); int ret; u8 *buffer, *alignbuffer; unsigned long absize; absize = keylen + alignmask; buffer = kmalloc(absize, GFP_ATOMIC); if (!buffer) return -ENOMEM; alignbuffer = (u8 *)ALIGN((unsigned long)buffer, alignmask + 1); memcpy(alignbuffer, key, keylen); ret = cipher->setkey(tfm, alignbuffer, keylen); memset(alignbuffer, 0, keylen); kfree(buffer); return ret; } static int setkey(struct crypto_tfm *tfm, const u8 *key, unsigned int keylen) { struct blkcipher_alg *cipher = &tfm->__crt_alg->cra_blkcipher; unsigned long alignmask = crypto_tfm_alg_alignmask(tfm); if (keylen < cipher->min_keysize || keylen > cipher->max_keysize) { tfm->crt_flags |= CRYPTO_TFM_RES_BAD_KEY_LEN; return -EINVAL; } if ((unsigned long)key & alignmask) return setkey_unaligned(tfm, key, keylen); return cipher->setkey(tfm, key, keylen); } static int async_setkey(struct crypto_ablkcipher *tfm, const u8 *key, unsigned int keylen) { return setkey(crypto_ablkcipher_tfm(tfm), key, keylen); } static int async_encrypt(struct ablkcipher_request *req) { struct crypto_tfm *tfm = req->base.tfm; struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher; struct blkcipher_desc desc = { .tfm = __crypto_blkcipher_cast(tfm), .info = req->info, .flags = req->base.flags, }; return alg->encrypt(&desc, req->dst, req->src, req->nbytes); } static int async_decrypt(struct ablkcipher_request *req) { struct crypto_tfm *tfm = req->base.tfm; struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher; struct blkcipher_desc desc = { .tfm = __crypto_blkcipher_cast(tfm), .info = req->info, .flags = req->base.flags, }; return alg->decrypt(&desc, req->dst, req->src, req->nbytes); } static unsigned int crypto_blkcipher_ctxsize(struct crypto_alg *alg, u32 type, u32 mask) { struct blkcipher_alg *cipher = &alg->cra_blkcipher; unsigned int len = alg->cra_ctxsize; if ((mask & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_MASK && cipher->ivsize) { len = ALIGN(len, (unsigned long)alg->cra_alignmask + 1); len += cipher->ivsize; } return len; } static int crypto_init_blkcipher_ops_async(struct crypto_tfm *tfm) { struct ablkcipher_tfm *crt = &tfm->crt_ablkcipher; struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher; crt->setkey = async_setkey; crt->encrypt = async_encrypt; crt->decrypt = async_decrypt; if (!alg->ivsize) { crt->givencrypt = skcipher_null_givencrypt; crt->givdecrypt = skcipher_null_givdecrypt; } crt->base = __crypto_ablkcipher_cast(tfm); crt->ivsize = alg->ivsize; return 0; } static int crypto_init_blkcipher_ops_sync(struct crypto_tfm *tfm) { struct blkcipher_tfm *crt = &tfm->crt_blkcipher; struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher; unsigned long align = crypto_tfm_alg_alignmask(tfm) + 1; unsigned long addr; crt->setkey = setkey; crt->encrypt = alg->encrypt; crt->decrypt = alg->decrypt; addr = (unsigned long)crypto_tfm_ctx(tfm); addr = ALIGN(addr, align); addr += ALIGN(tfm->__crt_alg->cra_ctxsize, align); crt->iv = (void *)addr; return 0; } static int crypto_init_blkcipher_ops(struct crypto_tfm *tfm, u32 type, u32 mask) { struct blkcipher_alg *alg = &tfm->__crt_alg->cra_blkcipher; if (alg->ivsize > PAGE_SIZE / 8) return -EINVAL; if ((mask & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_MASK) return crypto_init_blkcipher_ops_sync(tfm); else return crypto_init_blkcipher_ops_async(tfm); } #ifdef CONFIG_NET static int crypto_blkcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_blkcipher rblkcipher; strncpy(rblkcipher.type, "blkcipher", sizeof(rblkcipher.type)); strncpy(rblkcipher.geniv, alg->cra_blkcipher.geniv ?: "<default>", sizeof(rblkcipher.geniv)); rblkcipher.blocksize = alg->cra_blocksize; rblkcipher.min_keysize = alg->cra_blkcipher.min_keysize; rblkcipher.max_keysize = alg->cra_blkcipher.max_keysize; rblkcipher.ivsize = alg->cra_blkcipher.ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_BLKCIPHER, sizeof(struct crypto_report_blkcipher), &rblkcipher)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } #else static int crypto_blkcipher_report(struct sk_buff *skb, struct crypto_alg *alg) { return -ENOSYS; } #endif static void crypto_blkcipher_show(struct seq_file *m, struct crypto_alg *alg) __attribute__ ((unused)); static void crypto_blkcipher_show(struct seq_file *m, struct crypto_alg *alg) { seq_printf(m, "type : blkcipher\n"); seq_printf(m, "blocksize : %u\n", alg->cra_blocksize); seq_printf(m, "min keysize : %u\n", alg->cra_blkcipher.min_keysize); seq_printf(m, "max keysize : %u\n", alg->cra_blkcipher.max_keysize); seq_printf(m, "ivsize : %u\n", alg->cra_blkcipher.ivsize); seq_printf(m, "geniv : %s\n", alg->cra_blkcipher.geniv ?: "<default>"); } const struct crypto_type crypto_blkcipher_type = { .ctxsize = crypto_blkcipher_ctxsize, .init = crypto_init_blkcipher_ops, #ifdef CONFIG_PROC_FS .show = crypto_blkcipher_show, #endif .report = crypto_blkcipher_report, }; EXPORT_SYMBOL_GPL(crypto_blkcipher_type); static int crypto_grab_nivcipher(struct crypto_skcipher_spawn *spawn, const char *name, u32 type, u32 mask) { struct crypto_alg *alg; int err; type = crypto_skcipher_type(type); mask = crypto_skcipher_mask(mask)| CRYPTO_ALG_GENIV; alg = crypto_alg_mod_lookup(name, type, mask); if (IS_ERR(alg)) return PTR_ERR(alg); err = crypto_init_spawn(&spawn->base, alg, spawn->base.inst, mask); crypto_mod_put(alg); return err; } struct crypto_instance *skcipher_geniv_alloc(struct crypto_template *tmpl, struct rtattr **tb, u32 type, u32 mask) { struct { int (*setkey)(struct crypto_ablkcipher *tfm, const u8 *key, unsigned int keylen); int (*encrypt)(struct ablkcipher_request *req); int (*decrypt)(struct ablkcipher_request *req); unsigned int min_keysize; unsigned int max_keysize; unsigned int ivsize; const char *geniv; } balg; const char *name; struct crypto_skcipher_spawn *spawn; struct crypto_attr_type *algt; struct crypto_instance *inst; struct crypto_alg *alg; int err; algt = crypto_get_attr_type(tb); if (IS_ERR(algt)) return ERR_CAST(algt); if ((algt->type ^ (CRYPTO_ALG_TYPE_GIVCIPHER | CRYPTO_ALG_GENIV)) & algt->mask) return ERR_PTR(-EINVAL); name = crypto_attr_alg_name(tb[1]); if (IS_ERR(name)) return ERR_CAST(name); inst = kzalloc(sizeof(*inst) + sizeof(*spawn), GFP_KERNEL); if (!inst) return ERR_PTR(-ENOMEM); spawn = crypto_instance_ctx(inst); /* Ignore async algorithms if necessary. */ mask |= crypto_requires_sync(algt->type, algt->mask); crypto_set_skcipher_spawn(spawn, inst); err = crypto_grab_nivcipher(spawn, name, type, mask); if (err) goto err_free_inst; alg = crypto_skcipher_spawn_alg(spawn); if ((alg->cra_flags & CRYPTO_ALG_TYPE_MASK) == CRYPTO_ALG_TYPE_BLKCIPHER) { balg.ivsize = alg->cra_blkcipher.ivsize; balg.min_keysize = alg->cra_blkcipher.min_keysize; balg.max_keysize = alg->cra_blkcipher.max_keysize; balg.setkey = async_setkey; balg.encrypt = async_encrypt; balg.decrypt = async_decrypt; balg.geniv = alg->cra_blkcipher.geniv; } else { balg.ivsize = alg->cra_ablkcipher.ivsize; balg.min_keysize = alg->cra_ablkcipher.min_keysize; balg.max_keysize = alg->cra_ablkcipher.max_keysize; balg.setkey = alg->cra_ablkcipher.setkey; balg.encrypt = alg->cra_ablkcipher.encrypt; balg.decrypt = alg->cra_ablkcipher.decrypt; balg.geniv = alg->cra_ablkcipher.geniv; } err = -EINVAL; if (!balg.ivsize) goto err_drop_alg; /* * This is only true if we're constructing an algorithm with its * default IV generator. For the default generator we elide the * template name and double-check the IV generator. */ if (algt->mask & CRYPTO_ALG_GENIV) { if (!balg.geniv) balg.geniv = crypto_default_geniv(alg); err = -EAGAIN; if (strcmp(tmpl->name, balg.geniv)) goto err_drop_alg; memcpy(inst->alg.cra_name, alg->cra_name, CRYPTO_MAX_ALG_NAME); memcpy(inst->alg.cra_driver_name, alg->cra_driver_name, CRYPTO_MAX_ALG_NAME); } else { err = -ENAMETOOLONG; if (snprintf(inst->alg.cra_name, CRYPTO_MAX_ALG_NAME, "%s(%s)", tmpl->name, alg->cra_name) >= CRYPTO_MAX_ALG_NAME) goto err_drop_alg; if (snprintf(inst->alg.cra_driver_name, CRYPTO_MAX_ALG_NAME, "%s(%s)", tmpl->name, alg->cra_driver_name) >= CRYPTO_MAX_ALG_NAME) goto err_drop_alg; } inst->alg.cra_flags = CRYPTO_ALG_TYPE_GIVCIPHER | CRYPTO_ALG_GENIV; inst->alg.cra_flags |= alg->cra_flags & CRYPTO_ALG_ASYNC; inst->alg.cra_priority = alg->cra_priority; inst->alg.cra_blocksize = alg->cra_blocksize; inst->alg.cra_alignmask = alg->cra_alignmask; inst->alg.cra_type = &crypto_givcipher_type; inst->alg.cra_ablkcipher.ivsize = balg.ivsize; inst->alg.cra_ablkcipher.min_keysize = balg.min_keysize; inst->alg.cra_ablkcipher.max_keysize = balg.max_keysize; inst->alg.cra_ablkcipher.geniv = balg.geniv; inst->alg.cra_ablkcipher.setkey = balg.setkey; inst->alg.cra_ablkcipher.encrypt = balg.encrypt; inst->alg.cra_ablkcipher.decrypt = balg.decrypt; out: return inst; err_drop_alg: crypto_drop_skcipher(spawn); err_free_inst: kfree(inst); inst = ERR_PTR(err); goto out; } EXPORT_SYMBOL_GPL(skcipher_geniv_alloc); void skcipher_geniv_free(struct crypto_instance *inst) { crypto_drop_skcipher(crypto_instance_ctx(inst)); kfree(inst); } EXPORT_SYMBOL_GPL(skcipher_geniv_free); int skcipher_geniv_init(struct crypto_tfm *tfm) { struct crypto_instance *inst = (void *)tfm->__crt_alg; struct crypto_ablkcipher *cipher; cipher = crypto_spawn_skcipher(crypto_instance_ctx(inst)); if (IS_ERR(cipher)) return PTR_ERR(cipher); tfm->crt_ablkcipher.base = cipher; tfm->crt_ablkcipher.reqsize += crypto_ablkcipher_reqsize(cipher); return 0; } EXPORT_SYMBOL_GPL(skcipher_geniv_init); void skcipher_geniv_exit(struct crypto_tfm *tfm) { crypto_free_ablkcipher(tfm->crt_ablkcipher.base); } EXPORT_SYMBOL_GPL(skcipher_geniv_exit); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Generic block chaining cipher type");
./CrossVul/dataset_final_sorted/CWE-310/c/good_5666_3
crossvul-cpp_data_good_5666_7
/* * Synchronous Cryptographic Hash operations. * * Copyright (c) 2008 Herbert Xu <herbert@gondor.apana.org.au> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include <crypto/scatterwalk.h> #include <crypto/internal/hash.h> #include <linux/err.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/seq_file.h> #include <linux/cryptouser.h> #include <net/netlink.h> #include "internal.h" static const struct crypto_type crypto_shash_type; static int shash_no_setkey(struct crypto_shash *tfm, const u8 *key, unsigned int keylen) { return -ENOSYS; } static int shash_setkey_unaligned(struct crypto_shash *tfm, const u8 *key, unsigned int keylen) { struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); unsigned long absize; u8 *buffer, *alignbuffer; int err; absize = keylen + (alignmask & ~(crypto_tfm_ctx_alignment() - 1)); buffer = kmalloc(absize, GFP_KERNEL); if (!buffer) return -ENOMEM; alignbuffer = (u8 *)ALIGN((unsigned long)buffer, alignmask + 1); memcpy(alignbuffer, key, keylen); err = shash->setkey(tfm, alignbuffer, keylen); kzfree(buffer); return err; } int crypto_shash_setkey(struct crypto_shash *tfm, const u8 *key, unsigned int keylen) { struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if ((unsigned long)key & alignmask) return shash_setkey_unaligned(tfm, key, keylen); return shash->setkey(tfm, key, keylen); } EXPORT_SYMBOL_GPL(crypto_shash_setkey); static inline unsigned int shash_align_buffer_size(unsigned len, unsigned long mask) { return len + (mask & ~(__alignof__(u8 __attribute__ ((aligned))) - 1)); } static int shash_update_unaligned(struct shash_desc *desc, const u8 *data, unsigned int len) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); unsigned int unaligned_len = alignmask + 1 - ((unsigned long)data & alignmask); u8 ubuf[shash_align_buffer_size(unaligned_len, alignmask)] __attribute__ ((aligned)); u8 *buf = PTR_ALIGN(&ubuf[0], alignmask + 1); int err; if (unaligned_len > len) unaligned_len = len; memcpy(buf, data, unaligned_len); err = shash->update(desc, buf, unaligned_len); memset(buf, 0, unaligned_len); return err ?: shash->update(desc, data + unaligned_len, len - unaligned_len); } int crypto_shash_update(struct shash_desc *desc, const u8 *data, unsigned int len) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if ((unsigned long)data & alignmask) return shash_update_unaligned(desc, data, len); return shash->update(desc, data, len); } EXPORT_SYMBOL_GPL(crypto_shash_update); static int shash_final_unaligned(struct shash_desc *desc, u8 *out) { struct crypto_shash *tfm = desc->tfm; unsigned long alignmask = crypto_shash_alignmask(tfm); struct shash_alg *shash = crypto_shash_alg(tfm); unsigned int ds = crypto_shash_digestsize(tfm); u8 ubuf[shash_align_buffer_size(ds, alignmask)] __attribute__ ((aligned)); u8 *buf = PTR_ALIGN(&ubuf[0], alignmask + 1); int err; err = shash->final(desc, buf); if (err) goto out; memcpy(out, buf, ds); out: memset(buf, 0, ds); return err; } int crypto_shash_final(struct shash_desc *desc, u8 *out) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if ((unsigned long)out & alignmask) return shash_final_unaligned(desc, out); return shash->final(desc, out); } EXPORT_SYMBOL_GPL(crypto_shash_final); static int shash_finup_unaligned(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out) { return crypto_shash_update(desc, data, len) ?: crypto_shash_final(desc, out); } int crypto_shash_finup(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if (((unsigned long)data | (unsigned long)out) & alignmask) return shash_finup_unaligned(desc, data, len, out); return shash->finup(desc, data, len, out); } EXPORT_SYMBOL_GPL(crypto_shash_finup); static int shash_digest_unaligned(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out) { return crypto_shash_init(desc) ?: crypto_shash_finup(desc, data, len, out); } int crypto_shash_digest(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if (((unsigned long)data | (unsigned long)out) & alignmask) return shash_digest_unaligned(desc, data, len, out); return shash->digest(desc, data, len, out); } EXPORT_SYMBOL_GPL(crypto_shash_digest); static int shash_default_export(struct shash_desc *desc, void *out) { memcpy(out, shash_desc_ctx(desc), crypto_shash_descsize(desc->tfm)); return 0; } static int shash_default_import(struct shash_desc *desc, const void *in) { memcpy(shash_desc_ctx(desc), in, crypto_shash_descsize(desc->tfm)); return 0; } static int shash_async_setkey(struct crypto_ahash *tfm, const u8 *key, unsigned int keylen) { struct crypto_shash **ctx = crypto_ahash_ctx(tfm); return crypto_shash_setkey(*ctx, key, keylen); } static int shash_async_init(struct ahash_request *req) { struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req)); struct shash_desc *desc = ahash_request_ctx(req); desc->tfm = *ctx; desc->flags = req->base.flags; return crypto_shash_init(desc); } int shash_ahash_update(struct ahash_request *req, struct shash_desc *desc) { struct crypto_hash_walk walk; int nbytes; for (nbytes = crypto_hash_walk_first(req, &walk); nbytes > 0; nbytes = crypto_hash_walk_done(&walk, nbytes)) nbytes = crypto_shash_update(desc, walk.data, nbytes); return nbytes; } EXPORT_SYMBOL_GPL(shash_ahash_update); static int shash_async_update(struct ahash_request *req) { return shash_ahash_update(req, ahash_request_ctx(req)); } static int shash_async_final(struct ahash_request *req) { return crypto_shash_final(ahash_request_ctx(req), req->result); } int shash_ahash_finup(struct ahash_request *req, struct shash_desc *desc) { struct crypto_hash_walk walk; int nbytes; nbytes = crypto_hash_walk_first(req, &walk); if (!nbytes) return crypto_shash_final(desc, req->result); do { nbytes = crypto_hash_walk_last(&walk) ? crypto_shash_finup(desc, walk.data, nbytes, req->result) : crypto_shash_update(desc, walk.data, nbytes); nbytes = crypto_hash_walk_done(&walk, nbytes); } while (nbytes > 0); return nbytes; } EXPORT_SYMBOL_GPL(shash_ahash_finup); static int shash_async_finup(struct ahash_request *req) { struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req)); struct shash_desc *desc = ahash_request_ctx(req); desc->tfm = *ctx; desc->flags = req->base.flags; return shash_ahash_finup(req, desc); } int shash_ahash_digest(struct ahash_request *req, struct shash_desc *desc) { struct scatterlist *sg = req->src; unsigned int offset = sg->offset; unsigned int nbytes = req->nbytes; int err; if (nbytes < min(sg->length, ((unsigned int)(PAGE_SIZE)) - offset)) { void *data; data = kmap_atomic(sg_page(sg)); err = crypto_shash_digest(desc, data + offset, nbytes, req->result); kunmap_atomic(data); crypto_yield(desc->flags); } else err = crypto_shash_init(desc) ?: shash_ahash_finup(req, desc); return err; } EXPORT_SYMBOL_GPL(shash_ahash_digest); static int shash_async_digest(struct ahash_request *req) { struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req)); struct shash_desc *desc = ahash_request_ctx(req); desc->tfm = *ctx; desc->flags = req->base.flags; return shash_ahash_digest(req, desc); } static int shash_async_export(struct ahash_request *req, void *out) { return crypto_shash_export(ahash_request_ctx(req), out); } static int shash_async_import(struct ahash_request *req, const void *in) { struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req)); struct shash_desc *desc = ahash_request_ctx(req); desc->tfm = *ctx; desc->flags = req->base.flags; return crypto_shash_import(desc, in); } static void crypto_exit_shash_ops_async(struct crypto_tfm *tfm) { struct crypto_shash **ctx = crypto_tfm_ctx(tfm); crypto_free_shash(*ctx); } int crypto_init_shash_ops_async(struct crypto_tfm *tfm) { struct crypto_alg *calg = tfm->__crt_alg; struct shash_alg *alg = __crypto_shash_alg(calg); struct crypto_ahash *crt = __crypto_ahash_cast(tfm); struct crypto_shash **ctx = crypto_tfm_ctx(tfm); struct crypto_shash *shash; if (!crypto_mod_get(calg)) return -EAGAIN; shash = crypto_create_tfm(calg, &crypto_shash_type); if (IS_ERR(shash)) { crypto_mod_put(calg); return PTR_ERR(shash); } *ctx = shash; tfm->exit = crypto_exit_shash_ops_async; crt->init = shash_async_init; crt->update = shash_async_update; crt->final = shash_async_final; crt->finup = shash_async_finup; crt->digest = shash_async_digest; if (alg->setkey) crt->setkey = shash_async_setkey; if (alg->export) crt->export = shash_async_export; if (alg->import) crt->import = shash_async_import; crt->reqsize = sizeof(struct shash_desc) + crypto_shash_descsize(shash); return 0; } static int shash_compat_setkey(struct crypto_hash *tfm, const u8 *key, unsigned int keylen) { struct shash_desc **descp = crypto_hash_ctx(tfm); struct shash_desc *desc = *descp; return crypto_shash_setkey(desc->tfm, key, keylen); } static int shash_compat_init(struct hash_desc *hdesc) { struct shash_desc **descp = crypto_hash_ctx(hdesc->tfm); struct shash_desc *desc = *descp; desc->flags = hdesc->flags; return crypto_shash_init(desc); } static int shash_compat_update(struct hash_desc *hdesc, struct scatterlist *sg, unsigned int len) { struct shash_desc **descp = crypto_hash_ctx(hdesc->tfm); struct shash_desc *desc = *descp; struct crypto_hash_walk walk; int nbytes; for (nbytes = crypto_hash_walk_first_compat(hdesc, &walk, sg, len); nbytes > 0; nbytes = crypto_hash_walk_done(&walk, nbytes)) nbytes = crypto_shash_update(desc, walk.data, nbytes); return nbytes; } static int shash_compat_final(struct hash_desc *hdesc, u8 *out) { struct shash_desc **descp = crypto_hash_ctx(hdesc->tfm); return crypto_shash_final(*descp, out); } static int shash_compat_digest(struct hash_desc *hdesc, struct scatterlist *sg, unsigned int nbytes, u8 *out) { unsigned int offset = sg->offset; int err; if (nbytes < min(sg->length, ((unsigned int)(PAGE_SIZE)) - offset)) { struct shash_desc **descp = crypto_hash_ctx(hdesc->tfm); struct shash_desc *desc = *descp; void *data; desc->flags = hdesc->flags; data = kmap_atomic(sg_page(sg)); err = crypto_shash_digest(desc, data + offset, nbytes, out); kunmap_atomic(data); crypto_yield(desc->flags); goto out; } err = shash_compat_init(hdesc); if (err) goto out; err = shash_compat_update(hdesc, sg, nbytes); if (err) goto out; err = shash_compat_final(hdesc, out); out: return err; } static void crypto_exit_shash_ops_compat(struct crypto_tfm *tfm) { struct shash_desc **descp = crypto_tfm_ctx(tfm); struct shash_desc *desc = *descp; crypto_free_shash(desc->tfm); kzfree(desc); } static int crypto_init_shash_ops_compat(struct crypto_tfm *tfm) { struct hash_tfm *crt = &tfm->crt_hash; struct crypto_alg *calg = tfm->__crt_alg; struct shash_alg *alg = __crypto_shash_alg(calg); struct shash_desc **descp = crypto_tfm_ctx(tfm); struct crypto_shash *shash; struct shash_desc *desc; if (!crypto_mod_get(calg)) return -EAGAIN; shash = crypto_create_tfm(calg, &crypto_shash_type); if (IS_ERR(shash)) { crypto_mod_put(calg); return PTR_ERR(shash); } desc = kmalloc(sizeof(*desc) + crypto_shash_descsize(shash), GFP_KERNEL); if (!desc) { crypto_free_shash(shash); return -ENOMEM; } *descp = desc; desc->tfm = shash; tfm->exit = crypto_exit_shash_ops_compat; crt->init = shash_compat_init; crt->update = shash_compat_update; crt->final = shash_compat_final; crt->digest = shash_compat_digest; crt->setkey = shash_compat_setkey; crt->digestsize = alg->digestsize; return 0; } static int crypto_init_shash_ops(struct crypto_tfm *tfm, u32 type, u32 mask) { switch (mask & CRYPTO_ALG_TYPE_MASK) { case CRYPTO_ALG_TYPE_HASH_MASK: return crypto_init_shash_ops_compat(tfm); } return -EINVAL; } static unsigned int crypto_shash_ctxsize(struct crypto_alg *alg, u32 type, u32 mask) { switch (mask & CRYPTO_ALG_TYPE_MASK) { case CRYPTO_ALG_TYPE_HASH_MASK: return sizeof(struct shash_desc *); } return 0; } static int crypto_shash_init_tfm(struct crypto_tfm *tfm) { struct crypto_shash *hash = __crypto_shash_cast(tfm); hash->descsize = crypto_shash_alg(hash)->descsize; return 0; } static unsigned int crypto_shash_extsize(struct crypto_alg *alg) { return alg->cra_ctxsize; } #ifdef CONFIG_NET static int crypto_shash_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_hash rhash; struct shash_alg *salg = __crypto_shash_alg(alg); strncpy(rhash.type, "shash", sizeof(rhash.type)); rhash.blocksize = alg->cra_blocksize; rhash.digestsize = salg->digestsize; if (nla_put(skb, CRYPTOCFGA_REPORT_HASH, sizeof(struct crypto_report_hash), &rhash)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } #else static int crypto_shash_report(struct sk_buff *skb, struct crypto_alg *alg) { return -ENOSYS; } #endif static void crypto_shash_show(struct seq_file *m, struct crypto_alg *alg) __attribute__ ((unused)); static void crypto_shash_show(struct seq_file *m, struct crypto_alg *alg) { struct shash_alg *salg = __crypto_shash_alg(alg); seq_printf(m, "type : shash\n"); seq_printf(m, "blocksize : %u\n", alg->cra_blocksize); seq_printf(m, "digestsize : %u\n", salg->digestsize); } static const struct crypto_type crypto_shash_type = { .ctxsize = crypto_shash_ctxsize, .extsize = crypto_shash_extsize, .init = crypto_init_shash_ops, .init_tfm = crypto_shash_init_tfm, #ifdef CONFIG_PROC_FS .show = crypto_shash_show, #endif .report = crypto_shash_report, .maskclear = ~CRYPTO_ALG_TYPE_MASK, .maskset = CRYPTO_ALG_TYPE_MASK, .type = CRYPTO_ALG_TYPE_SHASH, .tfmsize = offsetof(struct crypto_shash, base), }; struct crypto_shash *crypto_alloc_shash(const char *alg_name, u32 type, u32 mask) { return crypto_alloc_tfm(alg_name, &crypto_shash_type, type, mask); } EXPORT_SYMBOL_GPL(crypto_alloc_shash); static int shash_prepare_alg(struct shash_alg *alg) { struct crypto_alg *base = &alg->base; if (alg->digestsize > PAGE_SIZE / 8 || alg->descsize > PAGE_SIZE / 8 || alg->statesize > PAGE_SIZE / 8) return -EINVAL; base->cra_type = &crypto_shash_type; base->cra_flags &= ~CRYPTO_ALG_TYPE_MASK; base->cra_flags |= CRYPTO_ALG_TYPE_SHASH; if (!alg->finup) alg->finup = shash_finup_unaligned; if (!alg->digest) alg->digest = shash_digest_unaligned; if (!alg->export) { alg->export = shash_default_export; alg->import = shash_default_import; alg->statesize = alg->descsize; } if (!alg->setkey) alg->setkey = shash_no_setkey; return 0; } int crypto_register_shash(struct shash_alg *alg) { struct crypto_alg *base = &alg->base; int err; err = shash_prepare_alg(alg); if (err) return err; return crypto_register_alg(base); } EXPORT_SYMBOL_GPL(crypto_register_shash); int crypto_unregister_shash(struct shash_alg *alg) { return crypto_unregister_alg(&alg->base); } EXPORT_SYMBOL_GPL(crypto_unregister_shash); int crypto_register_shashes(struct shash_alg *algs, int count) { int i, ret; for (i = 0; i < count; i++) { ret = crypto_register_shash(&algs[i]); if (ret) goto err; } return 0; err: for (--i; i >= 0; --i) crypto_unregister_shash(&algs[i]); return ret; } EXPORT_SYMBOL_GPL(crypto_register_shashes); int crypto_unregister_shashes(struct shash_alg *algs, int count) { int i, ret; for (i = count - 1; i >= 0; --i) { ret = crypto_unregister_shash(&algs[i]); if (ret) pr_err("Failed to unregister %s %s: %d\n", algs[i].base.cra_driver_name, algs[i].base.cra_name, ret); } return 0; } EXPORT_SYMBOL_GPL(crypto_unregister_shashes); int shash_register_instance(struct crypto_template *tmpl, struct shash_instance *inst) { int err; err = shash_prepare_alg(&inst->alg); if (err) return err; return crypto_register_instance(tmpl, shash_crypto_instance(inst)); } EXPORT_SYMBOL_GPL(shash_register_instance); void shash_free_instance(struct crypto_instance *inst) { crypto_drop_spawn(crypto_instance_ctx(inst)); kfree(shash_instance(inst)); } EXPORT_SYMBOL_GPL(shash_free_instance); int crypto_init_shash_spawn(struct crypto_shash_spawn *spawn, struct shash_alg *alg, struct crypto_instance *inst) { return crypto_init_spawn2(&spawn->base, &alg->base, inst, &crypto_shash_type); } EXPORT_SYMBOL_GPL(crypto_init_shash_spawn); struct shash_alg *shash_attr_alg(struct rtattr *rta, u32 type, u32 mask) { struct crypto_alg *alg; alg = crypto_attr_alg2(rta, &crypto_shash_type, type, mask); return IS_ERR(alg) ? ERR_CAST(alg) : container_of(alg, struct shash_alg, base); } EXPORT_SYMBOL_GPL(shash_attr_alg); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Synchronous cryptographic hash type");
./CrossVul/dataset_final_sorted/CWE-310/c/good_5666_7
crossvul-cpp_data_good_1445_3
/* ssl/d1_srvr.c */ /* * DTLS implementation written by Nagendra Modadugu * (nagendra@cs.stanford.edu) for the OpenSSL project 2005. */ /* ==================================================================== * Copyright (c) 1999-2007 The OpenSSL 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: * * 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. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <stdio.h> #include "ssl_locl.h" #include <openssl/buffer.h> #include <openssl/rand.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/md5.h> #include <openssl/bn.h> #ifndef OPENSSL_NO_DH #include <openssl/dh.h> #endif static const SSL_METHOD *dtls1_get_server_method(int ver); static int dtls1_send_hello_verify_request(SSL *s); static const SSL_METHOD *dtls1_get_server_method(int ver) { if (ver == DTLS1_VERSION) return(DTLSv1_server_method()); else if (ver == DTLS1_2_VERSION) return(DTLSv1_2_server_method()); else return(NULL); } IMPLEMENT_dtls1_meth_func(DTLS1_VERSION, DTLSv1_server_method, dtls1_accept, ssl_undefined_function, dtls1_get_server_method, DTLSv1_enc_data) IMPLEMENT_dtls1_meth_func(DTLS1_2_VERSION, DTLSv1_2_server_method, dtls1_accept, ssl_undefined_function, dtls1_get_server_method, DTLSv1_2_enc_data) IMPLEMENT_dtls1_meth_func(DTLS_ANY_VERSION, DTLS_server_method, dtls1_accept, ssl_undefined_function, dtls1_get_server_method, DTLSv1_2_enc_data) int dtls1_accept(SSL *s) { BUF_MEM *buf; unsigned long Time=(unsigned long)time(NULL); void (*cb)(const SSL *ssl,int type,int val)=NULL; unsigned long alg_k; int ret= -1; int new_state,state,skip=0; int listen; #ifndef OPENSSL_NO_SCTP unsigned char sctpauthkey[64]; char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)]; #endif RAND_add(&Time,sizeof(Time),0); ERR_clear_error(); clear_sys_error(); if (s->info_callback != NULL) cb=s->info_callback; else if (s->ctx->info_callback != NULL) cb=s->ctx->info_callback; listen = s->d1->listen; /* init things to blank */ s->in_handshake++; if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); s->d1->listen = listen; #ifndef OPENSSL_NO_SCTP /* Notify SCTP BIO socket to enter handshake * mode and prevent stream identifier other * than 0. Will be ignored if no SCTP is used. */ BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE, s->in_handshake, NULL); #endif if (s->cert == NULL) { SSLerr(SSL_F_DTLS1_ACCEPT,SSL_R_NO_CERTIFICATE_SET); return(-1); } #ifndef OPENSSL_NO_HEARTBEATS /* If we're awaiting a HeartbeatResponse, pretend we * already got and don't await it anymore, because * Heartbeats don't make sense during handshakes anyway. */ if (s->tlsext_hb_pending) { dtls1_stop_timer(s); s->tlsext_hb_pending = 0; s->tlsext_hb_seq++; } #endif for (;;) { state=s->state; switch (s->state) { case SSL_ST_RENEGOTIATE: s->renegotiate=1; /* s->state=SSL_ST_ACCEPT; */ case SSL_ST_BEFORE: case SSL_ST_ACCEPT: case SSL_ST_BEFORE|SSL_ST_ACCEPT: case SSL_ST_OK|SSL_ST_ACCEPT: s->server=1; if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1); if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00)) { SSLerr(SSL_F_DTLS1_ACCEPT, ERR_R_INTERNAL_ERROR); return -1; } s->type=SSL_ST_ACCEPT; if (s->init_buf == NULL) { if ((buf=BUF_MEM_new()) == NULL) { ret= -1; goto end; } if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH)) { BUF_MEM_free(buf); ret= -1; goto end; } s->init_buf=buf; } if (!ssl3_setup_buffers(s)) { ret= -1; goto end; } s->init_num=0; s->d1->change_cipher_spec_ok = 0; /* Should have been reset by ssl3_get_finished, too. */ s->s3->change_cipher_spec = 0; if (s->state != SSL_ST_RENEGOTIATE) { /* Ok, we now need to push on a buffering BIO so that * the output is sent in a way that TCP likes :-) * ...but not with SCTP :-) */ #ifndef OPENSSL_NO_SCTP if (!BIO_dgram_is_sctp(SSL_get_wbio(s))) #endif if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; } ssl3_init_finished_mac(s); s->state=SSL3_ST_SR_CLNT_HELLO_A; s->ctx->stats.sess_accept++; } else { /* s->state == SSL_ST_RENEGOTIATE, * we will just send a HelloRequest */ s->ctx->stats.sess_accept_renegotiate++; s->state=SSL3_ST_SW_HELLO_REQ_A; } break; case SSL3_ST_SW_HELLO_REQ_A: case SSL3_ST_SW_HELLO_REQ_B: s->shutdown=0; dtls1_clear_record_buffer(s); dtls1_start_timer(s); ret=ssl3_send_hello_request(s); if (ret <= 0) goto end; s->s3->tmp.next_state=SSL3_ST_SR_CLNT_HELLO_A; s->state=SSL3_ST_SW_FLUSH; s->init_num=0; ssl3_init_finished_mac(s); break; case SSL3_ST_SW_HELLO_REQ_C: s->state=SSL_ST_OK; break; case SSL3_ST_SR_CLNT_HELLO_A: case SSL3_ST_SR_CLNT_HELLO_B: case SSL3_ST_SR_CLNT_HELLO_C: s->shutdown=0; ret=ssl3_get_client_hello(s); if (ret <= 0) goto end; dtls1_stop_timer(s); if (ret == 1 && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)) s->state = DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A; else s->state = SSL3_ST_SW_SRVR_HELLO_A; s->init_num=0; /* Reflect ClientHello sequence to remain stateless while listening */ if (listen) { memcpy(s->s3->write_sequence, s->s3->read_sequence, sizeof(s->s3->write_sequence)); } /* If we're just listening, stop here */ if (listen && s->state == SSL3_ST_SW_SRVR_HELLO_A) { ret = 2; s->d1->listen = 0; /* Set expected sequence numbers * to continue the handshake. */ s->d1->handshake_read_seq = 2; s->d1->handshake_write_seq = 1; s->d1->next_handshake_write_seq = 1; goto end; } break; case DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A: case DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B: ret = dtls1_send_hello_verify_request(s); if ( ret <= 0) goto end; s->state=SSL3_ST_SW_FLUSH; s->s3->tmp.next_state=SSL3_ST_SR_CLNT_HELLO_A; /* HelloVerifyRequest resets Finished MAC */ if (s->version != DTLS1_BAD_VER) ssl3_init_finished_mac(s); break; #ifndef OPENSSL_NO_SCTP case DTLS1_SCTP_ST_SR_READ_SOCK: if (BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) { s->s3->in_read_app_data=2; s->rwstate=SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); ret = -1; goto end; } s->state=SSL3_ST_SR_FINISHED_A; break; case DTLS1_SCTP_ST_SW_WRITE_SOCK: ret = BIO_dgram_sctp_wait_for_dry(SSL_get_wbio(s)); if (ret < 0) goto end; if (ret == 0) { if (s->d1->next_state != SSL_ST_OK) { s->s3->in_read_app_data=2; s->rwstate=SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); ret = -1; goto end; } } s->state=s->d1->next_state; break; #endif case SSL3_ST_SW_SRVR_HELLO_A: case SSL3_ST_SW_SRVR_HELLO_B: s->renegotiate = 2; dtls1_start_timer(s); ret=ssl3_send_server_hello(s); if (ret <= 0) goto end; if (s->hit) { #ifndef OPENSSL_NO_SCTP /* Add new shared key for SCTP-Auth, * will be ignored if no SCTP used. */ snprintf((char*) labelbuffer, sizeof(DTLS1_SCTP_AUTH_LABEL), DTLS1_SCTP_AUTH_LABEL); SSL_export_keying_material(s, sctpauthkey, sizeof(sctpauthkey), labelbuffer, sizeof(labelbuffer), NULL, 0, 0); BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY, sizeof(sctpauthkey), sctpauthkey); #endif #ifndef OPENSSL_NO_TLSEXT if (s->tlsext_ticket_expected) s->state=SSL3_ST_SW_SESSION_TICKET_A; else s->state=SSL3_ST_SW_CHANGE_A; #else s->state=SSL3_ST_SW_CHANGE_A; #endif } else s->state=SSL3_ST_SW_CERT_A; s->init_num=0; break; case SSL3_ST_SW_CERT_A: case SSL3_ST_SW_CERT_B: /* Check if it is anon DH or normal PSK */ if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { dtls1_start_timer(s); ret=ssl3_send_server_certificate(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_TLSEXT if (s->tlsext_status_expected) s->state=SSL3_ST_SW_CERT_STATUS_A; else s->state=SSL3_ST_SW_KEY_EXCH_A; } else { skip = 1; s->state=SSL3_ST_SW_KEY_EXCH_A; } #else } else skip=1; s->state=SSL3_ST_SW_KEY_EXCH_A; #endif s->init_num=0; break; case SSL3_ST_SW_KEY_EXCH_A: case SSL3_ST_SW_KEY_EXCH_B: alg_k = s->s3->tmp.new_cipher->algorithm_mkey; /* * clear this, it may get reset by * send_server_key_exchange */ s->s3->tmp.use_rsa_tmp=0; /* only send if a DH key exchange or * RSA but we have a sign only certificate */ if ( /* PSK: send ServerKeyExchange if PSK identity * hint if provided */ #ifndef OPENSSL_NO_PSK || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint) #endif || (alg_k & (SSL_kDHE|SSL_kDHr|SSL_kDHd)) || (alg_k & SSL_kECDHE) || ((alg_k & SSL_kRSA) && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher) ) ) ) ) { dtls1_start_timer(s); ret=ssl3_send_server_key_exchange(s); if (ret <= 0) goto end; } else skip=1; s->state=SSL3_ST_SW_CERT_REQ_A; s->init_num=0; break; case SSL3_ST_SW_CERT_REQ_A: case SSL3_ST_SW_CERT_REQ_B: if (/* don't request cert unless asked for it: */ !(s->verify_mode & SSL_VERIFY_PEER) || /* if SSL_VERIFY_CLIENT_ONCE is set, * don't request cert during re-negotiation: */ ((s->session->peer != NULL) && (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) || /* never request cert in anonymous ciphersuites * (see section "Certificate request" in SSL 3 drafts * and in RFC 2246): */ ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) && /* ... except when the application insists on verification * (against the specs, but s3_clnt.c accepts this for SSL 3) */ !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) || /* never request cert in Kerberos ciphersuites */ (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) /* With normal PSK Certificates and * Certificate Requests are omitted */ || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { /* no cert request */ skip=1; s->s3->tmp.cert_request=0; s->state=SSL3_ST_SW_SRVR_DONE_A; #ifndef OPENSSL_NO_SCTP if (BIO_dgram_is_sctp(SSL_get_wbio(s))) { s->d1->next_state = SSL3_ST_SW_SRVR_DONE_A; s->state = DTLS1_SCTP_ST_SW_WRITE_SOCK; } #endif } else { s->s3->tmp.cert_request=1; dtls1_start_timer(s); ret=ssl3_send_certificate_request(s); if (ret <= 0) goto end; #ifndef NETSCAPE_HANG_BUG s->state=SSL3_ST_SW_SRVR_DONE_A; #ifndef OPENSSL_NO_SCTP if (BIO_dgram_is_sctp(SSL_get_wbio(s))) { s->d1->next_state = SSL3_ST_SW_SRVR_DONE_A; s->state = DTLS1_SCTP_ST_SW_WRITE_SOCK; } #endif #else s->state=SSL3_ST_SW_FLUSH; s->s3->tmp.next_state=SSL3_ST_SR_CERT_A; #ifndef OPENSSL_NO_SCTP if (BIO_dgram_is_sctp(SSL_get_wbio(s))) { s->d1->next_state = s->s3->tmp.next_state; s->s3->tmp.next_state=DTLS1_SCTP_ST_SW_WRITE_SOCK; } #endif #endif s->init_num=0; } break; case SSL3_ST_SW_SRVR_DONE_A: case SSL3_ST_SW_SRVR_DONE_B: dtls1_start_timer(s); ret=ssl3_send_server_done(s); if (ret <= 0) goto end; s->s3->tmp.next_state=SSL3_ST_SR_CERT_A; s->state=SSL3_ST_SW_FLUSH; s->init_num=0; break; case SSL3_ST_SW_FLUSH: s->rwstate=SSL_WRITING; if (BIO_flush(s->wbio) <= 0) { /* If the write error was fatal, stop trying */ if (!BIO_should_retry(s->wbio)) { s->rwstate=SSL_NOTHING; s->state=s->s3->tmp.next_state; } ret= -1; goto end; } s->rwstate=SSL_NOTHING; s->state=s->s3->tmp.next_state; break; case SSL3_ST_SR_CERT_A: case SSL3_ST_SR_CERT_B: if (s->s3->tmp.cert_request) { ret=ssl3_get_client_certificate(s); if (ret <= 0) goto end; } s->init_num=0; s->state=SSL3_ST_SR_KEY_EXCH_A; break; case SSL3_ST_SR_KEY_EXCH_A: case SSL3_ST_SR_KEY_EXCH_B: ret=ssl3_get_client_key_exchange(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_SCTP /* Add new shared key for SCTP-Auth, * will be ignored if no SCTP used. */ snprintf((char *) labelbuffer, sizeof(DTLS1_SCTP_AUTH_LABEL), DTLS1_SCTP_AUTH_LABEL); SSL_export_keying_material(s, sctpauthkey, sizeof(sctpauthkey), labelbuffer, sizeof(labelbuffer), NULL, 0, 0); BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY, sizeof(sctpauthkey), sctpauthkey); #endif s->state=SSL3_ST_SR_CERT_VRFY_A; s->init_num=0; if (ret == 2) { /* For the ECDH ciphersuites when * the client sends its ECDH pub key in * a certificate, the CertificateVerify * message is not sent. */ s->state=SSL3_ST_SR_FINISHED_A; s->init_num = 0; } else if (SSL_USE_SIGALGS(s)) { s->state=SSL3_ST_SR_CERT_VRFY_A; s->init_num=0; if (!s->session->peer) break; /* For sigalgs freeze the handshake buffer * at this point and digest cached records. */ if (!s->s3->handshake_buffer) { SSLerr(SSL_F_DTLS1_ACCEPT,ERR_R_INTERNAL_ERROR); return -1; } s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE; if (!ssl3_digest_cached_records(s)) return -1; } else { s->state=SSL3_ST_SR_CERT_VRFY_A; s->init_num=0; /* We need to get hashes here so if there is * a client cert, it can be verified */ s->method->ssl3_enc->cert_verify_mac(s, NID_md5, &(s->s3->tmp.cert_verify_md[0])); s->method->ssl3_enc->cert_verify_mac(s, NID_sha1, &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH])); } break; case SSL3_ST_SR_CERT_VRFY_A: case SSL3_ST_SR_CERT_VRFY_B: /* * This *should* be the first time we enable CCS, but be * extra careful about surrounding code changes. We need * to set this here because we don't know if we're * expecting a CertificateVerify or not. */ if (!s->s3->change_cipher_spec) s->d1->change_cipher_spec_ok = 1; /* we should decide if we expected this one */ ret=ssl3_get_cert_verify(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_SCTP if (BIO_dgram_is_sctp(SSL_get_wbio(s)) && state == SSL_ST_RENEGOTIATE) s->state=DTLS1_SCTP_ST_SR_READ_SOCK; else #endif s->state=SSL3_ST_SR_FINISHED_A; s->init_num=0; break; case SSL3_ST_SR_FINISHED_A: case SSL3_ST_SR_FINISHED_B: /* * Enable CCS for resumed handshakes. * In a full handshake, we end up here through * SSL3_ST_SR_CERT_VRFY_B, so change_cipher_spec_ok was * already set. Receiving a CCS clears the flag, so make * sure not to re-enable it to ban duplicates. * s->s3->change_cipher_spec is set when a CCS is * processed in d1_pkt.c, and remains set until * the client's Finished message is read. */ if (!s->s3->change_cipher_spec) s->d1->change_cipher_spec_ok = 1; ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A, SSL3_ST_SR_FINISHED_B); if (ret <= 0) goto end; dtls1_stop_timer(s); if (s->hit) s->state=SSL_ST_OK; #ifndef OPENSSL_NO_TLSEXT else if (s->tlsext_ticket_expected) s->state=SSL3_ST_SW_SESSION_TICKET_A; #endif else s->state=SSL3_ST_SW_CHANGE_A; s->init_num=0; break; #ifndef OPENSSL_NO_TLSEXT case SSL3_ST_SW_SESSION_TICKET_A: case SSL3_ST_SW_SESSION_TICKET_B: ret=ssl3_send_newsession_ticket(s); if (ret <= 0) goto end; s->state=SSL3_ST_SW_CHANGE_A; s->init_num=0; break; case SSL3_ST_SW_CERT_STATUS_A: case SSL3_ST_SW_CERT_STATUS_B: ret=ssl3_send_cert_status(s); if (ret <= 0) goto end; s->state=SSL3_ST_SW_KEY_EXCH_A; s->init_num=0; break; #endif case SSL3_ST_SW_CHANGE_A: case SSL3_ST_SW_CHANGE_B: s->session->cipher=s->s3->tmp.new_cipher; if (!s->method->ssl3_enc->setup_key_block(s)) { ret= -1; goto end; } ret=dtls1_send_change_cipher_spec(s, SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B); if (ret <= 0) goto end; #ifndef OPENSSL_NO_SCTP if (!s->hit) { /* Change to new shared key of SCTP-Auth, * will be ignored if no SCTP used. */ BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY, 0, NULL); } #endif s->state=SSL3_ST_SW_FINISHED_A; s->init_num=0; if (!s->method->ssl3_enc->change_cipher_state(s, SSL3_CHANGE_CIPHER_SERVER_WRITE)) { ret= -1; goto end; } dtls1_reset_seq_numbers(s, SSL3_CC_WRITE); break; case SSL3_ST_SW_FINISHED_A: case SSL3_ST_SW_FINISHED_B: ret=ssl3_send_finished(s, SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B, s->method->ssl3_enc->server_finished_label, s->method->ssl3_enc->server_finished_label_len); if (ret <= 0) goto end; s->state=SSL3_ST_SW_FLUSH; if (s->hit) { s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A; #ifndef OPENSSL_NO_SCTP /* Change to new shared key of SCTP-Auth, * will be ignored if no SCTP used. */ BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY, 0, NULL); #endif } else { s->s3->tmp.next_state=SSL_ST_OK; #ifndef OPENSSL_NO_SCTP if (BIO_dgram_is_sctp(SSL_get_wbio(s))) { s->d1->next_state = s->s3->tmp.next_state; s->s3->tmp.next_state=DTLS1_SCTP_ST_SW_WRITE_SOCK; } #endif } s->init_num=0; break; case SSL_ST_OK: /* clean a few things up */ ssl3_cleanup_key_block(s); #if 0 BUF_MEM_free(s->init_buf); s->init_buf=NULL; #endif /* remove buffering on output */ ssl_free_wbio_buffer(s); s->init_num=0; if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */ { s->renegotiate=0; s->new_session=0; ssl_update_cache(s,SSL_SESS_CACHE_SERVER); s->ctx->stats.sess_accept_good++; /* s->server=1; */ s->handshake_func=dtls1_accept; if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1); } ret = 1; /* done handshaking, next message is client hello */ s->d1->handshake_read_seq = 0; /* next message is server hello */ s->d1->handshake_write_seq = 0; s->d1->next_handshake_write_seq = 0; goto end; /* break; */ default: SSLerr(SSL_F_DTLS1_ACCEPT,SSL_R_UNKNOWN_STATE); ret= -1; goto end; /* break; */ } if (!s->s3->tmp.reuse_message && !skip) { if (s->debug) { if ((ret=BIO_flush(s->wbio)) <= 0) goto end; } if ((cb != NULL) && (s->state != state)) { new_state=s->state; s->state=state; cb(s,SSL_CB_ACCEPT_LOOP,1); s->state=new_state; } } skip=0; } end: /* BIO_flush(s->wbio); */ s->in_handshake--; #ifndef OPENSSL_NO_SCTP /* Notify SCTP BIO socket to leave handshake * mode and prevent stream identifier other * than 0. Will be ignored if no SCTP is used. */ BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE, s->in_handshake, NULL); #endif if (cb != NULL) cb(s,SSL_CB_ACCEPT_EXIT,ret); return(ret); } int dtls1_send_hello_verify_request(SSL *s) { unsigned int msg_len; unsigned char *msg, *buf, *p; if (s->state == DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A) { buf = (unsigned char *)s->init_buf->data; msg = p = &(buf[DTLS1_HM_HEADER_LENGTH]); /* Always use DTLS 1.0 version: see RFC 6347 */ *(p++) = DTLS1_VERSION >> 8; *(p++) = DTLS1_VERSION & 0xFF; if (s->ctx->app_gen_cookie_cb == NULL || s->ctx->app_gen_cookie_cb(s, s->d1->cookie, &(s->d1->cookie_len)) == 0) { SSLerr(SSL_F_DTLS1_SEND_HELLO_VERIFY_REQUEST,ERR_R_INTERNAL_ERROR); return 0; } *(p++) = (unsigned char) s->d1->cookie_len; memcpy(p, s->d1->cookie, s->d1->cookie_len); p += s->d1->cookie_len; msg_len = p - msg; dtls1_set_message_header(s, buf, DTLS1_MT_HELLO_VERIFY_REQUEST, msg_len, 0, msg_len); s->state=DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B; /* number of bytes to write */ s->init_num=p-buf; s->init_off=0; } /* s->state = DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B */ return(dtls1_do_write(s,SSL3_RT_HANDSHAKE)); }
./CrossVul/dataset_final_sorted/CWE-310/c/good_1445_3
crossvul-cpp_data_good_5666_2
/* * Asynchronous Cryptographic Hash operations. * * This is the asynchronous version of hash.c with notification of * completion via a callback. * * Copyright (c) 2008 Loc Ho <lho@amcc.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 <crypto/internal/hash.h> #include <crypto/scatterwalk.h> #include <linux/err.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/seq_file.h> #include <linux/cryptouser.h> #include <net/netlink.h> #include "internal.h" struct ahash_request_priv { crypto_completion_t complete; void *data; u8 *result; void *ubuf[] CRYPTO_MINALIGN_ATTR; }; static inline struct ahash_alg *crypto_ahash_alg(struct crypto_ahash *hash) { return container_of(crypto_hash_alg_common(hash), struct ahash_alg, halg); } static int hash_walk_next(struct crypto_hash_walk *walk) { unsigned int alignmask = walk->alignmask; unsigned int offset = walk->offset; unsigned int nbytes = min(walk->entrylen, ((unsigned int)(PAGE_SIZE)) - offset); walk->data = kmap_atomic(walk->pg); walk->data += offset; if (offset & alignmask) { unsigned int unaligned = alignmask + 1 - (offset & alignmask); if (nbytes > unaligned) nbytes = unaligned; } walk->entrylen -= nbytes; return nbytes; } static int hash_walk_new_entry(struct crypto_hash_walk *walk) { struct scatterlist *sg; sg = walk->sg; walk->pg = sg_page(sg); walk->offset = sg->offset; walk->entrylen = sg->length; if (walk->entrylen > walk->total) walk->entrylen = walk->total; walk->total -= walk->entrylen; return hash_walk_next(walk); } int crypto_hash_walk_done(struct crypto_hash_walk *walk, int err) { unsigned int alignmask = walk->alignmask; unsigned int nbytes = walk->entrylen; walk->data -= walk->offset; if (nbytes && walk->offset & alignmask && !err) { walk->offset = ALIGN(walk->offset, alignmask + 1); walk->data += walk->offset; nbytes = min(nbytes, ((unsigned int)(PAGE_SIZE)) - walk->offset); walk->entrylen -= nbytes; return nbytes; } kunmap_atomic(walk->data); crypto_yield(walk->flags); if (err) return err; if (nbytes) { walk->offset = 0; walk->pg++; return hash_walk_next(walk); } if (!walk->total) return 0; walk->sg = scatterwalk_sg_next(walk->sg); return hash_walk_new_entry(walk); } EXPORT_SYMBOL_GPL(crypto_hash_walk_done); int crypto_hash_walk_first(struct ahash_request *req, struct crypto_hash_walk *walk) { walk->total = req->nbytes; if (!walk->total) return 0; walk->alignmask = crypto_ahash_alignmask(crypto_ahash_reqtfm(req)); walk->sg = req->src; walk->flags = req->base.flags; return hash_walk_new_entry(walk); } EXPORT_SYMBOL_GPL(crypto_hash_walk_first); int crypto_hash_walk_first_compat(struct hash_desc *hdesc, struct crypto_hash_walk *walk, struct scatterlist *sg, unsigned int len) { walk->total = len; if (!walk->total) return 0; walk->alignmask = crypto_hash_alignmask(hdesc->tfm); walk->sg = sg; walk->flags = hdesc->flags; return hash_walk_new_entry(walk); } static int ahash_setkey_unaligned(struct crypto_ahash *tfm, const u8 *key, unsigned int keylen) { unsigned long alignmask = crypto_ahash_alignmask(tfm); int ret; u8 *buffer, *alignbuffer; unsigned long absize; absize = keylen + alignmask; buffer = kmalloc(absize, GFP_KERNEL); if (!buffer) return -ENOMEM; alignbuffer = (u8 *)ALIGN((unsigned long)buffer, alignmask + 1); memcpy(alignbuffer, key, keylen); ret = tfm->setkey(tfm, alignbuffer, keylen); kzfree(buffer); return ret; } int crypto_ahash_setkey(struct crypto_ahash *tfm, const u8 *key, unsigned int keylen) { unsigned long alignmask = crypto_ahash_alignmask(tfm); if ((unsigned long)key & alignmask) return ahash_setkey_unaligned(tfm, key, keylen); return tfm->setkey(tfm, key, keylen); } EXPORT_SYMBOL_GPL(crypto_ahash_setkey); static int ahash_nosetkey(struct crypto_ahash *tfm, const u8 *key, unsigned int keylen) { return -ENOSYS; } static inline unsigned int ahash_align_buffer_size(unsigned len, unsigned long mask) { return len + (mask & ~(crypto_tfm_ctx_alignment() - 1)); } static void ahash_op_unaligned_finish(struct ahash_request *req, int err) { struct ahash_request_priv *priv = req->priv; if (err == -EINPROGRESS) return; if (!err) memcpy(priv->result, req->result, crypto_ahash_digestsize(crypto_ahash_reqtfm(req))); kzfree(priv); } static void ahash_op_unaligned_done(struct crypto_async_request *req, int err) { struct ahash_request *areq = req->data; struct ahash_request_priv *priv = areq->priv; crypto_completion_t complete = priv->complete; void *data = priv->data; ahash_op_unaligned_finish(areq, err); complete(data, err); } static int ahash_op_unaligned(struct ahash_request *req, int (*op)(struct ahash_request *)) { struct crypto_ahash *tfm = crypto_ahash_reqtfm(req); unsigned long alignmask = crypto_ahash_alignmask(tfm); unsigned int ds = crypto_ahash_digestsize(tfm); struct ahash_request_priv *priv; int err; priv = kmalloc(sizeof(*priv) + ahash_align_buffer_size(ds, alignmask), (req->base.flags & CRYPTO_TFM_REQ_MAY_SLEEP) ? GFP_KERNEL : GFP_ATOMIC); if (!priv) return -ENOMEM; priv->result = req->result; priv->complete = req->base.complete; priv->data = req->base.data; req->result = PTR_ALIGN((u8 *)priv->ubuf, alignmask + 1); req->base.complete = ahash_op_unaligned_done; req->base.data = req; req->priv = priv; err = op(req); ahash_op_unaligned_finish(req, err); return err; } static int crypto_ahash_op(struct ahash_request *req, int (*op)(struct ahash_request *)) { struct crypto_ahash *tfm = crypto_ahash_reqtfm(req); unsigned long alignmask = crypto_ahash_alignmask(tfm); if ((unsigned long)req->result & alignmask) return ahash_op_unaligned(req, op); return op(req); } int crypto_ahash_final(struct ahash_request *req) { return crypto_ahash_op(req, crypto_ahash_reqtfm(req)->final); } EXPORT_SYMBOL_GPL(crypto_ahash_final); int crypto_ahash_finup(struct ahash_request *req) { return crypto_ahash_op(req, crypto_ahash_reqtfm(req)->finup); } EXPORT_SYMBOL_GPL(crypto_ahash_finup); int crypto_ahash_digest(struct ahash_request *req) { return crypto_ahash_op(req, crypto_ahash_reqtfm(req)->digest); } EXPORT_SYMBOL_GPL(crypto_ahash_digest); static void ahash_def_finup_finish2(struct ahash_request *req, int err) { struct ahash_request_priv *priv = req->priv; if (err == -EINPROGRESS) return; if (!err) memcpy(priv->result, req->result, crypto_ahash_digestsize(crypto_ahash_reqtfm(req))); kzfree(priv); } static void ahash_def_finup_done2(struct crypto_async_request *req, int err) { struct ahash_request *areq = req->data; struct ahash_request_priv *priv = areq->priv; crypto_completion_t complete = priv->complete; void *data = priv->data; ahash_def_finup_finish2(areq, err); complete(data, err); } static int ahash_def_finup_finish1(struct ahash_request *req, int err) { if (err) goto out; req->base.complete = ahash_def_finup_done2; req->base.flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP; err = crypto_ahash_reqtfm(req)->final(req); out: ahash_def_finup_finish2(req, err); return err; } static void ahash_def_finup_done1(struct crypto_async_request *req, int err) { struct ahash_request *areq = req->data; struct ahash_request_priv *priv = areq->priv; crypto_completion_t complete = priv->complete; void *data = priv->data; err = ahash_def_finup_finish1(areq, err); complete(data, err); } static int ahash_def_finup(struct ahash_request *req) { struct crypto_ahash *tfm = crypto_ahash_reqtfm(req); unsigned long alignmask = crypto_ahash_alignmask(tfm); unsigned int ds = crypto_ahash_digestsize(tfm); struct ahash_request_priv *priv; priv = kmalloc(sizeof(*priv) + ahash_align_buffer_size(ds, alignmask), (req->base.flags & CRYPTO_TFM_REQ_MAY_SLEEP) ? GFP_KERNEL : GFP_ATOMIC); if (!priv) return -ENOMEM; priv->result = req->result; priv->complete = req->base.complete; priv->data = req->base.data; req->result = PTR_ALIGN((u8 *)priv->ubuf, alignmask + 1); req->base.complete = ahash_def_finup_done1; req->base.data = req; req->priv = priv; return ahash_def_finup_finish1(req, tfm->update(req)); } static int ahash_no_export(struct ahash_request *req, void *out) { return -ENOSYS; } static int ahash_no_import(struct ahash_request *req, const void *in) { return -ENOSYS; } static int crypto_ahash_init_tfm(struct crypto_tfm *tfm) { struct crypto_ahash *hash = __crypto_ahash_cast(tfm); struct ahash_alg *alg = crypto_ahash_alg(hash); hash->setkey = ahash_nosetkey; hash->export = ahash_no_export; hash->import = ahash_no_import; if (tfm->__crt_alg->cra_type != &crypto_ahash_type) return crypto_init_shash_ops_async(tfm); hash->init = alg->init; hash->update = alg->update; hash->final = alg->final; hash->finup = alg->finup ?: ahash_def_finup; hash->digest = alg->digest; if (alg->setkey) hash->setkey = alg->setkey; if (alg->export) hash->export = alg->export; if (alg->import) hash->import = alg->import; return 0; } static unsigned int crypto_ahash_extsize(struct crypto_alg *alg) { if (alg->cra_type == &crypto_ahash_type) return alg->cra_ctxsize; return sizeof(struct crypto_shash *); } #ifdef CONFIG_NET static int crypto_ahash_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_hash rhash; strncpy(rhash.type, "ahash", sizeof(rhash.type)); rhash.blocksize = alg->cra_blocksize; rhash.digestsize = __crypto_hash_alg_common(alg)->digestsize; if (nla_put(skb, CRYPTOCFGA_REPORT_HASH, sizeof(struct crypto_report_hash), &rhash)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } #else static int crypto_ahash_report(struct sk_buff *skb, struct crypto_alg *alg) { return -ENOSYS; } #endif static void crypto_ahash_show(struct seq_file *m, struct crypto_alg *alg) __attribute__ ((unused)); static void crypto_ahash_show(struct seq_file *m, struct crypto_alg *alg) { seq_printf(m, "type : ahash\n"); seq_printf(m, "async : %s\n", alg->cra_flags & CRYPTO_ALG_ASYNC ? "yes" : "no"); seq_printf(m, "blocksize : %u\n", alg->cra_blocksize); seq_printf(m, "digestsize : %u\n", __crypto_hash_alg_common(alg)->digestsize); } const struct crypto_type crypto_ahash_type = { .extsize = crypto_ahash_extsize, .init_tfm = crypto_ahash_init_tfm, #ifdef CONFIG_PROC_FS .show = crypto_ahash_show, #endif .report = crypto_ahash_report, .maskclear = ~CRYPTO_ALG_TYPE_MASK, .maskset = CRYPTO_ALG_TYPE_AHASH_MASK, .type = CRYPTO_ALG_TYPE_AHASH, .tfmsize = offsetof(struct crypto_ahash, base), }; EXPORT_SYMBOL_GPL(crypto_ahash_type); struct crypto_ahash *crypto_alloc_ahash(const char *alg_name, u32 type, u32 mask) { return crypto_alloc_tfm(alg_name, &crypto_ahash_type, type, mask); } EXPORT_SYMBOL_GPL(crypto_alloc_ahash); static int ahash_prepare_alg(struct ahash_alg *alg) { struct crypto_alg *base = &alg->halg.base; if (alg->halg.digestsize > PAGE_SIZE / 8 || alg->halg.statesize > PAGE_SIZE / 8) return -EINVAL; base->cra_type = &crypto_ahash_type; base->cra_flags &= ~CRYPTO_ALG_TYPE_MASK; base->cra_flags |= CRYPTO_ALG_TYPE_AHASH; return 0; } int crypto_register_ahash(struct ahash_alg *alg) { struct crypto_alg *base = &alg->halg.base; int err; err = ahash_prepare_alg(alg); if (err) return err; return crypto_register_alg(base); } EXPORT_SYMBOL_GPL(crypto_register_ahash); int crypto_unregister_ahash(struct ahash_alg *alg) { return crypto_unregister_alg(&alg->halg.base); } EXPORT_SYMBOL_GPL(crypto_unregister_ahash); int ahash_register_instance(struct crypto_template *tmpl, struct ahash_instance *inst) { int err; err = ahash_prepare_alg(&inst->alg); if (err) return err; return crypto_register_instance(tmpl, ahash_crypto_instance(inst)); } EXPORT_SYMBOL_GPL(ahash_register_instance); void ahash_free_instance(struct crypto_instance *inst) { crypto_drop_spawn(crypto_instance_ctx(inst)); kfree(ahash_instance(inst)); } EXPORT_SYMBOL_GPL(ahash_free_instance); int crypto_init_ahash_spawn(struct crypto_ahash_spawn *spawn, struct hash_alg_common *alg, struct crypto_instance *inst) { return crypto_init_spawn2(&spawn->base, &alg->base, inst, &crypto_ahash_type); } EXPORT_SYMBOL_GPL(crypto_init_ahash_spawn); struct hash_alg_common *ahash_attr_alg(struct rtattr *rta, u32 type, u32 mask) { struct crypto_alg *alg; alg = crypto_attr_alg2(rta, &crypto_ahash_type, type, mask); return IS_ERR(alg) ? ERR_CAST(alg) : __crypto_hash_alg_common(alg); } EXPORT_SYMBOL_GPL(ahash_attr_alg); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Asynchronous cryptographic hash type");
./CrossVul/dataset_final_sorted/CWE-310/c/good_5666_2
crossvul-cpp_data_good_2309_3
/* crypto/ecdsa/ecdsa_vrf.c */ /* * Written by Nils Larsch for the OpenSSL project */ /* ==================================================================== * Copyright (c) 1998-2002 The OpenSSL 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: * * 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. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include "ecs_locl.h" #include "cryptlib.h" #ifndef OPENSSL_NO_ENGINE #include <openssl/engine.h> #endif /*- * returns * 1: correct signature * 0: incorrect signature * -1: error */ int ECDSA_do_verify(const unsigned char *dgst, int dgst_len, const ECDSA_SIG *sig, EC_KEY *eckey) { ECDSA_DATA *ecdsa = ecdsa_check(eckey); if (ecdsa == NULL) return 0; return ecdsa->meth->ecdsa_do_verify(dgst, dgst_len, sig, eckey); } /*- * returns * 1: correct signature * 0: incorrect signature * -1: error */ int ECDSA_verify(int type, const unsigned char *dgst, int dgst_len, const unsigned char *sigbuf, int sig_len, EC_KEY *eckey) { ECDSA_SIG *s; const unsigned char *p = sigbuf; unsigned char *der = NULL; int derlen = -1; int ret=-1; s = ECDSA_SIG_new(); if (s == NULL) return(ret); if (d2i_ECDSA_SIG(&s, &p, sig_len) == NULL) goto err; /* Ensure signature uses DER and doesn't have trailing garbage */ derlen = i2d_ECDSA_SIG(s, &der); if (derlen != sig_len || memcmp(sigbuf, der, derlen)) goto err; ret=ECDSA_do_verify(dgst, dgst_len, s, eckey); err: if (derlen > 0) { OPENSSL_cleanse(der, derlen); OPENSSL_free(der); } ECDSA_SIG_free(s); return(ret); }
./CrossVul/dataset_final_sorted/CWE-310/c/good_2309_3
crossvul-cpp_data_bad_5741_0
/* SCTP kernel implementation * (C) Copyright IBM Corp. 2002, 2004 * Copyright (c) 2001 Nokia, Inc. * Copyright (c) 2001 La Monte H.P. Yarroll * Copyright (c) 2002-2003 Intel Corp. * * This file is part of the SCTP kernel implementation * * SCTP over IPv6. * * 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 <linux-sctp@vger.kernel.org> * * Written or modified by: * Le Yanqun <yanqun.le@nokia.com> * Hui Huang <hui.huang@nokia.com> * La Monte H.P. Yarroll <piggy@acm.org> * Sridhar Samudrala <sri@us.ibm.com> * Jon Grimm <jgrimm@us.ibm.com> * Ardelle Fan <ardelle.fan@intel.com> * * Based on: * linux/net/ipv6/tcp_ipv6.c */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/in.h> #include <linux/in6.h> #include <linux/netdevice.h> #include <linux/init.h> #include <linux/ipsec.h> #include <linux/slab.h> #include <linux/ipv6.h> #include <linux/icmpv6.h> #include <linux/random.h> #include <linux/seq_file.h> #include <net/protocol.h> #include <net/ndisc.h> #include <net/ip.h> #include <net/ipv6.h> #include <net/transp_v6.h> #include <net/addrconf.h> #include <net/ip6_route.h> #include <net/inet_common.h> #include <net/inet_ecn.h> #include <net/sctp/sctp.h> #include <asm/uaccess.h> static inline int sctp_v6_addr_match_len(union sctp_addr *s1, union sctp_addr *s2); static void sctp_v6_to_addr(union sctp_addr *addr, struct in6_addr *saddr, __be16 port); static int sctp_v6_cmp_addr(const union sctp_addr *addr1, const union sctp_addr *addr2); /* Event handler for inet6 address addition/deletion events. * The sctp_local_addr_list needs to be protocted by a spin lock since * multiple notifiers (say IPv4 and IPv6) may be running at the same * time and thus corrupt the list. * The reader side is protected with RCU. */ static int sctp_inet6addr_event(struct notifier_block *this, unsigned long ev, void *ptr) { struct inet6_ifaddr *ifa = (struct inet6_ifaddr *)ptr; struct sctp_sockaddr_entry *addr = NULL; struct sctp_sockaddr_entry *temp; struct net *net = dev_net(ifa->idev->dev); int found = 0; switch (ev) { case NETDEV_UP: addr = kmalloc(sizeof(struct sctp_sockaddr_entry), GFP_ATOMIC); if (addr) { addr->a.v6.sin6_family = AF_INET6; addr->a.v6.sin6_port = 0; addr->a.v6.sin6_addr = ifa->addr; addr->a.v6.sin6_scope_id = ifa->idev->dev->ifindex; addr->valid = 1; spin_lock_bh(&net->sctp.local_addr_lock); list_add_tail_rcu(&addr->list, &net->sctp.local_addr_list); sctp_addr_wq_mgmt(net, addr, SCTP_ADDR_NEW); spin_unlock_bh(&net->sctp.local_addr_lock); } break; case NETDEV_DOWN: spin_lock_bh(&net->sctp.local_addr_lock); list_for_each_entry_safe(addr, temp, &net->sctp.local_addr_list, list) { if (addr->a.sa.sa_family == AF_INET6 && ipv6_addr_equal(&addr->a.v6.sin6_addr, &ifa->addr)) { sctp_addr_wq_mgmt(net, addr, SCTP_ADDR_DEL); found = 1; addr->valid = 0; list_del_rcu(&addr->list); break; } } spin_unlock_bh(&net->sctp.local_addr_lock); if (found) kfree_rcu(addr, rcu); break; } return NOTIFY_DONE; } static struct notifier_block sctp_inet6addr_notifier = { .notifier_call = sctp_inet6addr_event, }; /* ICMP error handler. */ static void sctp_v6_err(struct sk_buff *skb, struct inet6_skb_parm *opt, u8 type, u8 code, int offset, __be32 info) { struct inet6_dev *idev; struct sock *sk; struct sctp_association *asoc; struct sctp_transport *transport; struct ipv6_pinfo *np; __u16 saveip, savesctp; int err; struct net *net = dev_net(skb->dev); idev = in6_dev_get(skb->dev); /* Fix up skb to look at the embedded net header. */ saveip = skb->network_header; savesctp = skb->transport_header; skb_reset_network_header(skb); skb_set_transport_header(skb, offset); sk = sctp_err_lookup(net, AF_INET6, skb, sctp_hdr(skb), &asoc, &transport); /* Put back, the original pointers. */ skb->network_header = saveip; skb->transport_header = savesctp; if (!sk) { ICMP6_INC_STATS_BH(net, idev, ICMP6_MIB_INERRORS); goto out; } /* Warning: The sock lock is held. Remember to call * sctp_err_finish! */ switch (type) { case ICMPV6_PKT_TOOBIG: sctp_icmp_frag_needed(sk, asoc, transport, ntohl(info)); goto out_unlock; case ICMPV6_PARAMPROB: if (ICMPV6_UNK_NEXTHDR == code) { sctp_icmp_proto_unreachable(sk, asoc, transport); goto out_unlock; } break; case NDISC_REDIRECT: sctp_icmp_redirect(sk, transport, skb); break; default: break; } np = inet6_sk(sk); icmpv6_err_convert(type, code, &err); if (!sock_owned_by_user(sk) && np->recverr) { sk->sk_err = err; sk->sk_error_report(sk); } else { /* Only an error on timeout */ sk->sk_err_soft = err; } out_unlock: sctp_err_finish(sk, asoc); out: if (likely(idev != NULL)) in6_dev_put(idev); } /* Based on tcp_v6_xmit() in tcp_ipv6.c. */ static int sctp_v6_xmit(struct sk_buff *skb, struct sctp_transport *transport) { struct sock *sk = skb->sk; struct ipv6_pinfo *np = inet6_sk(sk); struct flowi6 fl6; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = sk->sk_protocol; /* Fill in the dest address from the route entry passed with the skb * and the source address from the transport. */ fl6.daddr = transport->ipaddr.v6.sin6_addr; fl6.saddr = transport->saddr.v6.sin6_addr; fl6.flowlabel = np->flow_label; IP6_ECN_flow_xmit(sk, fl6.flowlabel); if (ipv6_addr_type(&fl6.saddr) & IPV6_ADDR_LINKLOCAL) fl6.flowi6_oif = transport->saddr.v6.sin6_scope_id; else fl6.flowi6_oif = sk->sk_bound_dev_if; if (np->opt && np->opt->srcrt) { struct rt0_hdr *rt0 = (struct rt0_hdr *) np->opt->srcrt; fl6.daddr = *rt0->addr; } pr_debug("%s: skb:%p, len:%d, src:%pI6 dst:%pI6\n", __func__, skb, skb->len, &fl6.saddr, &fl6.daddr); SCTP_INC_STATS(sock_net(sk), SCTP_MIB_OUTSCTPPACKS); if (!(transport->param_flags & SPP_PMTUD_ENABLE)) skb->local_df = 1; return ip6_xmit(sk, skb, &fl6, np->opt, np->tclass); } /* Returns the dst cache entry for the given source and destination ip * addresses. */ static void sctp_v6_get_dst(struct sctp_transport *t, union sctp_addr *saddr, struct flowi *fl, struct sock *sk) { struct sctp_association *asoc = t->asoc; struct dst_entry *dst = NULL; struct flowi6 *fl6 = &fl->u.ip6; struct sctp_bind_addr *bp; struct sctp_sockaddr_entry *laddr; union sctp_addr *baddr = NULL; union sctp_addr *daddr = &t->ipaddr; union sctp_addr dst_saddr; __u8 matchlen = 0; __u8 bmatchlen; sctp_scope_t scope; memset(fl6, 0, sizeof(struct flowi6)); fl6->daddr = daddr->v6.sin6_addr; fl6->fl6_dport = daddr->v6.sin6_port; fl6->flowi6_proto = IPPROTO_SCTP; if (ipv6_addr_type(&daddr->v6.sin6_addr) & IPV6_ADDR_LINKLOCAL) fl6->flowi6_oif = daddr->v6.sin6_scope_id; pr_debug("%s: dst=%pI6 ", __func__, &fl6->daddr); if (asoc) fl6->fl6_sport = htons(asoc->base.bind_addr.port); if (saddr) { fl6->saddr = saddr->v6.sin6_addr; fl6->fl6_sport = saddr->v6.sin6_port; pr_debug("src=%pI6 - ", &fl6->saddr); } dst = ip6_dst_lookup_flow(sk, fl6, NULL, false); if (!asoc || saddr) goto out; bp = &asoc->base.bind_addr; scope = sctp_scope(daddr); /* ip6_dst_lookup has filled in the fl6->saddr for us. Check * to see if we can use it. */ if (!IS_ERR(dst)) { /* Walk through the bind address list and look for a bind * address that matches the source address of the returned dst. */ sctp_v6_to_addr(&dst_saddr, &fl6->saddr, htons(bp->port)); rcu_read_lock(); list_for_each_entry_rcu(laddr, &bp->address_list, list) { if (!laddr->valid || (laddr->state != SCTP_ADDR_SRC)) continue; /* Do not compare against v4 addrs */ if ((laddr->a.sa.sa_family == AF_INET6) && (sctp_v6_cmp_addr(&dst_saddr, &laddr->a))) { rcu_read_unlock(); goto out; } } rcu_read_unlock(); /* None of the bound addresses match the source address of the * dst. So release it. */ dst_release(dst); dst = NULL; } /* Walk through the bind address list and try to get the * best source address for a given destination. */ rcu_read_lock(); list_for_each_entry_rcu(laddr, &bp->address_list, list) { if (!laddr->valid) continue; if ((laddr->state == SCTP_ADDR_SRC) && (laddr->a.sa.sa_family == AF_INET6) && (scope <= sctp_scope(&laddr->a))) { bmatchlen = sctp_v6_addr_match_len(daddr, &laddr->a); if (!baddr || (matchlen < bmatchlen)) { baddr = &laddr->a; matchlen = bmatchlen; } } } rcu_read_unlock(); if (baddr) { fl6->saddr = baddr->v6.sin6_addr; fl6->fl6_sport = baddr->v6.sin6_port; dst = ip6_dst_lookup_flow(sk, fl6, NULL, false); } out: if (!IS_ERR_OR_NULL(dst)) { struct rt6_info *rt; rt = (struct rt6_info *)dst; t->dst = dst; t->dst_cookie = rt->rt6i_node ? rt->rt6i_node->fn_sernum : 0; pr_debug("rt6_dst:%pI6 rt6_src:%pI6\n", &rt->rt6i_dst.addr, &fl6->saddr); } else { t->dst = NULL; pr_debug("no route\n"); } } /* Returns the number of consecutive initial bits that match in the 2 ipv6 * addresses. */ static inline int sctp_v6_addr_match_len(union sctp_addr *s1, union sctp_addr *s2) { return ipv6_addr_diff(&s1->v6.sin6_addr, &s2->v6.sin6_addr); } /* Fills in the source address(saddr) based on the destination address(daddr) * and asoc's bind address list. */ static void sctp_v6_get_saddr(struct sctp_sock *sk, struct sctp_transport *t, struct flowi *fl) { struct flowi6 *fl6 = &fl->u.ip6; union sctp_addr *saddr = &t->saddr; pr_debug("%s: asoc:%p dst:%p\n", __func__, t->asoc, t->dst); if (t->dst) { saddr->v6.sin6_family = AF_INET6; saddr->v6.sin6_addr = fl6->saddr; } } /* Make a copy of all potential local addresses. */ static void sctp_v6_copy_addrlist(struct list_head *addrlist, struct net_device *dev) { struct inet6_dev *in6_dev; struct inet6_ifaddr *ifp; struct sctp_sockaddr_entry *addr; rcu_read_lock(); if ((in6_dev = __in6_dev_get(dev)) == NULL) { rcu_read_unlock(); return; } read_lock_bh(&in6_dev->lock); list_for_each_entry(ifp, &in6_dev->addr_list, if_list) { /* Add the address to the local list. */ addr = kzalloc(sizeof(*addr), GFP_ATOMIC); if (addr) { addr->a.v6.sin6_family = AF_INET6; addr->a.v6.sin6_port = 0; addr->a.v6.sin6_addr = ifp->addr; addr->a.v6.sin6_scope_id = dev->ifindex; addr->valid = 1; INIT_LIST_HEAD(&addr->list); list_add_tail(&addr->list, addrlist); } } read_unlock_bh(&in6_dev->lock); rcu_read_unlock(); } /* Initialize a sockaddr_storage from in incoming skb. */ static void sctp_v6_from_skb(union sctp_addr *addr,struct sk_buff *skb, int is_saddr) { __be16 *port; struct sctphdr *sh; port = &addr->v6.sin6_port; addr->v6.sin6_family = AF_INET6; addr->v6.sin6_flowinfo = 0; /* FIXME */ addr->v6.sin6_scope_id = ((struct inet6_skb_parm *)skb->cb)->iif; sh = sctp_hdr(skb); if (is_saddr) { *port = sh->source; addr->v6.sin6_addr = ipv6_hdr(skb)->saddr; } else { *port = sh->dest; addr->v6.sin6_addr = ipv6_hdr(skb)->daddr; } } /* Initialize an sctp_addr from a socket. */ static void sctp_v6_from_sk(union sctp_addr *addr, struct sock *sk) { addr->v6.sin6_family = AF_INET6; addr->v6.sin6_port = 0; addr->v6.sin6_addr = inet6_sk(sk)->rcv_saddr; } /* Initialize sk->sk_rcv_saddr from sctp_addr. */ static void sctp_v6_to_sk_saddr(union sctp_addr *addr, struct sock *sk) { if (addr->sa.sa_family == AF_INET && sctp_sk(sk)->v4mapped) { inet6_sk(sk)->rcv_saddr.s6_addr32[0] = 0; inet6_sk(sk)->rcv_saddr.s6_addr32[1] = 0; inet6_sk(sk)->rcv_saddr.s6_addr32[2] = htonl(0x0000ffff); inet6_sk(sk)->rcv_saddr.s6_addr32[3] = addr->v4.sin_addr.s_addr; } else { inet6_sk(sk)->rcv_saddr = addr->v6.sin6_addr; } } /* Initialize sk->sk_daddr from sctp_addr. */ static void sctp_v6_to_sk_daddr(union sctp_addr *addr, struct sock *sk) { if (addr->sa.sa_family == AF_INET && sctp_sk(sk)->v4mapped) { inet6_sk(sk)->daddr.s6_addr32[0] = 0; inet6_sk(sk)->daddr.s6_addr32[1] = 0; inet6_sk(sk)->daddr.s6_addr32[2] = htonl(0x0000ffff); inet6_sk(sk)->daddr.s6_addr32[3] = addr->v4.sin_addr.s_addr; } else { inet6_sk(sk)->daddr = addr->v6.sin6_addr; } } /* Initialize a sctp_addr from an address parameter. */ static void sctp_v6_from_addr_param(union sctp_addr *addr, union sctp_addr_param *param, __be16 port, int iif) { addr->v6.sin6_family = AF_INET6; addr->v6.sin6_port = port; addr->v6.sin6_flowinfo = 0; /* BUG */ addr->v6.sin6_addr = param->v6.addr; addr->v6.sin6_scope_id = iif; } /* Initialize an address parameter from a sctp_addr and return the length * of the address parameter. */ static int sctp_v6_to_addr_param(const union sctp_addr *addr, union sctp_addr_param *param) { int length = sizeof(sctp_ipv6addr_param_t); param->v6.param_hdr.type = SCTP_PARAM_IPV6_ADDRESS; param->v6.param_hdr.length = htons(length); param->v6.addr = addr->v6.sin6_addr; return length; } /* Initialize a sctp_addr from struct in6_addr. */ static void sctp_v6_to_addr(union sctp_addr *addr, struct in6_addr *saddr, __be16 port) { addr->sa.sa_family = AF_INET6; addr->v6.sin6_port = port; addr->v6.sin6_addr = *saddr; } /* Compare addresses exactly. * v4-mapped-v6 is also in consideration. */ static int sctp_v6_cmp_addr(const union sctp_addr *addr1, const union sctp_addr *addr2) { if (addr1->sa.sa_family != addr2->sa.sa_family) { if (addr1->sa.sa_family == AF_INET && addr2->sa.sa_family == AF_INET6 && ipv6_addr_v4mapped(&addr2->v6.sin6_addr)) { if (addr2->v6.sin6_port == addr1->v4.sin_port && addr2->v6.sin6_addr.s6_addr32[3] == addr1->v4.sin_addr.s_addr) return 1; } if (addr2->sa.sa_family == AF_INET && addr1->sa.sa_family == AF_INET6 && ipv6_addr_v4mapped(&addr1->v6.sin6_addr)) { if (addr1->v6.sin6_port == addr2->v4.sin_port && addr1->v6.sin6_addr.s6_addr32[3] == addr2->v4.sin_addr.s_addr) return 1; } return 0; } if (!ipv6_addr_equal(&addr1->v6.sin6_addr, &addr2->v6.sin6_addr)) return 0; /* If this is a linklocal address, compare the scope_id. */ if (ipv6_addr_type(&addr1->v6.sin6_addr) & IPV6_ADDR_LINKLOCAL) { if (addr1->v6.sin6_scope_id && addr2->v6.sin6_scope_id && (addr1->v6.sin6_scope_id != addr2->v6.sin6_scope_id)) { return 0; } } return 1; } /* Initialize addr struct to INADDR_ANY. */ static void sctp_v6_inaddr_any(union sctp_addr *addr, __be16 port) { memset(addr, 0x00, sizeof(union sctp_addr)); addr->v6.sin6_family = AF_INET6; addr->v6.sin6_port = port; } /* Is this a wildcard address? */ static int sctp_v6_is_any(const union sctp_addr *addr) { return ipv6_addr_any(&addr->v6.sin6_addr); } /* Should this be available for binding? */ static int sctp_v6_available(union sctp_addr *addr, struct sctp_sock *sp) { int type; const struct in6_addr *in6 = (const struct in6_addr *)&addr->v6.sin6_addr; type = ipv6_addr_type(in6); if (IPV6_ADDR_ANY == type) return 1; if (type == IPV6_ADDR_MAPPED) { if (sp && !sp->v4mapped) return 0; if (sp && ipv6_only_sock(sctp_opt2sk(sp))) return 0; sctp_v6_map_v4(addr); return sctp_get_af_specific(AF_INET)->available(addr, sp); } if (!(type & IPV6_ADDR_UNICAST)) return 0; return ipv6_chk_addr(sock_net(&sp->inet.sk), in6, NULL, 0); } /* This function checks if the address is a valid address to be used for * SCTP. * * Output: * Return 0 - If the address is a non-unicast or an illegal address. * Return 1 - If the address is a unicast. */ static int sctp_v6_addr_valid(union sctp_addr *addr, struct sctp_sock *sp, const struct sk_buff *skb) { int ret = ipv6_addr_type(&addr->v6.sin6_addr); /* Support v4-mapped-v6 address. */ if (ret == IPV6_ADDR_MAPPED) { /* Note: This routine is used in input, so v4-mapped-v6 * are disallowed here when there is no sctp_sock. */ if (!sp || !sp->v4mapped) return 0; if (sp && ipv6_only_sock(sctp_opt2sk(sp))) return 0; sctp_v6_map_v4(addr); return sctp_get_af_specific(AF_INET)->addr_valid(addr, sp, skb); } /* Is this a non-unicast address */ if (!(ret & IPV6_ADDR_UNICAST)) return 0; return 1; } /* What is the scope of 'addr'? */ static sctp_scope_t sctp_v6_scope(union sctp_addr *addr) { int v6scope; sctp_scope_t retval; /* The IPv6 scope is really a set of bit fields. * See IFA_* in <net/if_inet6.h>. Map to a generic SCTP scope. */ v6scope = ipv6_addr_scope(&addr->v6.sin6_addr); switch (v6scope) { case IFA_HOST: retval = SCTP_SCOPE_LOOPBACK; break; case IFA_LINK: retval = SCTP_SCOPE_LINK; break; case IFA_SITE: retval = SCTP_SCOPE_PRIVATE; break; default: retval = SCTP_SCOPE_GLOBAL; break; } return retval; } /* Create and initialize a new sk for the socket to be returned by accept(). */ static struct sock *sctp_v6_create_accept_sk(struct sock *sk, struct sctp_association *asoc) { struct sock *newsk; struct ipv6_pinfo *newnp, *np = inet6_sk(sk); struct sctp6_sock *newsctp6sk; newsk = sk_alloc(sock_net(sk), PF_INET6, GFP_KERNEL, sk->sk_prot); if (!newsk) goto out; sock_init_data(NULL, newsk); sctp_copy_sock(newsk, sk, asoc); sock_reset_flag(sk, SOCK_ZAPPED); newsctp6sk = (struct sctp6_sock *)newsk; inet_sk(newsk)->pinet6 = &newsctp6sk->inet6; sctp_sk(newsk)->v4mapped = sctp_sk(sk)->v4mapped; newnp = inet6_sk(newsk); memcpy(newnp, np, sizeof(struct ipv6_pinfo)); /* Initialize sk's sport, dport, rcv_saddr and daddr for getsockname() * and getpeername(). */ sctp_v6_to_sk_daddr(&asoc->peer.primary_addr, newsk); sk_refcnt_debug_inc(newsk); if (newsk->sk_prot->init(newsk)) { sk_common_release(newsk); newsk = NULL; } out: return newsk; } /* Map v4 address to mapped v6 address */ static void sctp_v6_addr_v4map(struct sctp_sock *sp, union sctp_addr *addr) { if (sp->v4mapped && AF_INET == addr->sa.sa_family) sctp_v4_map_v6(addr); } /* Where did this skb come from? */ static int sctp_v6_skb_iif(const struct sk_buff *skb) { struct inet6_skb_parm *opt = (struct inet6_skb_parm *) skb->cb; return opt->iif; } /* Was this packet marked by Explicit Congestion Notification? */ static int sctp_v6_is_ce(const struct sk_buff *skb) { return *((__u32 *)(ipv6_hdr(skb))) & htonl(1 << 20); } /* Dump the v6 addr to the seq file. */ static void sctp_v6_seq_dump_addr(struct seq_file *seq, union sctp_addr *addr) { seq_printf(seq, "%pI6 ", &addr->v6.sin6_addr); } static void sctp_v6_ecn_capable(struct sock *sk) { inet6_sk(sk)->tclass |= INET_ECN_ECT_0; } /* Initialize a PF_INET6 socket msg_name. */ static void sctp_inet6_msgname(char *msgname, int *addr_len) { struct sockaddr_in6 *sin6; sin6 = (struct sockaddr_in6 *)msgname; sin6->sin6_family = AF_INET6; sin6->sin6_flowinfo = 0; sin6->sin6_scope_id = 0; /*FIXME */ *addr_len = sizeof(struct sockaddr_in6); } /* Initialize a PF_INET msgname from a ulpevent. */ static void sctp_inet6_event_msgname(struct sctp_ulpevent *event, char *msgname, int *addrlen) { struct sockaddr_in6 *sin6, *sin6from; if (msgname) { union sctp_addr *addr; struct sctp_association *asoc; asoc = event->asoc; sctp_inet6_msgname(msgname, addrlen); sin6 = (struct sockaddr_in6 *)msgname; sin6->sin6_port = htons(asoc->peer.port); addr = &asoc->peer.primary_addr; /* Note: If we go to a common v6 format, this code * will change. */ /* Map ipv4 address into v4-mapped-on-v6 address. */ if (sctp_sk(asoc->base.sk)->v4mapped && AF_INET == addr->sa.sa_family) { sctp_v4_map_v6((union sctp_addr *)sin6); sin6->sin6_addr.s6_addr32[3] = addr->v4.sin_addr.s_addr; return; } sin6from = &asoc->peer.primary_addr.v6; sin6->sin6_addr = sin6from->sin6_addr; if (ipv6_addr_type(&sin6->sin6_addr) & IPV6_ADDR_LINKLOCAL) sin6->sin6_scope_id = sin6from->sin6_scope_id; } } /* Initialize a msg_name from an inbound skb. */ static void sctp_inet6_skb_msgname(struct sk_buff *skb, char *msgname, int *addr_len) { struct sctphdr *sh; struct sockaddr_in6 *sin6; if (msgname) { sctp_inet6_msgname(msgname, addr_len); sin6 = (struct sockaddr_in6 *)msgname; sh = sctp_hdr(skb); sin6->sin6_port = sh->source; /* Map ipv4 address into v4-mapped-on-v6 address. */ if (sctp_sk(skb->sk)->v4mapped && ip_hdr(skb)->version == 4) { sctp_v4_map_v6((union sctp_addr *)sin6); sin6->sin6_addr.s6_addr32[3] = ip_hdr(skb)->saddr; return; } /* Otherwise, just copy the v6 address. */ sin6->sin6_addr = ipv6_hdr(skb)->saddr; if (ipv6_addr_type(&sin6->sin6_addr) & IPV6_ADDR_LINKLOCAL) { struct sctp_ulpevent *ev = sctp_skb2event(skb); sin6->sin6_scope_id = ev->iif; } } } /* Do we support this AF? */ static int sctp_inet6_af_supported(sa_family_t family, struct sctp_sock *sp) { switch (family) { case AF_INET6: return 1; /* v4-mapped-v6 addresses */ case AF_INET: if (!__ipv6_only_sock(sctp_opt2sk(sp))) return 1; default: return 0; } } /* Address matching with wildcards allowed. This extra level * of indirection lets us choose whether a PF_INET6 should * disallow any v4 addresses if we so choose. */ static int sctp_inet6_cmp_addr(const union sctp_addr *addr1, const union sctp_addr *addr2, struct sctp_sock *opt) { struct sctp_af *af1, *af2; struct sock *sk = sctp_opt2sk(opt); af1 = sctp_get_af_specific(addr1->sa.sa_family); af2 = sctp_get_af_specific(addr2->sa.sa_family); if (!af1 || !af2) return 0; /* If the socket is IPv6 only, v4 addrs will not match */ if (__ipv6_only_sock(sk) && af1 != af2) return 0; /* Today, wildcard AF_INET/AF_INET6. */ if (sctp_is_any(sk, addr1) || sctp_is_any(sk, addr2)) return 1; if (addr1->sa.sa_family != addr2->sa.sa_family) return 0; return af1->cmp_addr(addr1, addr2); } /* Verify that the provided sockaddr looks bindable. Common verification, * has already been taken care of. */ static int sctp_inet6_bind_verify(struct sctp_sock *opt, union sctp_addr *addr) { struct sctp_af *af; /* ASSERT: address family has already been verified. */ if (addr->sa.sa_family != AF_INET6) af = sctp_get_af_specific(addr->sa.sa_family); else { int type = ipv6_addr_type(&addr->v6.sin6_addr); struct net_device *dev; if (type & IPV6_ADDR_LINKLOCAL) { struct net *net; if (!addr->v6.sin6_scope_id) return 0; net = sock_net(&opt->inet.sk); rcu_read_lock(); dev = dev_get_by_index_rcu(net, addr->v6.sin6_scope_id); if (!dev || !ipv6_chk_addr(net, &addr->v6.sin6_addr, dev, 0)) { rcu_read_unlock(); return 0; } rcu_read_unlock(); } else if (type == IPV6_ADDR_MAPPED) { if (!opt->v4mapped) return 0; } af = opt->pf->af; } return af->available(addr, opt); } /* Verify that the provided sockaddr looks sendable. Common verification, * has already been taken care of. */ static int sctp_inet6_send_verify(struct sctp_sock *opt, union sctp_addr *addr) { struct sctp_af *af = NULL; /* ASSERT: address family has already been verified. */ if (addr->sa.sa_family != AF_INET6) af = sctp_get_af_specific(addr->sa.sa_family); else { int type = ipv6_addr_type(&addr->v6.sin6_addr); struct net_device *dev; if (type & IPV6_ADDR_LINKLOCAL) { if (!addr->v6.sin6_scope_id) return 0; rcu_read_lock(); dev = dev_get_by_index_rcu(sock_net(&opt->inet.sk), addr->v6.sin6_scope_id); rcu_read_unlock(); if (!dev) return 0; } af = opt->pf->af; } return af != NULL; } /* Fill in Supported Address Type information for INIT and INIT-ACK * chunks. Note: In the future, we may want to look at sock options * to determine whether a PF_INET6 socket really wants to have IPV4 * addresses. * Returns number of addresses supported. */ static int sctp_inet6_supported_addrs(const struct sctp_sock *opt, __be16 *types) { types[0] = SCTP_PARAM_IPV6_ADDRESS; if (!opt || !ipv6_only_sock(sctp_opt2sk(opt))) { types[1] = SCTP_PARAM_IPV4_ADDRESS; return 2; } return 1; } static const struct proto_ops inet6_seqpacket_ops = { .family = PF_INET6, .owner = THIS_MODULE, .release = inet6_release, .bind = inet6_bind, .connect = inet_dgram_connect, .socketpair = sock_no_socketpair, .accept = inet_accept, .getname = inet6_getname, .poll = sctp_poll, .ioctl = inet6_ioctl, .listen = sctp_inet_listen, .shutdown = inet_shutdown, .setsockopt = sock_common_setsockopt, .getsockopt = sock_common_getsockopt, .sendmsg = inet_sendmsg, .recvmsg = sock_common_recvmsg, .mmap = sock_no_mmap, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_sock_common_setsockopt, .compat_getsockopt = compat_sock_common_getsockopt, #endif }; static struct inet_protosw sctpv6_seqpacket_protosw = { .type = SOCK_SEQPACKET, .protocol = IPPROTO_SCTP, .prot = &sctpv6_prot, .ops = &inet6_seqpacket_ops, .no_check = 0, .flags = SCTP_PROTOSW_FLAG }; static struct inet_protosw sctpv6_stream_protosw = { .type = SOCK_STREAM, .protocol = IPPROTO_SCTP, .prot = &sctpv6_prot, .ops = &inet6_seqpacket_ops, .no_check = 0, .flags = SCTP_PROTOSW_FLAG, }; static int sctp6_rcv(struct sk_buff *skb) { return sctp_rcv(skb) ? -1 : 0; } static const struct inet6_protocol sctpv6_protocol = { .handler = sctp6_rcv, .err_handler = sctp_v6_err, .flags = INET6_PROTO_NOPOLICY | INET6_PROTO_FINAL, }; static struct sctp_af sctp_af_inet6 = { .sa_family = AF_INET6, .sctp_xmit = sctp_v6_xmit, .setsockopt = ipv6_setsockopt, .getsockopt = ipv6_getsockopt, .get_dst = sctp_v6_get_dst, .get_saddr = sctp_v6_get_saddr, .copy_addrlist = sctp_v6_copy_addrlist, .from_skb = sctp_v6_from_skb, .from_sk = sctp_v6_from_sk, .to_sk_saddr = sctp_v6_to_sk_saddr, .to_sk_daddr = sctp_v6_to_sk_daddr, .from_addr_param = sctp_v6_from_addr_param, .to_addr_param = sctp_v6_to_addr_param, .cmp_addr = sctp_v6_cmp_addr, .scope = sctp_v6_scope, .addr_valid = sctp_v6_addr_valid, .inaddr_any = sctp_v6_inaddr_any, .is_any = sctp_v6_is_any, .available = sctp_v6_available, .skb_iif = sctp_v6_skb_iif, .is_ce = sctp_v6_is_ce, .seq_dump_addr = sctp_v6_seq_dump_addr, .ecn_capable = sctp_v6_ecn_capable, .net_header_len = sizeof(struct ipv6hdr), .sockaddr_len = sizeof(struct sockaddr_in6), #ifdef CONFIG_COMPAT .compat_setsockopt = compat_ipv6_setsockopt, .compat_getsockopt = compat_ipv6_getsockopt, #endif }; static struct sctp_pf sctp_pf_inet6 = { .event_msgname = sctp_inet6_event_msgname, .skb_msgname = sctp_inet6_skb_msgname, .af_supported = sctp_inet6_af_supported, .cmp_addr = sctp_inet6_cmp_addr, .bind_verify = sctp_inet6_bind_verify, .send_verify = sctp_inet6_send_verify, .supported_addrs = sctp_inet6_supported_addrs, .create_accept_sk = sctp_v6_create_accept_sk, .addr_v4map = sctp_v6_addr_v4map, .af = &sctp_af_inet6, }; /* Initialize IPv6 support and register with socket layer. */ void sctp_v6_pf_init(void) { /* Register the SCTP specific PF_INET6 functions. */ sctp_register_pf(&sctp_pf_inet6, PF_INET6); /* Register the SCTP specific AF_INET6 functions. */ sctp_register_af(&sctp_af_inet6); } void sctp_v6_pf_exit(void) { list_del(&sctp_af_inet6.list); } /* Initialize IPv6 support and register with socket layer. */ int sctp_v6_protosw_init(void) { int rc; rc = proto_register(&sctpv6_prot, 1); if (rc) return rc; /* Add SCTPv6(UDP and TCP style) to inetsw6 linked list. */ inet6_register_protosw(&sctpv6_seqpacket_protosw); inet6_register_protosw(&sctpv6_stream_protosw); return 0; } void sctp_v6_protosw_exit(void) { inet6_unregister_protosw(&sctpv6_seqpacket_protosw); inet6_unregister_protosw(&sctpv6_stream_protosw); proto_unregister(&sctpv6_prot); } /* Register with inet6 layer. */ int sctp_v6_add_protocol(void) { /* Register notifier for inet6 address additions/deletions. */ register_inet6addr_notifier(&sctp_inet6addr_notifier); if (inet6_add_protocol(&sctpv6_protocol, IPPROTO_SCTP) < 0) return -EAGAIN; return 0; } /* Unregister with inet6 layer. */ void sctp_v6_del_protocol(void) { inet6_del_protocol(&sctpv6_protocol, IPPROTO_SCTP); unregister_inet6addr_notifier(&sctp_inet6addr_notifier); }
./CrossVul/dataset_final_sorted/CWE-310/c/bad_5741_0
crossvul-cpp_data_good_2309_2
/* dsa_asn1.c */ /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL * project 2000. */ /* ==================================================================== * Copyright (c) 2000-2005 The OpenSSL 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: * * 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. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include <stdio.h> #include "cryptlib.h" #include <openssl/dsa.h> #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/rand.h> /* Override the default new methods */ static int sig_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { if(operation == ASN1_OP_NEW_PRE) { DSA_SIG *sig; sig = OPENSSL_malloc(sizeof(DSA_SIG)); if (!sig) { DSAerr(DSA_F_SIG_CB, ERR_R_MALLOC_FAILURE); return 0; } sig->r = NULL; sig->s = NULL; *pval = (ASN1_VALUE *)sig; return 2; } return 1; } ASN1_SEQUENCE_cb(DSA_SIG, sig_cb) = { ASN1_SIMPLE(DSA_SIG, r, CBIGNUM), ASN1_SIMPLE(DSA_SIG, s, CBIGNUM) } ASN1_SEQUENCE_END_cb(DSA_SIG, DSA_SIG) IMPLEMENT_ASN1_FUNCTIONS_const(DSA_SIG) /* Override the default free and new methods */ static int dsa_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { if(operation == ASN1_OP_NEW_PRE) { *pval = (ASN1_VALUE *)DSA_new(); if(*pval) return 2; return 0; } else if(operation == ASN1_OP_FREE_PRE) { DSA_free((DSA *)*pval); *pval = NULL; return 2; } return 1; } ASN1_SEQUENCE_cb(DSAPrivateKey, dsa_cb) = { ASN1_SIMPLE(DSA, version, LONG), ASN1_SIMPLE(DSA, p, BIGNUM), ASN1_SIMPLE(DSA, q, BIGNUM), ASN1_SIMPLE(DSA, g, BIGNUM), ASN1_SIMPLE(DSA, pub_key, BIGNUM), ASN1_SIMPLE(DSA, priv_key, BIGNUM) } ASN1_SEQUENCE_END_cb(DSA, DSAPrivateKey) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(DSA, DSAPrivateKey, DSAPrivateKey) ASN1_SEQUENCE_cb(DSAparams, dsa_cb) = { ASN1_SIMPLE(DSA, p, BIGNUM), ASN1_SIMPLE(DSA, q, BIGNUM), ASN1_SIMPLE(DSA, g, BIGNUM), } ASN1_SEQUENCE_END_cb(DSA, DSAparams) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(DSA, DSAparams, DSAparams) /* DSA public key is a bit trickier... its effectively a CHOICE type * decided by a field called write_params which can either write out * just the public key as an INTEGER or the parameters and public key * in a SEQUENCE */ ASN1_SEQUENCE(dsa_pub_internal) = { ASN1_SIMPLE(DSA, pub_key, BIGNUM), ASN1_SIMPLE(DSA, p, BIGNUM), ASN1_SIMPLE(DSA, q, BIGNUM), ASN1_SIMPLE(DSA, g, BIGNUM) } ASN1_SEQUENCE_END_name(DSA, dsa_pub_internal) ASN1_CHOICE_cb(DSAPublicKey, dsa_cb) = { ASN1_SIMPLE(DSA, pub_key, BIGNUM), ASN1_EX_COMBINE(0, 0, dsa_pub_internal) } ASN1_CHOICE_END_cb(DSA, DSAPublicKey, write_params) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(DSA, DSAPublicKey, DSAPublicKey) DSA *DSAparams_dup(DSA *dsa) { return ASN1_item_dup(ASN1_ITEM_rptr(DSAparams), dsa); } int DSA_sign(int type, const unsigned char *dgst, int dlen, unsigned char *sig, unsigned int *siglen, DSA *dsa) { DSA_SIG *s; RAND_seed(dgst, dlen); s=DSA_do_sign(dgst,dlen,dsa); if (s == NULL) { *siglen=0; return(0); } *siglen=i2d_DSA_SIG(s,&sig); DSA_SIG_free(s); return(1); } /* data has already been hashed (probably with SHA or SHA-1). */ /*- * returns * 1: correct signature * 0: incorrect signature * -1: error */ int DSA_verify(int type, const unsigned char *dgst, int dgst_len, const unsigned char *sigbuf, int siglen, DSA *dsa) { DSA_SIG *s; const unsigned char *p = sigbuf; unsigned char *der = NULL; int derlen = -1; int ret=-1; s = DSA_SIG_new(); if (s == NULL) return(ret); if (d2i_DSA_SIG(&s,&p,siglen) == NULL) goto err; /* Ensure signature uses DER and doesn't have trailing garbage */ derlen = i2d_DSA_SIG(s, &der); if (derlen != siglen || memcmp(sigbuf, der, derlen)) goto err; ret=DSA_do_verify(dgst,dgst_len,s,dsa); err: if (derlen > 0) { OPENSSL_cleanse(der, derlen); OPENSSL_free(der); } DSA_SIG_free(s); return(ret); }
./CrossVul/dataset_final_sorted/CWE-310/c/good_2309_2
crossvul-cpp_data_bad_1445_3
/* ssl/d1_srvr.c */ /* * DTLS implementation written by Nagendra Modadugu * (nagendra@cs.stanford.edu) for the OpenSSL project 2005. */ /* ==================================================================== * Copyright (c) 1999-2007 The OpenSSL 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: * * 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. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <stdio.h> #include "ssl_locl.h" #include <openssl/buffer.h> #include <openssl/rand.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/md5.h> #include <openssl/bn.h> #ifndef OPENSSL_NO_DH #include <openssl/dh.h> #endif static const SSL_METHOD *dtls1_get_server_method(int ver); static int dtls1_send_hello_verify_request(SSL *s); static const SSL_METHOD *dtls1_get_server_method(int ver) { if (ver == DTLS1_VERSION) return(DTLSv1_server_method()); else if (ver == DTLS1_2_VERSION) return(DTLSv1_2_server_method()); else return(NULL); } IMPLEMENT_dtls1_meth_func(DTLS1_VERSION, DTLSv1_server_method, dtls1_accept, ssl_undefined_function, dtls1_get_server_method, DTLSv1_enc_data) IMPLEMENT_dtls1_meth_func(DTLS1_2_VERSION, DTLSv1_2_server_method, dtls1_accept, ssl_undefined_function, dtls1_get_server_method, DTLSv1_2_enc_data) IMPLEMENT_dtls1_meth_func(DTLS_ANY_VERSION, DTLS_server_method, dtls1_accept, ssl_undefined_function, dtls1_get_server_method, DTLSv1_2_enc_data) int dtls1_accept(SSL *s) { BUF_MEM *buf; unsigned long Time=(unsigned long)time(NULL); void (*cb)(const SSL *ssl,int type,int val)=NULL; unsigned long alg_k; int ret= -1; int new_state,state,skip=0; int listen; #ifndef OPENSSL_NO_SCTP unsigned char sctpauthkey[64]; char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)]; #endif RAND_add(&Time,sizeof(Time),0); ERR_clear_error(); clear_sys_error(); if (s->info_callback != NULL) cb=s->info_callback; else if (s->ctx->info_callback != NULL) cb=s->ctx->info_callback; listen = s->d1->listen; /* init things to blank */ s->in_handshake++; if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); s->d1->listen = listen; #ifndef OPENSSL_NO_SCTP /* Notify SCTP BIO socket to enter handshake * mode and prevent stream identifier other * than 0. Will be ignored if no SCTP is used. */ BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE, s->in_handshake, NULL); #endif if (s->cert == NULL) { SSLerr(SSL_F_DTLS1_ACCEPT,SSL_R_NO_CERTIFICATE_SET); return(-1); } #ifndef OPENSSL_NO_HEARTBEATS /* If we're awaiting a HeartbeatResponse, pretend we * already got and don't await it anymore, because * Heartbeats don't make sense during handshakes anyway. */ if (s->tlsext_hb_pending) { dtls1_stop_timer(s); s->tlsext_hb_pending = 0; s->tlsext_hb_seq++; } #endif for (;;) { state=s->state; switch (s->state) { case SSL_ST_RENEGOTIATE: s->renegotiate=1; /* s->state=SSL_ST_ACCEPT; */ case SSL_ST_BEFORE: case SSL_ST_ACCEPT: case SSL_ST_BEFORE|SSL_ST_ACCEPT: case SSL_ST_OK|SSL_ST_ACCEPT: s->server=1; if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1); if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00)) { SSLerr(SSL_F_DTLS1_ACCEPT, ERR_R_INTERNAL_ERROR); return -1; } s->type=SSL_ST_ACCEPT; if (s->init_buf == NULL) { if ((buf=BUF_MEM_new()) == NULL) { ret= -1; goto end; } if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH)) { BUF_MEM_free(buf); ret= -1; goto end; } s->init_buf=buf; } if (!ssl3_setup_buffers(s)) { ret= -1; goto end; } s->init_num=0; s->d1->change_cipher_spec_ok = 0; /* Should have been reset by ssl3_get_finished, too. */ s->s3->change_cipher_spec = 0; if (s->state != SSL_ST_RENEGOTIATE) { /* Ok, we now need to push on a buffering BIO so that * the output is sent in a way that TCP likes :-) * ...but not with SCTP :-) */ #ifndef OPENSSL_NO_SCTP if (!BIO_dgram_is_sctp(SSL_get_wbio(s))) #endif if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; } ssl3_init_finished_mac(s); s->state=SSL3_ST_SR_CLNT_HELLO_A; s->ctx->stats.sess_accept++; } else { /* s->state == SSL_ST_RENEGOTIATE, * we will just send a HelloRequest */ s->ctx->stats.sess_accept_renegotiate++; s->state=SSL3_ST_SW_HELLO_REQ_A; } break; case SSL3_ST_SW_HELLO_REQ_A: case SSL3_ST_SW_HELLO_REQ_B: s->shutdown=0; dtls1_clear_record_buffer(s); dtls1_start_timer(s); ret=ssl3_send_hello_request(s); if (ret <= 0) goto end; s->s3->tmp.next_state=SSL3_ST_SR_CLNT_HELLO_A; s->state=SSL3_ST_SW_FLUSH; s->init_num=0; ssl3_init_finished_mac(s); break; case SSL3_ST_SW_HELLO_REQ_C: s->state=SSL_ST_OK; break; case SSL3_ST_SR_CLNT_HELLO_A: case SSL3_ST_SR_CLNT_HELLO_B: case SSL3_ST_SR_CLNT_HELLO_C: s->shutdown=0; ret=ssl3_get_client_hello(s); if (ret <= 0) goto end; dtls1_stop_timer(s); if (ret == 1 && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)) s->state = DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A; else s->state = SSL3_ST_SW_SRVR_HELLO_A; s->init_num=0; /* Reflect ClientHello sequence to remain stateless while listening */ if (listen) { memcpy(s->s3->write_sequence, s->s3->read_sequence, sizeof(s->s3->write_sequence)); } /* If we're just listening, stop here */ if (listen && s->state == SSL3_ST_SW_SRVR_HELLO_A) { ret = 2; s->d1->listen = 0; /* Set expected sequence numbers * to continue the handshake. */ s->d1->handshake_read_seq = 2; s->d1->handshake_write_seq = 1; s->d1->next_handshake_write_seq = 1; goto end; } break; case DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A: case DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B: ret = dtls1_send_hello_verify_request(s); if ( ret <= 0) goto end; s->state=SSL3_ST_SW_FLUSH; s->s3->tmp.next_state=SSL3_ST_SR_CLNT_HELLO_A; /* HelloVerifyRequest resets Finished MAC */ if (s->version != DTLS1_BAD_VER) ssl3_init_finished_mac(s); break; #ifndef OPENSSL_NO_SCTP case DTLS1_SCTP_ST_SR_READ_SOCK: if (BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) { s->s3->in_read_app_data=2; s->rwstate=SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); ret = -1; goto end; } s->state=SSL3_ST_SR_FINISHED_A; break; case DTLS1_SCTP_ST_SW_WRITE_SOCK: ret = BIO_dgram_sctp_wait_for_dry(SSL_get_wbio(s)); if (ret < 0) goto end; if (ret == 0) { if (s->d1->next_state != SSL_ST_OK) { s->s3->in_read_app_data=2; s->rwstate=SSL_READING; BIO_clear_retry_flags(SSL_get_rbio(s)); BIO_set_retry_read(SSL_get_rbio(s)); ret = -1; goto end; } } s->state=s->d1->next_state; break; #endif case SSL3_ST_SW_SRVR_HELLO_A: case SSL3_ST_SW_SRVR_HELLO_B: s->renegotiate = 2; dtls1_start_timer(s); ret=ssl3_send_server_hello(s); if (ret <= 0) goto end; if (s->hit) { #ifndef OPENSSL_NO_SCTP /* Add new shared key for SCTP-Auth, * will be ignored if no SCTP used. */ snprintf((char*) labelbuffer, sizeof(DTLS1_SCTP_AUTH_LABEL), DTLS1_SCTP_AUTH_LABEL); SSL_export_keying_material(s, sctpauthkey, sizeof(sctpauthkey), labelbuffer, sizeof(labelbuffer), NULL, 0, 0); BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY, sizeof(sctpauthkey), sctpauthkey); #endif #ifndef OPENSSL_NO_TLSEXT if (s->tlsext_ticket_expected) s->state=SSL3_ST_SW_SESSION_TICKET_A; else s->state=SSL3_ST_SW_CHANGE_A; #else s->state=SSL3_ST_SW_CHANGE_A; #endif } else s->state=SSL3_ST_SW_CERT_A; s->init_num=0; break; case SSL3_ST_SW_CERT_A: case SSL3_ST_SW_CERT_B: /* Check if it is anon DH or normal PSK */ if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { dtls1_start_timer(s); ret=ssl3_send_server_certificate(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_TLSEXT if (s->tlsext_status_expected) s->state=SSL3_ST_SW_CERT_STATUS_A; else s->state=SSL3_ST_SW_KEY_EXCH_A; } else { skip = 1; s->state=SSL3_ST_SW_KEY_EXCH_A; } #else } else skip=1; s->state=SSL3_ST_SW_KEY_EXCH_A; #endif s->init_num=0; break; case SSL3_ST_SW_KEY_EXCH_A: case SSL3_ST_SW_KEY_EXCH_B: alg_k = s->s3->tmp.new_cipher->algorithm_mkey; /* clear this, it may get reset by * send_server_key_exchange */ if ((s->options & SSL_OP_EPHEMERAL_RSA) #ifndef OPENSSL_NO_KRB5 && !(alg_k & SSL_kKRB5) #endif /* OPENSSL_NO_KRB5 */ ) /* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key * even when forbidden by protocol specs * (handshake may fail as clients are not required to * be able to handle this) */ s->s3->tmp.use_rsa_tmp=1; else s->s3->tmp.use_rsa_tmp=0; /* only send if a DH key exchange or * RSA but we have a sign only certificate */ if (s->s3->tmp.use_rsa_tmp /* PSK: send ServerKeyExchange if PSK identity * hint if provided */ #ifndef OPENSSL_NO_PSK || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint) #endif || (alg_k & (SSL_kDHE|SSL_kDHr|SSL_kDHd)) || (alg_k & SSL_kECDHE) || ((alg_k & SSL_kRSA) && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher) ) ) ) ) { dtls1_start_timer(s); ret=ssl3_send_server_key_exchange(s); if (ret <= 0) goto end; } else skip=1; s->state=SSL3_ST_SW_CERT_REQ_A; s->init_num=0; break; case SSL3_ST_SW_CERT_REQ_A: case SSL3_ST_SW_CERT_REQ_B: if (/* don't request cert unless asked for it: */ !(s->verify_mode & SSL_VERIFY_PEER) || /* if SSL_VERIFY_CLIENT_ONCE is set, * don't request cert during re-negotiation: */ ((s->session->peer != NULL) && (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) || /* never request cert in anonymous ciphersuites * (see section "Certificate request" in SSL 3 drafts * and in RFC 2246): */ ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) && /* ... except when the application insists on verification * (against the specs, but s3_clnt.c accepts this for SSL 3) */ !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) || /* never request cert in Kerberos ciphersuites */ (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) /* With normal PSK Certificates and * Certificate Requests are omitted */ || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { /* no cert request */ skip=1; s->s3->tmp.cert_request=0; s->state=SSL3_ST_SW_SRVR_DONE_A; #ifndef OPENSSL_NO_SCTP if (BIO_dgram_is_sctp(SSL_get_wbio(s))) { s->d1->next_state = SSL3_ST_SW_SRVR_DONE_A; s->state = DTLS1_SCTP_ST_SW_WRITE_SOCK; } #endif } else { s->s3->tmp.cert_request=1; dtls1_start_timer(s); ret=ssl3_send_certificate_request(s); if (ret <= 0) goto end; #ifndef NETSCAPE_HANG_BUG s->state=SSL3_ST_SW_SRVR_DONE_A; #ifndef OPENSSL_NO_SCTP if (BIO_dgram_is_sctp(SSL_get_wbio(s))) { s->d1->next_state = SSL3_ST_SW_SRVR_DONE_A; s->state = DTLS1_SCTP_ST_SW_WRITE_SOCK; } #endif #else s->state=SSL3_ST_SW_FLUSH; s->s3->tmp.next_state=SSL3_ST_SR_CERT_A; #ifndef OPENSSL_NO_SCTP if (BIO_dgram_is_sctp(SSL_get_wbio(s))) { s->d1->next_state = s->s3->tmp.next_state; s->s3->tmp.next_state=DTLS1_SCTP_ST_SW_WRITE_SOCK; } #endif #endif s->init_num=0; } break; case SSL3_ST_SW_SRVR_DONE_A: case SSL3_ST_SW_SRVR_DONE_B: dtls1_start_timer(s); ret=ssl3_send_server_done(s); if (ret <= 0) goto end; s->s3->tmp.next_state=SSL3_ST_SR_CERT_A; s->state=SSL3_ST_SW_FLUSH; s->init_num=0; break; case SSL3_ST_SW_FLUSH: s->rwstate=SSL_WRITING; if (BIO_flush(s->wbio) <= 0) { /* If the write error was fatal, stop trying */ if (!BIO_should_retry(s->wbio)) { s->rwstate=SSL_NOTHING; s->state=s->s3->tmp.next_state; } ret= -1; goto end; } s->rwstate=SSL_NOTHING; s->state=s->s3->tmp.next_state; break; case SSL3_ST_SR_CERT_A: case SSL3_ST_SR_CERT_B: if (s->s3->tmp.cert_request) { ret=ssl3_get_client_certificate(s); if (ret <= 0) goto end; } s->init_num=0; s->state=SSL3_ST_SR_KEY_EXCH_A; break; case SSL3_ST_SR_KEY_EXCH_A: case SSL3_ST_SR_KEY_EXCH_B: ret=ssl3_get_client_key_exchange(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_SCTP /* Add new shared key for SCTP-Auth, * will be ignored if no SCTP used. */ snprintf((char *) labelbuffer, sizeof(DTLS1_SCTP_AUTH_LABEL), DTLS1_SCTP_AUTH_LABEL); SSL_export_keying_material(s, sctpauthkey, sizeof(sctpauthkey), labelbuffer, sizeof(labelbuffer), NULL, 0, 0); BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY, sizeof(sctpauthkey), sctpauthkey); #endif s->state=SSL3_ST_SR_CERT_VRFY_A; s->init_num=0; if (ret == 2) { /* For the ECDH ciphersuites when * the client sends its ECDH pub key in * a certificate, the CertificateVerify * message is not sent. */ s->state=SSL3_ST_SR_FINISHED_A; s->init_num = 0; } else if (SSL_USE_SIGALGS(s)) { s->state=SSL3_ST_SR_CERT_VRFY_A; s->init_num=0; if (!s->session->peer) break; /* For sigalgs freeze the handshake buffer * at this point and digest cached records. */ if (!s->s3->handshake_buffer) { SSLerr(SSL_F_DTLS1_ACCEPT,ERR_R_INTERNAL_ERROR); return -1; } s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE; if (!ssl3_digest_cached_records(s)) return -1; } else { s->state=SSL3_ST_SR_CERT_VRFY_A; s->init_num=0; /* We need to get hashes here so if there is * a client cert, it can be verified */ s->method->ssl3_enc->cert_verify_mac(s, NID_md5, &(s->s3->tmp.cert_verify_md[0])); s->method->ssl3_enc->cert_verify_mac(s, NID_sha1, &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH])); } break; case SSL3_ST_SR_CERT_VRFY_A: case SSL3_ST_SR_CERT_VRFY_B: /* * This *should* be the first time we enable CCS, but be * extra careful about surrounding code changes. We need * to set this here because we don't know if we're * expecting a CertificateVerify or not. */ if (!s->s3->change_cipher_spec) s->d1->change_cipher_spec_ok = 1; /* we should decide if we expected this one */ ret=ssl3_get_cert_verify(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_SCTP if (BIO_dgram_is_sctp(SSL_get_wbio(s)) && state == SSL_ST_RENEGOTIATE) s->state=DTLS1_SCTP_ST_SR_READ_SOCK; else #endif s->state=SSL3_ST_SR_FINISHED_A; s->init_num=0; break; case SSL3_ST_SR_FINISHED_A: case SSL3_ST_SR_FINISHED_B: /* * Enable CCS for resumed handshakes. * In a full handshake, we end up here through * SSL3_ST_SR_CERT_VRFY_B, so change_cipher_spec_ok was * already set. Receiving a CCS clears the flag, so make * sure not to re-enable it to ban duplicates. * s->s3->change_cipher_spec is set when a CCS is * processed in d1_pkt.c, and remains set until * the client's Finished message is read. */ if (!s->s3->change_cipher_spec) s->d1->change_cipher_spec_ok = 1; ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A, SSL3_ST_SR_FINISHED_B); if (ret <= 0) goto end; dtls1_stop_timer(s); if (s->hit) s->state=SSL_ST_OK; #ifndef OPENSSL_NO_TLSEXT else if (s->tlsext_ticket_expected) s->state=SSL3_ST_SW_SESSION_TICKET_A; #endif else s->state=SSL3_ST_SW_CHANGE_A; s->init_num=0; break; #ifndef OPENSSL_NO_TLSEXT case SSL3_ST_SW_SESSION_TICKET_A: case SSL3_ST_SW_SESSION_TICKET_B: ret=ssl3_send_newsession_ticket(s); if (ret <= 0) goto end; s->state=SSL3_ST_SW_CHANGE_A; s->init_num=0; break; case SSL3_ST_SW_CERT_STATUS_A: case SSL3_ST_SW_CERT_STATUS_B: ret=ssl3_send_cert_status(s); if (ret <= 0) goto end; s->state=SSL3_ST_SW_KEY_EXCH_A; s->init_num=0; break; #endif case SSL3_ST_SW_CHANGE_A: case SSL3_ST_SW_CHANGE_B: s->session->cipher=s->s3->tmp.new_cipher; if (!s->method->ssl3_enc->setup_key_block(s)) { ret= -1; goto end; } ret=dtls1_send_change_cipher_spec(s, SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B); if (ret <= 0) goto end; #ifndef OPENSSL_NO_SCTP if (!s->hit) { /* Change to new shared key of SCTP-Auth, * will be ignored if no SCTP used. */ BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY, 0, NULL); } #endif s->state=SSL3_ST_SW_FINISHED_A; s->init_num=0; if (!s->method->ssl3_enc->change_cipher_state(s, SSL3_CHANGE_CIPHER_SERVER_WRITE)) { ret= -1; goto end; } dtls1_reset_seq_numbers(s, SSL3_CC_WRITE); break; case SSL3_ST_SW_FINISHED_A: case SSL3_ST_SW_FINISHED_B: ret=ssl3_send_finished(s, SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B, s->method->ssl3_enc->server_finished_label, s->method->ssl3_enc->server_finished_label_len); if (ret <= 0) goto end; s->state=SSL3_ST_SW_FLUSH; if (s->hit) { s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A; #ifndef OPENSSL_NO_SCTP /* Change to new shared key of SCTP-Auth, * will be ignored if no SCTP used. */ BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY, 0, NULL); #endif } else { s->s3->tmp.next_state=SSL_ST_OK; #ifndef OPENSSL_NO_SCTP if (BIO_dgram_is_sctp(SSL_get_wbio(s))) { s->d1->next_state = s->s3->tmp.next_state; s->s3->tmp.next_state=DTLS1_SCTP_ST_SW_WRITE_SOCK; } #endif } s->init_num=0; break; case SSL_ST_OK: /* clean a few things up */ ssl3_cleanup_key_block(s); #if 0 BUF_MEM_free(s->init_buf); s->init_buf=NULL; #endif /* remove buffering on output */ ssl_free_wbio_buffer(s); s->init_num=0; if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */ { s->renegotiate=0; s->new_session=0; ssl_update_cache(s,SSL_SESS_CACHE_SERVER); s->ctx->stats.sess_accept_good++; /* s->server=1; */ s->handshake_func=dtls1_accept; if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1); } ret = 1; /* done handshaking, next message is client hello */ s->d1->handshake_read_seq = 0; /* next message is server hello */ s->d1->handshake_write_seq = 0; s->d1->next_handshake_write_seq = 0; goto end; /* break; */ default: SSLerr(SSL_F_DTLS1_ACCEPT,SSL_R_UNKNOWN_STATE); ret= -1; goto end; /* break; */ } if (!s->s3->tmp.reuse_message && !skip) { if (s->debug) { if ((ret=BIO_flush(s->wbio)) <= 0) goto end; } if ((cb != NULL) && (s->state != state)) { new_state=s->state; s->state=state; cb(s,SSL_CB_ACCEPT_LOOP,1); s->state=new_state; } } skip=0; } end: /* BIO_flush(s->wbio); */ s->in_handshake--; #ifndef OPENSSL_NO_SCTP /* Notify SCTP BIO socket to leave handshake * mode and prevent stream identifier other * than 0. Will be ignored if no SCTP is used. */ BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE, s->in_handshake, NULL); #endif if (cb != NULL) cb(s,SSL_CB_ACCEPT_EXIT,ret); return(ret); } int dtls1_send_hello_verify_request(SSL *s) { unsigned int msg_len; unsigned char *msg, *buf, *p; if (s->state == DTLS1_ST_SW_HELLO_VERIFY_REQUEST_A) { buf = (unsigned char *)s->init_buf->data; msg = p = &(buf[DTLS1_HM_HEADER_LENGTH]); /* Always use DTLS 1.0 version: see RFC 6347 */ *(p++) = DTLS1_VERSION >> 8; *(p++) = DTLS1_VERSION & 0xFF; if (s->ctx->app_gen_cookie_cb == NULL || s->ctx->app_gen_cookie_cb(s, s->d1->cookie, &(s->d1->cookie_len)) == 0) { SSLerr(SSL_F_DTLS1_SEND_HELLO_VERIFY_REQUEST,ERR_R_INTERNAL_ERROR); return 0; } *(p++) = (unsigned char) s->d1->cookie_len; memcpy(p, s->d1->cookie, s->d1->cookie_len); p += s->d1->cookie_len; msg_len = p - msg; dtls1_set_message_header(s, buf, DTLS1_MT_HELLO_VERIFY_REQUEST, msg_len, 0, msg_len); s->state=DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B; /* number of bytes to write */ s->init_num=p-buf; s->init_off=0; } /* s->state = DTLS1_ST_SW_HELLO_VERIFY_REQUEST_B */ return(dtls1_do_write(s,SSL3_RT_HANDSHAKE)); }
./CrossVul/dataset_final_sorted/CWE-310/c/bad_1445_3
crossvul-cpp_data_good_5666_4
/* * Crypto user configuration API. * * Copyright (C) 2011 secunet Security Networks AG * Copyright (C) 2011 Steffen Klassert <steffen.klassert@secunet.com> * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. */ #include <linux/module.h> #include <linux/crypto.h> #include <linux/cryptouser.h> #include <linux/sched.h> #include <net/netlink.h> #include <linux/security.h> #include <net/net_namespace.h> #include <crypto/internal/aead.h> #include <crypto/internal/skcipher.h> #include "internal.h" static DEFINE_MUTEX(crypto_cfg_mutex); /* The crypto netlink socket */ static struct sock *crypto_nlsk; struct crypto_dump_info { struct sk_buff *in_skb; struct sk_buff *out_skb; u32 nlmsg_seq; u16 nlmsg_flags; }; static struct crypto_alg *crypto_alg_match(struct crypto_user_alg *p, int exact) { struct crypto_alg *q, *alg = NULL; down_read(&crypto_alg_sem); list_for_each_entry(q, &crypto_alg_list, cra_list) { int match = 0; if ((q->cra_flags ^ p->cru_type) & p->cru_mask) continue; if (strlen(p->cru_driver_name)) match = !strcmp(q->cra_driver_name, p->cru_driver_name); else if (!exact) match = !strcmp(q->cra_name, p->cru_name); if (match) { alg = q; break; } } up_read(&crypto_alg_sem); return alg; } static int crypto_report_cipher(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_cipher rcipher; strncpy(rcipher.type, "cipher", sizeof(rcipher.type)); rcipher.blocksize = alg->cra_blocksize; rcipher.min_keysize = alg->cra_cipher.cia_min_keysize; rcipher.max_keysize = alg->cra_cipher.cia_max_keysize; if (nla_put(skb, CRYPTOCFGA_REPORT_CIPHER, sizeof(struct crypto_report_cipher), &rcipher)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } static int crypto_report_comp(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_comp rcomp; strncpy(rcomp.type, "compression", sizeof(rcomp.type)); if (nla_put(skb, CRYPTOCFGA_REPORT_COMPRESS, sizeof(struct crypto_report_comp), &rcomp)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } static int crypto_report_one(struct crypto_alg *alg, struct crypto_user_alg *ualg, struct sk_buff *skb) { strncpy(ualg->cru_name, alg->cra_name, sizeof(ualg->cru_name)); strncpy(ualg->cru_driver_name, alg->cra_driver_name, sizeof(ualg->cru_driver_name)); strncpy(ualg->cru_module_name, module_name(alg->cra_module), sizeof(ualg->cru_module_name)); ualg->cru_type = 0; ualg->cru_mask = 0; ualg->cru_flags = alg->cra_flags; ualg->cru_refcnt = atomic_read(&alg->cra_refcnt); if (nla_put_u32(skb, CRYPTOCFGA_PRIORITY_VAL, alg->cra_priority)) goto nla_put_failure; if (alg->cra_flags & CRYPTO_ALG_LARVAL) { struct crypto_report_larval rl; strncpy(rl.type, "larval", sizeof(rl.type)); if (nla_put(skb, CRYPTOCFGA_REPORT_LARVAL, sizeof(struct crypto_report_larval), &rl)) goto nla_put_failure; goto out; } if (alg->cra_type && alg->cra_type->report) { if (alg->cra_type->report(skb, alg)) goto nla_put_failure; goto out; } switch (alg->cra_flags & (CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_LARVAL)) { case CRYPTO_ALG_TYPE_CIPHER: if (crypto_report_cipher(skb, alg)) goto nla_put_failure; break; case CRYPTO_ALG_TYPE_COMPRESS: if (crypto_report_comp(skb, alg)) goto nla_put_failure; break; } out: return 0; nla_put_failure: return -EMSGSIZE; } static int crypto_report_alg(struct crypto_alg *alg, struct crypto_dump_info *info) { struct sk_buff *in_skb = info->in_skb; struct sk_buff *skb = info->out_skb; struct nlmsghdr *nlh; struct crypto_user_alg *ualg; int err = 0; nlh = nlmsg_put(skb, NETLINK_CB(in_skb).portid, info->nlmsg_seq, CRYPTO_MSG_GETALG, sizeof(*ualg), info->nlmsg_flags); if (!nlh) { err = -EMSGSIZE; goto out; } ualg = nlmsg_data(nlh); err = crypto_report_one(alg, ualg, skb); if (err) { nlmsg_cancel(skb, nlh); goto out; } nlmsg_end(skb, nlh); out: return err; } static int crypto_report(struct sk_buff *in_skb, struct nlmsghdr *in_nlh, struct nlattr **attrs) { struct crypto_user_alg *p = nlmsg_data(in_nlh); struct crypto_alg *alg; struct sk_buff *skb; struct crypto_dump_info info; int err; if (!p->cru_driver_name) return -EINVAL; alg = crypto_alg_match(p, 1); if (!alg) return -ENOENT; skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC); if (!skb) return -ENOMEM; info.in_skb = in_skb; info.out_skb = skb; info.nlmsg_seq = in_nlh->nlmsg_seq; info.nlmsg_flags = 0; err = crypto_report_alg(alg, &info); if (err) return err; return nlmsg_unicast(crypto_nlsk, skb, NETLINK_CB(in_skb).portid); } static int crypto_dump_report(struct sk_buff *skb, struct netlink_callback *cb) { struct crypto_alg *alg; struct crypto_dump_info info; int err; if (cb->args[0]) goto out; cb->args[0] = 1; info.in_skb = cb->skb; info.out_skb = skb; info.nlmsg_seq = cb->nlh->nlmsg_seq; info.nlmsg_flags = NLM_F_MULTI; list_for_each_entry(alg, &crypto_alg_list, cra_list) { err = crypto_report_alg(alg, &info); if (err) goto out_err; } out: return skb->len; out_err: return err; } static int crypto_dump_report_done(struct netlink_callback *cb) { return 0; } static int crypto_update_alg(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct crypto_alg *alg; struct crypto_user_alg *p = nlmsg_data(nlh); struct nlattr *priority = attrs[CRYPTOCFGA_PRIORITY_VAL]; LIST_HEAD(list); if (priority && !strlen(p->cru_driver_name)) return -EINVAL; alg = crypto_alg_match(p, 1); if (!alg) return -ENOENT; down_write(&crypto_alg_sem); crypto_remove_spawns(alg, &list, NULL); if (priority) alg->cra_priority = nla_get_u32(priority); up_write(&crypto_alg_sem); crypto_remove_final(&list); return 0; } static int crypto_del_alg(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct crypto_alg *alg; struct crypto_user_alg *p = nlmsg_data(nlh); alg = crypto_alg_match(p, 1); if (!alg) return -ENOENT; /* We can not unregister core algorithms such as aes-generic. * We would loose the reference in the crypto_alg_list to this algorithm * if we try to unregister. Unregistering such an algorithm without * removing the module is not possible, so we restrict to crypto * instances that are build from templates. */ if (!(alg->cra_flags & CRYPTO_ALG_INSTANCE)) return -EINVAL; if (atomic_read(&alg->cra_refcnt) != 1) return -EBUSY; return crypto_unregister_instance(alg); } static struct crypto_alg *crypto_user_skcipher_alg(const char *name, u32 type, u32 mask) { int err; struct crypto_alg *alg; type = crypto_skcipher_type(type); mask = crypto_skcipher_mask(mask); for (;;) { alg = crypto_lookup_skcipher(name, type, mask); if (!IS_ERR(alg)) return alg; err = PTR_ERR(alg); if (err != -EAGAIN) break; if (signal_pending(current)) { err = -EINTR; break; } } return ERR_PTR(err); } static struct crypto_alg *crypto_user_aead_alg(const char *name, u32 type, u32 mask) { int err; struct crypto_alg *alg; type &= ~(CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV); type |= CRYPTO_ALG_TYPE_AEAD; mask &= ~(CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV); mask |= CRYPTO_ALG_TYPE_MASK; for (;;) { alg = crypto_lookup_aead(name, type, mask); if (!IS_ERR(alg)) return alg; err = PTR_ERR(alg); if (err != -EAGAIN) break; if (signal_pending(current)) { err = -EINTR; break; } } return ERR_PTR(err); } static int crypto_add_alg(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { int exact = 0; const char *name; struct crypto_alg *alg; struct crypto_user_alg *p = nlmsg_data(nlh); struct nlattr *priority = attrs[CRYPTOCFGA_PRIORITY_VAL]; if (strlen(p->cru_driver_name)) exact = 1; if (priority && !exact) return -EINVAL; alg = crypto_alg_match(p, exact); if (alg) return -EEXIST; if (strlen(p->cru_driver_name)) name = p->cru_driver_name; else name = p->cru_name; switch (p->cru_type & p->cru_mask & CRYPTO_ALG_TYPE_MASK) { case CRYPTO_ALG_TYPE_AEAD: alg = crypto_user_aead_alg(name, p->cru_type, p->cru_mask); break; case CRYPTO_ALG_TYPE_GIVCIPHER: case CRYPTO_ALG_TYPE_BLKCIPHER: case CRYPTO_ALG_TYPE_ABLKCIPHER: alg = crypto_user_skcipher_alg(name, p->cru_type, p->cru_mask); break; default: alg = crypto_alg_mod_lookup(name, p->cru_type, p->cru_mask); } if (IS_ERR(alg)) return PTR_ERR(alg); down_write(&crypto_alg_sem); if (priority) alg->cra_priority = nla_get_u32(priority); up_write(&crypto_alg_sem); crypto_mod_put(alg); return 0; } #define MSGSIZE(type) sizeof(struct type) static const int crypto_msg_min[CRYPTO_NR_MSGTYPES] = { [CRYPTO_MSG_NEWALG - CRYPTO_MSG_BASE] = MSGSIZE(crypto_user_alg), [CRYPTO_MSG_DELALG - CRYPTO_MSG_BASE] = MSGSIZE(crypto_user_alg), [CRYPTO_MSG_UPDATEALG - CRYPTO_MSG_BASE] = MSGSIZE(crypto_user_alg), [CRYPTO_MSG_GETALG - CRYPTO_MSG_BASE] = MSGSIZE(crypto_user_alg), }; static const struct nla_policy crypto_policy[CRYPTOCFGA_MAX+1] = { [CRYPTOCFGA_PRIORITY_VAL] = { .type = NLA_U32}, }; #undef MSGSIZE static struct crypto_link { int (*doit)(struct sk_buff *, struct nlmsghdr *, struct nlattr **); int (*dump)(struct sk_buff *, struct netlink_callback *); int (*done)(struct netlink_callback *); } crypto_dispatch[CRYPTO_NR_MSGTYPES] = { [CRYPTO_MSG_NEWALG - CRYPTO_MSG_BASE] = { .doit = crypto_add_alg}, [CRYPTO_MSG_DELALG - CRYPTO_MSG_BASE] = { .doit = crypto_del_alg}, [CRYPTO_MSG_UPDATEALG - CRYPTO_MSG_BASE] = { .doit = crypto_update_alg}, [CRYPTO_MSG_GETALG - CRYPTO_MSG_BASE] = { .doit = crypto_report, .dump = crypto_dump_report, .done = crypto_dump_report_done}, }; static int crypto_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh) { struct nlattr *attrs[CRYPTOCFGA_MAX+1]; struct crypto_link *link; int type, err; type = nlh->nlmsg_type; if (type > CRYPTO_MSG_MAX) return -EINVAL; type -= CRYPTO_MSG_BASE; link = &crypto_dispatch[type]; if (!capable(CAP_NET_ADMIN)) return -EPERM; if ((type == (CRYPTO_MSG_GETALG - CRYPTO_MSG_BASE) && (nlh->nlmsg_flags & NLM_F_DUMP))) { struct crypto_alg *alg; u16 dump_alloc = 0; if (link->dump == NULL) return -EINVAL; list_for_each_entry(alg, &crypto_alg_list, cra_list) dump_alloc += CRYPTO_REPORT_MAXSIZE; { struct netlink_dump_control c = { .dump = link->dump, .done = link->done, .min_dump_alloc = dump_alloc, }; return netlink_dump_start(crypto_nlsk, skb, nlh, &c); } } err = nlmsg_parse(nlh, crypto_msg_min[type], attrs, CRYPTOCFGA_MAX, crypto_policy); if (err < 0) return err; if (link->doit == NULL) return -EINVAL; return link->doit(skb, nlh, attrs); } static void crypto_netlink_rcv(struct sk_buff *skb) { mutex_lock(&crypto_cfg_mutex); netlink_rcv_skb(skb, &crypto_user_rcv_msg); mutex_unlock(&crypto_cfg_mutex); } static int __init crypto_user_init(void) { struct netlink_kernel_cfg cfg = { .input = crypto_netlink_rcv, }; crypto_nlsk = netlink_kernel_create(&init_net, NETLINK_CRYPTO, &cfg); if (!crypto_nlsk) return -ENOMEM; return 0; } static void __exit crypto_user_exit(void) { netlink_kernel_release(crypto_nlsk); } module_init(crypto_user_init); module_exit(crypto_user_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Steffen Klassert <steffen.klassert@secunet.com>"); MODULE_DESCRIPTION("Crypto userspace configuration API");
./CrossVul/dataset_final_sorted/CWE-310/c/good_5666_4
crossvul-cpp_data_bad_5666_5
/* * Cryptographic API. * * Partial (de)compression operations. * * Copyright 2008 Sony Corporation * * 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. * * 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/crypto.h> #include <linux/errno.h> #include <linux/module.h> #include <linux/seq_file.h> #include <linux/string.h> #include <linux/cryptouser.h> #include <net/netlink.h> #include <crypto/compress.h> #include <crypto/internal/compress.h> #include "internal.h" static int crypto_pcomp_init(struct crypto_tfm *tfm, u32 type, u32 mask) { return 0; } static unsigned int crypto_pcomp_extsize(struct crypto_alg *alg) { return alg->cra_ctxsize; } static int crypto_pcomp_init_tfm(struct crypto_tfm *tfm) { return 0; } #ifdef CONFIG_NET static int crypto_pcomp_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_comp rpcomp; snprintf(rpcomp.type, CRYPTO_MAX_ALG_NAME, "%s", "pcomp"); if (nla_put(skb, CRYPTOCFGA_REPORT_COMPRESS, sizeof(struct crypto_report_comp), &rpcomp)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } #else static int crypto_pcomp_report(struct sk_buff *skb, struct crypto_alg *alg) { return -ENOSYS; } #endif static void crypto_pcomp_show(struct seq_file *m, struct crypto_alg *alg) __attribute__ ((unused)); static void crypto_pcomp_show(struct seq_file *m, struct crypto_alg *alg) { seq_printf(m, "type : pcomp\n"); } static const struct crypto_type crypto_pcomp_type = { .extsize = crypto_pcomp_extsize, .init = crypto_pcomp_init, .init_tfm = crypto_pcomp_init_tfm, #ifdef CONFIG_PROC_FS .show = crypto_pcomp_show, #endif .report = crypto_pcomp_report, .maskclear = ~CRYPTO_ALG_TYPE_MASK, .maskset = CRYPTO_ALG_TYPE_MASK, .type = CRYPTO_ALG_TYPE_PCOMPRESS, .tfmsize = offsetof(struct crypto_pcomp, base), }; struct crypto_pcomp *crypto_alloc_pcomp(const char *alg_name, u32 type, u32 mask) { return crypto_alloc_tfm(alg_name, &crypto_pcomp_type, type, mask); } EXPORT_SYMBOL_GPL(crypto_alloc_pcomp); int crypto_register_pcomp(struct pcomp_alg *alg) { struct crypto_alg *base = &alg->base; base->cra_type = &crypto_pcomp_type; base->cra_flags &= ~CRYPTO_ALG_TYPE_MASK; base->cra_flags |= CRYPTO_ALG_TYPE_PCOMPRESS; return crypto_register_alg(base); } EXPORT_SYMBOL_GPL(crypto_register_pcomp); int crypto_unregister_pcomp(struct pcomp_alg *alg) { return crypto_unregister_alg(&alg->base); } EXPORT_SYMBOL_GPL(crypto_unregister_pcomp); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Partial (de)compression type"); MODULE_AUTHOR("Sony Corporation");
./CrossVul/dataset_final_sorted/CWE-310/c/bad_5666_5
crossvul-cpp_data_good_1445_4
/* ssl/s3_clnt.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ /* ==================================================================== * Copyright (c) 1998-2007 The OpenSSL 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: * * 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. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* ==================================================================== * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * * Portions of the attached software ("Contribution") are developed by * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project. * * The Contribution is licensed pursuant to the OpenSSL open source * license provided above. * * ECC cipher suite support in OpenSSL originally written by * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories. * */ /* ==================================================================== * Copyright 2005 Nokia. All rights reserved. * * The portions of the attached software ("Contribution") is developed by * Nokia Corporation and is licensed pursuant to the OpenSSL open source * license. * * The Contribution, originally written by Mika Kousa and Pasi Eronen of * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites * support (see RFC 4279) to OpenSSL. * * No patent licenses or other rights except those expressly stated in * the OpenSSL open source license shall be deemed granted or received * expressly, by implication, estoppel, or otherwise. * * No assurances are provided by Nokia that the Contribution does not * infringe the patent or other intellectual property rights of any third * party or that the license provides you with all the necessary rights * to make use of the Contribution. * * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR * OTHERWISE. */ #include <stdio.h> #include "ssl_locl.h" #include "kssl_lcl.h" #include <openssl/buffer.h> #include <openssl/rand.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/md5.h> #ifndef OPENSSL_NO_DH #include <openssl/dh.h> #endif #include <openssl/bn.h> #ifndef OPENSSL_NO_ENGINE #include <openssl/engine.h> #endif static int ca_dn_cmp(const X509_NAME * const *a,const X509_NAME * const *b); #ifndef OPENSSL_NO_SSL3_METHOD static const SSL_METHOD *ssl3_get_client_method(int ver) { if (ver == SSL3_VERSION) return(SSLv3_client_method()); else return(NULL); } IMPLEMENT_ssl3_meth_func(SSLv3_client_method, ssl_undefined_function, ssl3_connect, ssl3_get_client_method) #endif int ssl3_connect(SSL *s) { BUF_MEM *buf=NULL; unsigned long Time=(unsigned long)time(NULL); void (*cb)(const SSL *ssl,int type,int val)=NULL; int ret= -1; int new_state,state,skip=0; RAND_add(&Time,sizeof(Time),0); ERR_clear_error(); clear_sys_error(); if (s->info_callback != NULL) cb=s->info_callback; else if (s->ctx->info_callback != NULL) cb=s->ctx->info_callback; s->in_handshake++; if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); #ifndef OPENSSL_NO_HEARTBEATS /* If we're awaiting a HeartbeatResponse, pretend we * already got and don't await it anymore, because * Heartbeats don't make sense during handshakes anyway. */ if (s->tlsext_hb_pending) { s->tlsext_hb_pending = 0; s->tlsext_hb_seq++; } #endif for (;;) { state=s->state; switch(s->state) { case SSL_ST_RENEGOTIATE: s->renegotiate=1; s->state=SSL_ST_CONNECT; s->ctx->stats.sess_connect_renegotiate++; /* break */ case SSL_ST_BEFORE: case SSL_ST_CONNECT: case SSL_ST_BEFORE|SSL_ST_CONNECT: case SSL_ST_OK|SSL_ST_CONNECT: s->server=0; if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1); if ((s->version & 0xff00 ) != 0x0300) { SSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR); ret = -1; goto end; } if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) { SSLerr(SSL_F_SSL3_CONNECT, SSL_R_VERSION_TOO_LOW); return -1; } /* s->version=SSL3_VERSION; */ s->type=SSL_ST_CONNECT; if (s->init_buf == NULL) { if ((buf=BUF_MEM_new()) == NULL) { ret= -1; goto end; } if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH)) { ret= -1; goto end; } s->init_buf=buf; buf=NULL; } if (!ssl3_setup_buffers(s)) { ret= -1; goto end; } /* setup buffing BIO */ if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; } /* don't push the buffering BIO quite yet */ ssl3_init_finished_mac(s); s->state=SSL3_ST_CW_CLNT_HELLO_A; s->ctx->stats.sess_connect++; s->init_num=0; s->s3->flags &= ~SSL3_FLAGS_CCS_OK; /* Should have been reset by ssl3_get_finished, too. */ s->s3->change_cipher_spec = 0; break; case SSL3_ST_CW_CLNT_HELLO_A: case SSL3_ST_CW_CLNT_HELLO_B: s->shutdown=0; ret=ssl3_client_hello(s); if (ret <= 0) goto end; s->state=SSL3_ST_CR_SRVR_HELLO_A; s->init_num=0; /* turn on buffering for the next lot of output */ if (s->bbio != s->wbio) s->wbio=BIO_push(s->bbio,s->wbio); break; case SSL3_ST_CR_SRVR_HELLO_A: case SSL3_ST_CR_SRVR_HELLO_B: ret=ssl3_get_server_hello(s); if (ret <= 0) goto end; if (s->hit) { s->state=SSL3_ST_CR_FINISHED_A; #ifndef OPENSSL_NO_TLSEXT if (s->tlsext_ticket_expected) { /* receive renewed session ticket */ s->state=SSL3_ST_CR_SESSION_TICKET_A; } #endif } else { s->state=SSL3_ST_CR_CERT_A; } s->init_num=0; break; case SSL3_ST_CR_CERT_A: case SSL3_ST_CR_CERT_B: /* Check if it is anon DH/ECDH, SRP auth */ /* or PSK */ if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP)) && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { ret=ssl3_get_server_certificate(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_TLSEXT if (s->tlsext_status_expected) s->state=SSL3_ST_CR_CERT_STATUS_A; else s->state=SSL3_ST_CR_KEY_EXCH_A; } else { skip = 1; s->state=SSL3_ST_CR_KEY_EXCH_A; } #else } else skip=1; s->state=SSL3_ST_CR_KEY_EXCH_A; #endif s->init_num=0; break; case SSL3_ST_CR_KEY_EXCH_A: case SSL3_ST_CR_KEY_EXCH_B: ret=ssl3_get_key_exchange(s); if (ret <= 0) goto end; s->state=SSL3_ST_CR_CERT_REQ_A; s->init_num=0; /* at this point we check that we have the * required stuff from the server */ if (!ssl3_check_cert_and_algorithm(s)) { ret= -1; goto end; } break; case SSL3_ST_CR_CERT_REQ_A: case SSL3_ST_CR_CERT_REQ_B: ret=ssl3_get_certificate_request(s); if (ret <= 0) goto end; s->state=SSL3_ST_CR_SRVR_DONE_A; s->init_num=0; break; case SSL3_ST_CR_SRVR_DONE_A: case SSL3_ST_CR_SRVR_DONE_B: ret=ssl3_get_server_done(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_SRP if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) { if ((ret = SRP_Calc_A_param(s))<=0) { SSLerr(SSL_F_SSL3_CONNECT,SSL_R_SRP_A_CALC); ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR); goto end; } } #endif if (s->s3->tmp.cert_req) s->state=SSL3_ST_CW_CERT_A; else s->state=SSL3_ST_CW_KEY_EXCH_A; s->init_num=0; break; case SSL3_ST_CW_CERT_A: case SSL3_ST_CW_CERT_B: case SSL3_ST_CW_CERT_C: case SSL3_ST_CW_CERT_D: ret=ssl3_send_client_certificate(s); if (ret <= 0) goto end; s->state=SSL3_ST_CW_KEY_EXCH_A; s->init_num=0; break; case SSL3_ST_CW_KEY_EXCH_A: case SSL3_ST_CW_KEY_EXCH_B: ret=ssl3_send_client_key_exchange(s); if (ret <= 0) goto end; /* EAY EAY EAY need to check for DH fix cert * sent back */ /* For TLS, cert_req is set to 2, so a cert chain * of nothing is sent, but no verify packet is sent */ /* XXX: For now, we do not support client * authentication in ECDH cipher suites with * ECDH (rather than ECDSA) certificates. * We need to skip the certificate verify * message when client's ECDH public key is sent * inside the client certificate. */ if (s->s3->tmp.cert_req == 1) { s->state=SSL3_ST_CW_CERT_VRFY_A; } else { s->state=SSL3_ST_CW_CHANGE_A; } if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) { s->state=SSL3_ST_CW_CHANGE_A; } s->init_num=0; break; case SSL3_ST_CW_CERT_VRFY_A: case SSL3_ST_CW_CERT_VRFY_B: ret=ssl3_send_client_verify(s); if (ret <= 0) goto end; s->state=SSL3_ST_CW_CHANGE_A; s->init_num=0; break; case SSL3_ST_CW_CHANGE_A: case SSL3_ST_CW_CHANGE_B: ret=ssl3_send_change_cipher_spec(s, SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B); if (ret <= 0) goto end; #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) s->state=SSL3_ST_CW_FINISHED_A; #else if (s->s3->next_proto_neg_seen) s->state=SSL3_ST_CW_NEXT_PROTO_A; else s->state=SSL3_ST_CW_FINISHED_A; #endif s->init_num=0; s->session->cipher=s->s3->tmp.new_cipher; #ifdef OPENSSL_NO_COMP s->session->compress_meth=0; #else if (s->s3->tmp.new_compression == NULL) s->session->compress_meth=0; else s->session->compress_meth= s->s3->tmp.new_compression->id; #endif if (!s->method->ssl3_enc->setup_key_block(s)) { ret= -1; goto end; } if (!s->method->ssl3_enc->change_cipher_state(s, SSL3_CHANGE_CIPHER_CLIENT_WRITE)) { ret= -1; goto end; } break; #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) case SSL3_ST_CW_NEXT_PROTO_A: case SSL3_ST_CW_NEXT_PROTO_B: ret=ssl3_send_next_proto(s); if (ret <= 0) goto end; s->state=SSL3_ST_CW_FINISHED_A; break; #endif case SSL3_ST_CW_FINISHED_A: case SSL3_ST_CW_FINISHED_B: ret=ssl3_send_finished(s, SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B, s->method->ssl3_enc->client_finished_label, s->method->ssl3_enc->client_finished_label_len); if (ret <= 0) goto end; s->state=SSL3_ST_CW_FLUSH; /* clear flags */ s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER; if (s->hit) { s->s3->tmp.next_state=SSL_ST_OK; if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED) { s->state=SSL_ST_OK; s->s3->flags|=SSL3_FLAGS_POP_BUFFER; s->s3->delay_buf_pop_ret=0; } } else { #ifndef OPENSSL_NO_TLSEXT /* Allow NewSessionTicket if ticket expected */ if (s->tlsext_ticket_expected) s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A; else #endif s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A; } s->init_num=0; break; #ifndef OPENSSL_NO_TLSEXT case SSL3_ST_CR_SESSION_TICKET_A: case SSL3_ST_CR_SESSION_TICKET_B: ret=ssl3_get_new_session_ticket(s); if (ret <= 0) goto end; s->state=SSL3_ST_CR_FINISHED_A; s->init_num=0; break; case SSL3_ST_CR_CERT_STATUS_A: case SSL3_ST_CR_CERT_STATUS_B: ret=ssl3_get_cert_status(s); if (ret <= 0) goto end; s->state=SSL3_ST_CR_KEY_EXCH_A; s->init_num=0; break; #endif case SSL3_ST_CR_FINISHED_A: case SSL3_ST_CR_FINISHED_B: s->s3->flags |= SSL3_FLAGS_CCS_OK; ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A, SSL3_ST_CR_FINISHED_B); if (ret <= 0) goto end; if (s->hit) s->state=SSL3_ST_CW_CHANGE_A; else s->state=SSL_ST_OK; s->init_num=0; break; case SSL3_ST_CW_FLUSH: s->rwstate=SSL_WRITING; if (BIO_flush(s->wbio) <= 0) { ret= -1; goto end; } s->rwstate=SSL_NOTHING; s->state=s->s3->tmp.next_state; break; case SSL_ST_OK: /* clean a few things up */ ssl3_cleanup_key_block(s); if (s->init_buf != NULL) { BUF_MEM_free(s->init_buf); s->init_buf=NULL; } /* If we are not 'joining' the last two packets, * remove the buffering now */ if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER)) ssl_free_wbio_buffer(s); /* else do it later in ssl3_write */ s->init_num=0; s->renegotiate=0; s->new_session=0; ssl_update_cache(s,SSL_SESS_CACHE_CLIENT); if (s->hit) s->ctx->stats.sess_hit++; ret=1; /* s->server=0; */ s->handshake_func=ssl3_connect; s->ctx->stats.sess_connect_good++; if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1); goto end; /* break; */ default: SSLerr(SSL_F_SSL3_CONNECT,SSL_R_UNKNOWN_STATE); ret= -1; goto end; /* break; */ } /* did we do anything */ if (!s->s3->tmp.reuse_message && !skip) { if (s->debug) { if ((ret=BIO_flush(s->wbio)) <= 0) goto end; } if ((cb != NULL) && (s->state != state)) { new_state=s->state; s->state=state; cb(s,SSL_CB_CONNECT_LOOP,1); s->state=new_state; } } skip=0; } end: s->in_handshake--; if (buf != NULL) BUF_MEM_free(buf); if (cb != NULL) cb(s,SSL_CB_CONNECT_EXIT,ret); return(ret); } int ssl3_client_hello(SSL *s) { unsigned char *buf; unsigned char *p,*d; int i; unsigned long l; int al = 0; #ifndef OPENSSL_NO_COMP int j; SSL_COMP *comp; #endif buf=(unsigned char *)s->init_buf->data; if (s->state == SSL3_ST_CW_CLNT_HELLO_A) { SSL_SESSION *sess = s->session; if ((sess == NULL) || (sess->ssl_version != s->version) || !sess->session_id_length || (sess->not_resumable)) { if (!ssl_get_new_session(s,0)) goto err; } if (s->method->version == DTLS_ANY_VERSION) { /* Determine which DTLS version to use */ int options = s->options; /* If DTLS 1.2 disabled correct the version number */ if (options & SSL_OP_NO_DTLSv1_2) { if (tls1_suiteb(s)) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE); goto err; } /* Disabling all versions is silly: return an * error. */ if (options & SSL_OP_NO_DTLSv1) { SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_WRONG_SSL_VERSION); goto err; } /* Update method so we don't use any DTLS 1.2 * features. */ s->method = DTLSv1_client_method(); s->version = DTLS1_VERSION; } else { /* We only support one version: update method */ if (options & SSL_OP_NO_DTLSv1) s->method = DTLSv1_2_client_method(); s->version = DTLS1_2_VERSION; } s->client_version = s->version; } /* else use the pre-loaded session */ p=s->s3->client_random; /* for DTLS if client_random is initialized, reuse it, we are * required to use same upon reply to HelloVerify */ if (SSL_IS_DTLS(s)) { size_t idx; i = 1; for (idx=0; idx < sizeof(s->s3->client_random); idx++) { if (p[idx]) { i = 0; break; } } } else i = 1; if (i) ssl_fill_hello_random(s, 0, p, sizeof(s->s3->client_random)); /* Do the message type and length last */ d=p= ssl_handshake_start(s); /*- * version indicates the negotiated version: for example from * an SSLv2/v3 compatible client hello). The client_version * field is the maximum version we permit and it is also * used in RSA encrypted premaster secrets. Some servers can * choke if we initially report a higher version then * renegotiate to a lower one in the premaster secret. This * didn't happen with TLS 1.0 as most servers supported it * but it can with TLS 1.1 or later if the server only supports * 1.0. * * Possible scenario with previous logic: * 1. Client hello indicates TLS 1.2 * 2. Server hello says TLS 1.0 * 3. RSA encrypted premaster secret uses 1.2. * 4. Handhaked proceeds using TLS 1.0. * 5. Server sends hello request to renegotiate. * 6. Client hello indicates TLS v1.0 as we now * know that is maximum server supports. * 7. Server chokes on RSA encrypted premaster secret * containing version 1.0. * * For interoperability it should be OK to always use the * maximum version we support in client hello and then rely * on the checking of version to ensure the servers isn't * being inconsistent: for example initially negotiating with * TLS 1.0 and renegotiating with TLS 1.2. We do this by using * client_version in client hello and not resetting it to * the negotiated version. */ #if 0 *(p++)=s->version>>8; *(p++)=s->version&0xff; s->client_version=s->version; #else *(p++)=s->client_version>>8; *(p++)=s->client_version&0xff; #endif /* Random stuff */ memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE); p+=SSL3_RANDOM_SIZE; /* Session ID */ if (s->new_session) i=0; else i=s->session->session_id_length; *(p++)=i; if (i != 0) { if (i > (int)sizeof(s->session->session_id)) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } memcpy(p,s->session->session_id,i); p+=i; } /* cookie stuff for DTLS */ if (SSL_IS_DTLS(s)) { if ( s->d1->cookie_len > sizeof(s->d1->cookie)) { SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); goto err; } *(p++) = s->d1->cookie_len; memcpy(p, s->d1->cookie, s->d1->cookie_len); p += s->d1->cookie_len; } /* Ciphers supported */ i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0); if (i == 0) { SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE); goto err; } #ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH /* Some servers hang if client hello > 256 bytes * as hack workaround chop number of supported ciphers * to keep it well below this if we use TLS v1.2 */ if (TLS1_get_version(s) >= TLS1_2_VERSION && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH) i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1; #endif s2n(i,p); p+=i; /* COMPRESSION */ #ifdef OPENSSL_NO_COMP *(p++)=1; #else if (!ssl_allow_compression(s) || !s->ctx->comp_methods) j=0; else j=sk_SSL_COMP_num(s->ctx->comp_methods); *(p++)=1+j; for (i=0; i<j; i++) { comp=sk_SSL_COMP_value(s->ctx->comp_methods,i); *(p++)=comp->id; } #endif *(p++)=0; /* Add the NULL method */ #ifndef OPENSSL_NO_TLSEXT /* TLS extensions*/ if (ssl_prepare_clienthello_tlsext(s) <= 0) { SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT); goto err; } if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH, &al)) == NULL) { ssl3_send_alert(s,SSL3_AL_FATAL,al); SSLerr(SSL_F_SSL3_CLIENT_HELLO,ERR_R_INTERNAL_ERROR); goto err; } #endif l= p-d; ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l); s->state=SSL3_ST_CW_CLNT_HELLO_B; } /* SSL3_ST_CW_CLNT_HELLO_B */ return ssl_do_write(s); err: return(-1); } int ssl3_get_server_hello(SSL *s) { STACK_OF(SSL_CIPHER) *sk; const SSL_CIPHER *c; CERT *ct = s->cert; unsigned char *p,*d; int i,al=SSL_AD_INTERNAL_ERROR,ok; unsigned int j; long n; #ifndef OPENSSL_NO_COMP SSL_COMP *comp; #endif /* Hello verify request and/or server hello version may not * match so set first packet if we're negotiating version. */ if (SSL_IS_DTLS(s)) s->first_packet = 1; n=s->method->ssl_get_message(s, SSL3_ST_CR_SRVR_HELLO_A, SSL3_ST_CR_SRVR_HELLO_B, -1, 20000, /* ?? */ &ok); if (!ok) return((int)n); if (SSL_IS_DTLS(s)) { s->first_packet = 0; if ( s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST) { if ( s->d1->send_cookie == 0) { s->s3->tmp.reuse_message = 1; return 1; } else /* already sent a cookie */ { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } } } if ( s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } d=p=(unsigned char *)s->init_msg; if (s->method->version == DTLS_ANY_VERSION) { /* Work out correct protocol version to use */ int hversion = (p[0] << 8)|p[1]; int options = s->options; if (hversion == DTLS1_2_VERSION && !(options & SSL_OP_NO_DTLSv1_2)) s->method = DTLSv1_2_client_method(); else if (tls1_suiteb(s)) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE); s->version = hversion; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } else if (hversion == DTLS1_VERSION && !(options & SSL_OP_NO_DTLSv1)) s->method = DTLSv1_client_method(); else { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION); s->version = hversion; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } s->version = s->method->version; } if ((p[0] != (s->version>>8)) || (p[1] != (s->version&0xff))) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION); s->version=(s->version&0xff00)|p[1]; al=SSL_AD_PROTOCOL_VERSION; goto f_err; } p+=2; /* load the server hello data */ /* load the server random */ memcpy(s->s3->server_random,p,SSL3_RANDOM_SIZE); p+=SSL3_RANDOM_SIZE; s->hit = 0; /* get the session-id */ j= *(p++); if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SSL3_SESSION_ID_TOO_LONG); goto f_err; } #ifndef OPENSSL_NO_TLSEXT /* check if we want to resume the session based on external pre-shared secret */ if (s->version >= TLS1_VERSION && s->tls_session_secret_cb) { SSL_CIPHER *pref_cipher=NULL; s->session->master_key_length=sizeof(s->session->master_key); if (s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length, NULL, &pref_cipher, s->tls_session_secret_cb_arg)) { s->session->cipher = pref_cipher ? pref_cipher : ssl_get_cipher_by_char(s, p+j); s->hit = 1; } } #endif /* OPENSSL_NO_TLSEXT */ if (!s->hit && j != 0 && j == s->session->session_id_length && memcmp(p,s->session->session_id,j) == 0) { if(s->sid_ctx_length != s->session->sid_ctx_length || memcmp(s->session->sid_ctx,s->sid_ctx,s->sid_ctx_length)) { /* actually a client application bug */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT); goto f_err; } s->hit=1; } /* a miss or crap from the other end */ if (!s->hit) { /* If we were trying for session-id reuse, make a new * SSL_SESSION so we don't stuff up other people */ if (s->session->session_id_length > 0) { if (!ssl_get_new_session(s,0)) { goto f_err; } } s->session->session_id_length=j; memcpy(s->session->session_id,p,j); /* j could be 0 */ } p+=j; c=ssl_get_cipher_by_char(s,p); if (c == NULL) { /* unknown cipher */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNKNOWN_CIPHER_RETURNED); goto f_err; } /* Set version disabled mask now we know version */ if (!SSL_USE_TLS1_2_CIPHERS(s)) ct->mask_ssl = SSL_TLSV1_2; else ct->mask_ssl = 0; /* If it is a disabled cipher we didn't send it in client hello, * so return an error. */ if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_CHECK)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED); goto f_err; } p+=ssl_put_cipher_by_char(s,NULL,NULL); sk=ssl_get_ciphers_by_id(s); i=sk_SSL_CIPHER_find(sk,c); if (i < 0) { /* we did not say we would use this cipher */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED); goto f_err; } /* Depending on the session caching (internal/external), the cipher and/or cipher_id values may not be set. Make sure that cipher_id is set and use it for comparison. */ if (s->session->cipher) s->session->cipher_id = s->session->cipher->id; if (s->hit && (s->session->cipher_id != c->id)) { /* Workaround is now obsolete */ #if 0 if (!(s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)) #endif { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED); goto f_err; } } s->s3->tmp.new_cipher=c; /* Don't digest cached records if no sigalgs: we may need them for * client authentication. */ if (!SSL_USE_SIGALGS(s) && !ssl3_digest_cached_records(s)) goto f_err; /* lets get the compression algorithm */ /* COMPRESSION */ #ifdef OPENSSL_NO_COMP if (*(p++) != 0) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM); goto f_err; } /* If compression is disabled we'd better not try to resume a session * using compression. */ if (s->session->compress_meth != 0) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } #else j= *(p++); if (s->hit && j != s->session->compress_meth) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED); goto f_err; } if (j == 0) comp=NULL; else if (!ssl_allow_compression(s)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_COMPRESSION_DISABLED); goto f_err; } else comp=ssl3_comp_find(s->ctx->comp_methods,j); if ((j != 0) && (comp == NULL)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM); goto f_err; } else { s->s3->tmp.new_compression=comp; } #endif #ifndef OPENSSL_NO_TLSEXT /* TLS extensions*/ if (!ssl_parse_serverhello_tlsext(s,&p,d,n)) { SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_PARSE_TLSEXT); goto err; } #endif if (p != (d+n)) { /* wrong packet length */ al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_PACKET_LENGTH); goto f_err; } return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(-1); } int ssl3_get_server_certificate(SSL *s) { int al,i,ok,ret= -1; unsigned long n,nc,llen,l; X509 *x=NULL; const unsigned char *q,*p; unsigned char *d; STACK_OF(X509) *sk=NULL; SESS_CERT *sc; EVP_PKEY *pkey=NULL; int need_cert = 1; /* VRS: 0=> will allow null cert if auth == KRB5 */ n=s->method->ssl_get_message(s, SSL3_ST_CR_CERT_A, SSL3_ST_CR_CERT_B, -1, s->max_cert_list, &ok); if (!ok) return((int)n); if ((s->s3->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) || ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) && (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE))) { s->s3->tmp.reuse_message=1; return(1); } if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_BAD_MESSAGE_TYPE); goto f_err; } p=d=(unsigned char *)s->init_msg; if ((sk=sk_X509_new_null()) == NULL) { SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE); goto err; } n2l3(p,llen); if (llen+3 != n) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_LENGTH_MISMATCH); goto f_err; } for (nc=0; nc<llen; ) { n2l3(p,l); if ((l+nc+3) > llen) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH); goto f_err; } q=p; x=d2i_X509(NULL,&q,l); if (x == NULL) { al=SSL_AD_BAD_CERTIFICATE; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_ASN1_LIB); goto f_err; } if (q != (p+l)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH); goto f_err; } if (!sk_X509_push(sk,x)) { SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE); goto err; } x=NULL; nc+=l+3; p=q; } i=ssl_verify_cert_chain(s,sk); if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0) #ifndef OPENSSL_NO_KRB5 && !((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) && (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5)) #endif /* OPENSSL_NO_KRB5 */ ) { al=ssl_verify_alarm_type(s->verify_result); SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED); goto f_err; } ERR_clear_error(); /* but we keep s->verify_result */ if (i > 1) { SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, i); al = SSL_AD_HANDSHAKE_FAILURE; goto f_err; } sc=ssl_sess_cert_new(); if (sc == NULL) goto err; if (s->session->sess_cert) ssl_sess_cert_free(s->session->sess_cert); s->session->sess_cert=sc; sc->cert_chain=sk; /* Inconsistency alert: cert_chain does include the peer's * certificate, which we don't include in s3_srvr.c */ x=sk_X509_value(sk,0); sk=NULL; /* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/ pkey=X509_get_pubkey(x); /* VRS: allow null cert if auth == KRB5 */ need_cert = ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) && (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5)) ? 0 : 1; #ifdef KSSL_DEBUG fprintf(stderr,"pkey,x = %p, %p\n", pkey,x); fprintf(stderr,"ssl_cert_type(x,pkey) = %d\n", ssl_cert_type(x,pkey)); fprintf(stderr,"cipher, alg, nc = %s, %lx, %lx, %d\n", s->s3->tmp.new_cipher->name, s->s3->tmp.new_cipher->algorithm_mkey, s->s3->tmp.new_cipher->algorithm_auth, need_cert); #endif /* KSSL_DEBUG */ if (need_cert && ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey))) { x=NULL; al=SSL3_AL_FATAL; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS); goto f_err; } i=ssl_cert_type(x,pkey); if (need_cert && i < 0) { x=NULL; al=SSL3_AL_FATAL; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_UNKNOWN_CERTIFICATE_TYPE); goto f_err; } if (need_cert) { int exp_idx = ssl_cipher_get_cert_index(s->s3->tmp.new_cipher); if (exp_idx >= 0 && i != exp_idx) { x=NULL; al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, SSL_R_WRONG_CERTIFICATE_TYPE); goto f_err; } sc->peer_cert_type=i; CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509); /* Why would the following ever happen? * We just created sc a couple of lines ago. */ if (sc->peer_pkeys[i].x509 != NULL) X509_free(sc->peer_pkeys[i].x509); sc->peer_pkeys[i].x509=x; sc->peer_key= &(sc->peer_pkeys[i]); if (s->session->peer != NULL) X509_free(s->session->peer); CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509); s->session->peer=x; } else { sc->peer_cert_type=i; sc->peer_key= NULL; if (s->session->peer != NULL) X509_free(s->session->peer); s->session->peer=NULL; } s->session->verify_result = s->verify_result; x=NULL; ret=1; if (0) { f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); } err: EVP_PKEY_free(pkey); X509_free(x); sk_X509_pop_free(sk,X509_free); return(ret); } int ssl3_get_key_exchange(SSL *s) { #ifndef OPENSSL_NO_RSA unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2]; #endif EVP_MD_CTX md_ctx; unsigned char *param,*p; int al,j,ok; long i,param_len,n,alg_k,alg_a; EVP_PKEY *pkey=NULL; const EVP_MD *md = NULL; #ifndef OPENSSL_NO_RSA RSA *rsa=NULL; #endif #ifndef OPENSSL_NO_DH DH *dh=NULL; #endif #ifndef OPENSSL_NO_ECDH EC_KEY *ecdh = NULL; BN_CTX *bn_ctx = NULL; EC_POINT *srvr_ecpoint = NULL; int curve_nid = 0; int encoded_pt_len = 0; #endif EVP_MD_CTX_init(&md_ctx); /* use same message size as in ssl3_get_certificate_request() * as ServerKeyExchange message may be skipped */ n=s->method->ssl_get_message(s, SSL3_ST_CR_KEY_EXCH_A, SSL3_ST_CR_KEY_EXCH_B, -1, s->max_cert_list, &ok); if (!ok) return((int)n); alg_k=s->s3->tmp.new_cipher->algorithm_mkey; if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) { /* * Can't skip server key exchange if this is an ephemeral * ciphersuite. */ if (alg_k & (SSL_kDHE|SSL_kECDHE)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_UNEXPECTED_MESSAGE); al = SSL_AD_UNEXPECTED_MESSAGE; goto f_err; } #ifndef OPENSSL_NO_PSK /* In plain PSK ciphersuite, ServerKeyExchange can be omitted if no identity hint is sent. Set session->sess_cert anyway to avoid problems later.*/ if (alg_k & SSL_kPSK) { s->session->sess_cert=ssl_sess_cert_new(); if (s->ctx->psk_identity_hint) OPENSSL_free(s->ctx->psk_identity_hint); s->ctx->psk_identity_hint = NULL; } #endif s->s3->tmp.reuse_message=1; return(1); } param=p=(unsigned char *)s->init_msg; if (s->session->sess_cert != NULL) { #ifndef OPENSSL_NO_RSA if (s->session->sess_cert->peer_rsa_tmp != NULL) { RSA_free(s->session->sess_cert->peer_rsa_tmp); s->session->sess_cert->peer_rsa_tmp=NULL; } #endif #ifndef OPENSSL_NO_DH if (s->session->sess_cert->peer_dh_tmp) { DH_free(s->session->sess_cert->peer_dh_tmp); s->session->sess_cert->peer_dh_tmp=NULL; } #endif #ifndef OPENSSL_NO_ECDH if (s->session->sess_cert->peer_ecdh_tmp) { EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp); s->session->sess_cert->peer_ecdh_tmp=NULL; } #endif } else { s->session->sess_cert=ssl_sess_cert_new(); } /* Total length of the parameters including the length prefix */ param_len=0; alg_a=s->s3->tmp.new_cipher->algorithm_auth; al=SSL_AD_DECODE_ERROR; #ifndef OPENSSL_NO_PSK if (alg_k & SSL_kPSK) { char tmp_id_hint[PSK_MAX_IDENTITY_LEN+1]; param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); /* Store PSK identity hint for later use, hint is used * in ssl3_send_client_key_exchange. Assume that the * maximum length of a PSK identity hint can be as * long as the maximum length of a PSK identity. */ if (i > PSK_MAX_IDENTITY_LEN) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto f_err; } if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH); goto f_err; } param_len += i; /* If received PSK identity hint contains NULL * characters, the hint is truncated from the first * NULL. p may not be ending with NULL, so create a * NULL-terminated string. */ memcpy(tmp_id_hint, p, i); memset(tmp_id_hint+i, 0, PSK_MAX_IDENTITY_LEN+1-i); if (s->ctx->psk_identity_hint != NULL) OPENSSL_free(s->ctx->psk_identity_hint); s->ctx->psk_identity_hint = BUF_strdup(tmp_id_hint); if (s->ctx->psk_identity_hint == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto f_err; } p+=i; n-=param_len; } else #endif /* !OPENSSL_NO_PSK */ #ifndef OPENSSL_NO_SRP if (alg_k & SSL_kSRP) { param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_N_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.N=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_G_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.g=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (1 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 1; i = (unsigned int)(p[0]); p++; if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_S_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.s=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_B_LENGTH); goto f_err; } param_len += i; if (!(s->srp_ctx.B=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; if (!srp_verify_server_param(s, &al)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS); goto f_err; } /* We must check if there is a certificate */ #ifndef OPENSSL_NO_RSA if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #else if (0) ; #endif #ifndef OPENSSL_NO_DSA else if (alg_a & SSL_aDSS) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509); #endif } else #endif /* !OPENSSL_NO_SRP */ #ifndef OPENSSL_NO_RSA if (alg_k & SSL_kRSA) { /* Temporary RSA keys only allowed in export ciphersuites */ if (!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_UNEXPECTED_MESSAGE); goto f_err; } if ((rsa=RSA_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH); goto f_err; } param_len += i; if (!(rsa->n=BN_bin2bn(p,i,rsa->n))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH); goto f_err; } param_len += i; if (!(rsa->e=BN_bin2bn(p,i,rsa->e))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; /* this should be because we are using an export cipher */ if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); else { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } s->session->sess_cert->peer_rsa_tmp=rsa; rsa=NULL; } #else /* OPENSSL_NO_RSA */ if (0) ; #endif #ifndef OPENSSL_NO_DH else if (alg_k & SSL_kDHE) { if ((dh=DH_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB); goto err; } param_len = 2; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH); goto f_err; } param_len += i; if (!(dh->p=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH); goto f_err; } param_len += i; if (!(dh->g=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; if (2 > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } param_len += 2; n2s(p,i); if (i > n - param_len) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH); goto f_err; } param_len += i; if (!(dh->pub_key=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } p+=i; n-=param_len; if (!ssl_security(s, SSL_SECOP_TMP_DH, DH_security_bits(dh), 0, dh)) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_DH_KEY_TOO_SMALL); goto f_err; } #ifndef OPENSSL_NO_RSA if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #else if (0) ; #endif #ifndef OPENSSL_NO_DSA else if (alg_a & SSL_aDSS) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509); #endif /* else anonymous DH, so no certificate or pkey. */ s->session->sess_cert->peer_dh_tmp=dh; dh=NULL; } else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER); goto f_err; } #endif /* !OPENSSL_NO_DH */ #ifndef OPENSSL_NO_ECDH else if (alg_k & SSL_kECDHE) { EC_GROUP *ngroup; const EC_GROUP *group; if ((ecdh=EC_KEY_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } /* Extract elliptic curve parameters and the * server's ephemeral ECDH public key. * Keep accumulating lengths of various components in * param_len and make sure it never exceeds n. */ /* XXX: For now we only support named (not generic) curves * and the ECParameters in this case is just three bytes. We * also need one byte for the length of the encoded point */ param_len=4; if (param_len > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } /* Check curve is one of our preferences, if not server has * sent an invalid curve. ECParameters is 3 bytes. */ if (!tls1_check_curve(s, p, 3)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_CURVE); goto f_err; } if ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0) { al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS); goto f_err; } ngroup = EC_GROUP_new_by_curve_name(curve_nid); if (ngroup == NULL) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } if (EC_KEY_set_group(ecdh, ngroup) == 0) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } EC_GROUP_free(ngroup); group = EC_KEY_get0_group(ecdh); if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && (EC_GROUP_get_degree(group) > 163)) { al=SSL_AD_EXPORT_RESTRICTION; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER); goto f_err; } p+=3; /* Next, get the encoded ECPoint */ if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) || ((bn_ctx = BN_CTX_new()) == NULL)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } encoded_pt_len = *p; /* length of encoded point */ p+=1; if ((encoded_pt_len > n - param_len) || (EC_POINT_oct2point(group, srvr_ecpoint, p, encoded_pt_len, bn_ctx) == 0)) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT); goto f_err; } param_len += encoded_pt_len; n-=param_len; p+=encoded_pt_len; /* The ECC/TLS specification does not mention * the use of DSA to sign ECParameters in the server * key exchange message. We do support RSA and ECDSA. */ if (0) ; #ifndef OPENSSL_NO_RSA else if (alg_a & SSL_aRSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); #endif #ifndef OPENSSL_NO_ECDSA else if (alg_a & SSL_aECDSA) pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509); #endif /* else anonymous ECDH, so no certificate or pkey. */ EC_KEY_set_public_key(ecdh, srvr_ecpoint); s->session->sess_cert->peer_ecdh_tmp=ecdh; ecdh=NULL; BN_CTX_free(bn_ctx); bn_ctx = NULL; EC_POINT_free(srvr_ecpoint); srvr_ecpoint = NULL; } else if (alg_k) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE); goto f_err; } #endif /* !OPENSSL_NO_ECDH */ /* p points to the next byte, there are 'n' bytes left */ /* if it was signed, check the signature */ if (pkey != NULL) { if (SSL_USE_SIGALGS(s)) { int rv; if (2 > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } rv = tls12_check_peer_sigalg(&md, s, p, pkey); if (rv == -1) goto err; else if (rv == 0) { goto f_err; } #ifdef SSL_DEBUG fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md)); #endif p += 2; n -= 2; } else md = EVP_sha1(); if (2 > n) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, SSL_R_LENGTH_TOO_SHORT); goto f_err; } n2s(p,i); n-=2; j=EVP_PKEY_size(pkey); /* Check signature length. If n is 0 then signature is empty */ if ((i != n) || (n > j) || (n <= 0)) { /* wrong packet length */ SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH); goto f_err; } #ifndef OPENSSL_NO_RSA if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) { int num; unsigned int size; j=0; q=md_buf; for (num=2; num > 0; num--) { EVP_MD_CTX_set_flags(&md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); EVP_DigestInit_ex(&md_ctx,(num == 2) ?s->ctx->md5:s->ctx->sha1, NULL); EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,param,param_len); EVP_DigestFinal_ex(&md_ctx,q,&size); q+=size; j+=size; } i=RSA_verify(NID_md5_sha1, md_buf, j, p, n, pkey->pkey.rsa); if (i < 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT); goto f_err; } if (i == 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); goto f_err; } } else #endif { EVP_VerifyInit_ex(&md_ctx, md, NULL); EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_VerifyUpdate(&md_ctx,param,param_len); if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE); goto f_err; } } } else { /* aNULL, aSRP or kPSK do not need public keys */ if (!(alg_a & (SSL_aNULL|SSL_aSRP)) && !(alg_k & SSL_kPSK)) { /* Might be wrong key type, check it */ if (ssl3_check_cert_and_algorithm(s)) /* Otherwise this shouldn't happen */ SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } /* still data left over */ if (n != 0) { SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE); goto f_err; } } EVP_PKEY_free(pkey); EVP_MD_CTX_cleanup(&md_ctx); return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: EVP_PKEY_free(pkey); #ifndef OPENSSL_NO_RSA if (rsa != NULL) RSA_free(rsa); #endif #ifndef OPENSSL_NO_DH if (dh != NULL) DH_free(dh); #endif #ifndef OPENSSL_NO_ECDH BN_CTX_free(bn_ctx); EC_POINT_free(srvr_ecpoint); if (ecdh != NULL) EC_KEY_free(ecdh); #endif EVP_MD_CTX_cleanup(&md_ctx); return(-1); } int ssl3_get_certificate_request(SSL *s) { int ok,ret=0; unsigned long n,nc,l; unsigned int llen, ctype_num,i; X509_NAME *xn=NULL; const unsigned char *p,*q; unsigned char *d; STACK_OF(X509_NAME) *ca_sk=NULL; n=s->method->ssl_get_message(s, SSL3_ST_CR_CERT_REQ_A, SSL3_ST_CR_CERT_REQ_B, -1, s->max_cert_list, &ok); if (!ok) return((int)n); s->s3->tmp.cert_req=0; if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE) { s->s3->tmp.reuse_message=1; /* If we get here we don't need any cached handshake records * as we wont be doing client auth. */ if (s->s3->handshake_buffer) { if (!ssl3_digest_cached_records(s)) goto err; } return(1); } if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_WRONG_MESSAGE_TYPE); goto err; } /* TLS does not like anon-DH with client cert */ if (s->version > SSL3_VERSION) { if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER); goto err; } } p=d=(unsigned char *)s->init_msg; if ((ca_sk=sk_X509_NAME_new(ca_dn_cmp)) == NULL) { SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE); goto err; } /* get the certificate types */ ctype_num= *(p++); if (s->cert->ctypes) { OPENSSL_free(s->cert->ctypes); s->cert->ctypes = NULL; } if (ctype_num > SSL3_CT_NUMBER) { /* If we exceed static buffer copy all to cert structure */ s->cert->ctypes = OPENSSL_malloc(ctype_num); if (s->cert->ctypes == NULL) { SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE); goto err; } memcpy(s->cert->ctypes, p, ctype_num); s->cert->ctype_num = (size_t)ctype_num; ctype_num=SSL3_CT_NUMBER; } for (i=0; i<ctype_num; i++) s->s3->tmp.ctype[i]= p[i]; p+=p[-1]; if (SSL_USE_SIGALGS(s)) { n2s(p, llen); /* Check we have enough room for signature algorithms and * following length value. */ if ((unsigned long)(p - d + llen + 2) > n) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_DATA_LENGTH_TOO_LONG); goto err; } /* Clear certificate digests and validity flags */ for (i = 0; i < SSL_PKEY_NUM; i++) { s->cert->pkeys[i].digest = NULL; s->cert->pkeys[i].valid_flags = 0; } if ((llen & 1) || !tls1_save_sigalgs(s, p, llen)) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_SIGNATURE_ALGORITHMS_ERROR); goto err; } if (!tls1_process_sigalgs(s)) { ssl3_send_alert(s,SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, ERR_R_MALLOC_FAILURE); goto err; } p += llen; } /* get the CA RDNs */ n2s(p,llen); #if 0 { FILE *out; out=fopen("/tmp/vsign.der","w"); fwrite(p,1,llen,out); fclose(out); } #endif if ((unsigned long)(p - d + llen) != n) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_LENGTH_MISMATCH); goto err; } for (nc=0; nc<llen; ) { n2s(p,l); if ((l+nc+2) > llen) { if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG)) goto cont; /* netscape bugs */ ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_TOO_LONG); goto err; } q=p; if ((xn=d2i_X509_NAME(NULL,&q,l)) == NULL) { /* If netscape tolerance is on, ignore errors */ if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG) goto cont; else { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_ASN1_LIB); goto err; } } if (q != (p+l)) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_LENGTH_MISMATCH); goto err; } if (!sk_X509_NAME_push(ca_sk,xn)) { SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE); goto err; } p+=l; nc+=l+2; } if (0) { cont: ERR_clear_error(); } /* we should setup a certificate to return.... */ s->s3->tmp.cert_req=1; s->s3->tmp.ctype_num=ctype_num; if (s->s3->tmp.ca_names != NULL) sk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free); s->s3->tmp.ca_names=ca_sk; ca_sk=NULL; ret=1; err: if (ca_sk != NULL) sk_X509_NAME_pop_free(ca_sk,X509_NAME_free); return(ret); } static int ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b) { return(X509_NAME_cmp(*a,*b)); } #ifndef OPENSSL_NO_TLSEXT int ssl3_get_new_session_ticket(SSL *s) { int ok,al,ret=0, ticklen; long n; const unsigned char *p; unsigned char *d; n=s->method->ssl_get_message(s, SSL3_ST_CR_SESSION_TICKET_A, SSL3_ST_CR_SESSION_TICKET_B, SSL3_MT_NEWSESSION_TICKET, 16384, &ok); if (!ok) return((int)n); if (n < 6) { /* need at least ticket_lifetime_hint + ticket length */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH); goto f_err; } p=d=(unsigned char *)s->init_msg; n2l(p, s->session->tlsext_tick_lifetime_hint); n2s(p, ticklen); /* ticket_lifetime_hint + ticket_length + ticket */ if (ticklen + 6 != n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH); goto f_err; } if (s->session->tlsext_tick) { OPENSSL_free(s->session->tlsext_tick); s->session->tlsext_ticklen = 0; } s->session->tlsext_tick = OPENSSL_malloc(ticklen); if (!s->session->tlsext_tick) { SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,ERR_R_MALLOC_FAILURE); goto err; } memcpy(s->session->tlsext_tick, p, ticklen); s->session->tlsext_ticklen = ticklen; /* There are two ways to detect a resumed ticket session. * One is to set an appropriate session ID and then the server * must return a match in ServerHello. This allows the normal * client session ID matching to work and we know much * earlier that the ticket has been accepted. * * The other way is to set zero length session ID when the * ticket is presented and rely on the handshake to determine * session resumption. * * We choose the former approach because this fits in with * assumptions elsewhere in OpenSSL. The session ID is set * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the * ticket. */ EVP_Digest(p, ticklen, s->session->session_id, &s->session->session_id_length, #ifndef OPENSSL_NO_SHA256 EVP_sha256(), NULL); #else EVP_sha1(), NULL); #endif ret=1; return(ret); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: return(-1); } int ssl3_get_cert_status(SSL *s) { int ok, al; unsigned long resplen,n; const unsigned char *p; n=s->method->ssl_get_message(s, SSL3_ST_CR_CERT_STATUS_A, SSL3_ST_CR_CERT_STATUS_B, SSL3_MT_CERTIFICATE_STATUS, 16384, &ok); if (!ok) return((int)n); if (n < 4) { /* need at least status type + length */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH); goto f_err; } p = (unsigned char *)s->init_msg; if (*p++ != TLSEXT_STATUSTYPE_ocsp) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_UNSUPPORTED_STATUS_TYPE); goto f_err; } n2l3(p, resplen); if (resplen + 4 != n) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH); goto f_err; } if (s->tlsext_ocsp_resp) OPENSSL_free(s->tlsext_ocsp_resp); s->tlsext_ocsp_resp = BUF_memdup(p, resplen); if (!s->tlsext_ocsp_resp) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE); goto f_err; } s->tlsext_ocsp_resplen = resplen; if (s->ctx->tlsext_status_cb) { int ret; ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg); if (ret == 0) { al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE; SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_INVALID_STATUS_RESPONSE); goto f_err; } if (ret < 0) { al = SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE); goto f_err; } } return 1; f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); return(-1); } #endif int ssl3_get_server_done(SSL *s) { int ok,ret=0; long n; n=s->method->ssl_get_message(s, SSL3_ST_CR_SRVR_DONE_A, SSL3_ST_CR_SRVR_DONE_B, SSL3_MT_SERVER_DONE, 30, /* should be very small, like 0 :-) */ &ok); if (!ok) return((int)n); if (n > 0) { /* should contain no data */ ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR); SSLerr(SSL_F_SSL3_GET_SERVER_DONE,SSL_R_LENGTH_MISMATCH); return -1; } ret=1; return(ret); } int ssl3_send_client_key_exchange(SSL *s) { unsigned char *p; int n; unsigned long alg_k; #ifndef OPENSSL_NO_RSA unsigned char *q; EVP_PKEY *pkey=NULL; #endif #ifndef OPENSSL_NO_KRB5 KSSL_ERR kssl_err; #endif /* OPENSSL_NO_KRB5 */ #ifndef OPENSSL_NO_ECDH EC_KEY *clnt_ecdh = NULL; const EC_POINT *srvr_ecpoint = NULL; EVP_PKEY *srvr_pub_pkey = NULL; unsigned char *encodedPoint = NULL; int encoded_pt_len = 0; BN_CTX * bn_ctx = NULL; #endif if (s->state == SSL3_ST_CW_KEY_EXCH_A) { p = ssl_handshake_start(s); alg_k=s->s3->tmp.new_cipher->algorithm_mkey; /* Fool emacs indentation */ if (0) {} #ifndef OPENSSL_NO_RSA else if (alg_k & SSL_kRSA) { RSA *rsa; unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH]; if (s->session->sess_cert == NULL) { /* We should always have a server certificate with SSL_kRSA. */ SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } if (s->session->sess_cert->peer_rsa_tmp != NULL) rsa=s->session->sess_cert->peer_rsa_tmp; else { pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509); if ((pkey == NULL) || (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } rsa=pkey->pkey.rsa; EVP_PKEY_free(pkey); } tmp_buf[0]=s->client_version>>8; tmp_buf[1]=s->client_version&0xff; if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0) goto err; s->session->master_key_length=sizeof tmp_buf; q=p; /* Fix buf for TLS and beyond */ if (s->version > SSL3_VERSION) p+=2; n=RSA_public_encrypt(sizeof tmp_buf, tmp_buf,p,rsa,RSA_PKCS1_PADDING); #ifdef PKCS1_CHECK if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++; if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70; #endif if (n <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT); goto err; } /* Fix buf for TLS and beyond */ if (s->version > SSL3_VERSION) { s2n(n,q); n+=2; } s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key, tmp_buf,sizeof tmp_buf); OPENSSL_cleanse(tmp_buf,sizeof tmp_buf); } #endif #ifndef OPENSSL_NO_KRB5 else if (alg_k & SSL_kKRB5) { krb5_error_code krb5rc; KSSL_CTX *kssl_ctx = s->kssl_ctx; /* krb5_data krb5_ap_req; */ krb5_data *enc_ticket; krb5_data authenticator, *authp = NULL; EVP_CIPHER_CTX ciph_ctx; const EVP_CIPHER *enc = NULL; unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH]; unsigned char epms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_IV_LENGTH]; int padl, outl = sizeof(epms); EVP_CIPHER_CTX_init(&ciph_ctx); #ifdef KSSL_DEBUG fprintf(stderr,"ssl3_send_client_key_exchange(%lx & %lx)\n", alg_k, SSL_kKRB5); #endif /* KSSL_DEBUG */ authp = NULL; #ifdef KRB5SENDAUTH if (KRB5SENDAUTH) authp = &authenticator; #endif /* KRB5SENDAUTH */ krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp, &kssl_err); enc = kssl_map_enc(kssl_ctx->enctype); if (enc == NULL) goto err; #ifdef KSSL_DEBUG { fprintf(stderr,"kssl_cget_tkt rtn %d\n", krb5rc); if (krb5rc && kssl_err.text) fprintf(stderr,"kssl_cget_tkt kssl_err=%s\n", kssl_err.text); } #endif /* KSSL_DEBUG */ if (krb5rc) { ssl3_send_alert(s,SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, kssl_err.reason); goto err; } /*- * 20010406 VRS - Earlier versions used KRB5 AP_REQ * in place of RFC 2712 KerberosWrapper, as in: * * Send ticket (copy to *p, set n = length) * n = krb5_ap_req.length; * memcpy(p, krb5_ap_req.data, krb5_ap_req.length); * if (krb5_ap_req.data) * kssl_krb5_free_data_contents(NULL,&krb5_ap_req); * * Now using real RFC 2712 KerberosWrapper * (Thanks to Simon Wilkinson <sxw@sxw.org.uk>) * Note: 2712 "opaque" types are here replaced * with a 2-byte length followed by the value. * Example: * KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms * Where "xx xx" = length bytes. Shown here with * optional authenticator omitted. */ /* KerberosWrapper.Ticket */ s2n(enc_ticket->length,p); memcpy(p, enc_ticket->data, enc_ticket->length); p+= enc_ticket->length; n = enc_ticket->length + 2; /* KerberosWrapper.Authenticator */ if (authp && authp->length) { s2n(authp->length,p); memcpy(p, authp->data, authp->length); p+= authp->length; n+= authp->length + 2; free(authp->data); authp->data = NULL; authp->length = 0; } else { s2n(0,p);/* null authenticator length */ n+=2; } tmp_buf[0]=s->client_version>>8; tmp_buf[1]=s->client_version&0xff; if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0) goto err; /*- * 20010420 VRS. Tried it this way; failed. * EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL); * EVP_CIPHER_CTX_set_key_length(&ciph_ctx, * kssl_ctx->length); * EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv); */ memset(iv, 0, sizeof iv); /* per RFC 1510 */ EVP_EncryptInit_ex(&ciph_ctx,enc, NULL, kssl_ctx->key,iv); EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf, sizeof tmp_buf); EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl); outl += padl; if (outl > (int)sizeof epms) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } EVP_CIPHER_CTX_cleanup(&ciph_ctx); /* KerberosWrapper.EncryptedPreMasterSecret */ s2n(outl,p); memcpy(p, epms, outl); p+=outl; n+=outl + 2; s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key, tmp_buf, sizeof tmp_buf); OPENSSL_cleanse(tmp_buf, sizeof tmp_buf); OPENSSL_cleanse(epms, outl); } #endif #ifndef OPENSSL_NO_DH else if (alg_k & (SSL_kDHE|SSL_kDHr|SSL_kDHd)) { DH *dh_srvr,*dh_clnt; SESS_CERT *scert = s->session->sess_cert; if (scert == NULL) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE); goto err; } if (scert->peer_dh_tmp != NULL) dh_srvr=scert->peer_dh_tmp; else { /* we get them from the cert */ int idx = scert->peer_cert_type; EVP_PKEY *spkey = NULL; dh_srvr = NULL; if (idx >= 0) spkey = X509_get_pubkey( scert->peer_pkeys[idx].x509); if (spkey) { dh_srvr = EVP_PKEY_get1_DH(spkey); EVP_PKEY_free(spkey); } if (dh_srvr == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } } if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) { /* Use client certificate key */ EVP_PKEY *clkey = s->cert->key->privatekey; dh_clnt = NULL; if (clkey) dh_clnt = EVP_PKEY_get1_DH(clkey); if (dh_clnt == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } } else { /* generate a new random key */ if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); goto err; } if (!DH_generate_key(dh_clnt)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); DH_free(dh_clnt); goto err; } } /* use the 'p' output buffer for the DH key, but * make sure to clear it out afterwards */ n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt); if (scert->peer_dh_tmp == NULL) DH_free(dh_srvr); if (n <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); DH_free(dh_clnt); goto err; } /* generate master key from the result */ s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key,p,n); /* clean up */ memset(p,0,n); if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY) n = 0; else { /* send off the data */ n=BN_num_bytes(dh_clnt->pub_key); s2n(n,p); BN_bn2bin(dh_clnt->pub_key,p); n+=2; } DH_free(dh_clnt); /* perhaps clean things up a bit EAY EAY EAY EAY*/ } #endif #ifndef OPENSSL_NO_ECDH else if (alg_k & (SSL_kECDHE|SSL_kECDHr|SSL_kECDHe)) { const EC_GROUP *srvr_group = NULL; EC_KEY *tkey; int ecdh_clnt_cert = 0; int field_size = 0; if (s->session->sess_cert == NULL) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE); goto err; } /* Did we send out the client's * ECDH share for use in premaster * computation as part of client certificate? * If so, set ecdh_clnt_cert to 1. */ if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL)) { /*- * XXX: For now, we do not support client * authentication using ECDH certificates. * To add such support, one needs to add * code that checks for appropriate * conditions and sets ecdh_clnt_cert to 1. * For example, the cert have an ECC * key on the same curve as the server's * and the key should be authorized for * key agreement. * * One also needs to add code in ssl3_connect * to skip sending the certificate verify * message. * * if ((s->cert->key->privatekey != NULL) && * (s->cert->key->privatekey->type == * EVP_PKEY_EC) && ...) * ecdh_clnt_cert = 1; */ } if (s->session->sess_cert->peer_ecdh_tmp != NULL) { tkey = s->session->sess_cert->peer_ecdh_tmp; } else { /* Get the Server Public Key from Cert */ srvr_pub_pkey = X509_get_pubkey(s->session-> \ sess_cert->peer_pkeys[SSL_PKEY_ECC].x509); if ((srvr_pub_pkey == NULL) || (srvr_pub_pkey->type != EVP_PKEY_EC) || (srvr_pub_pkey->pkey.ec == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } tkey = srvr_pub_pkey->pkey.ec; } srvr_group = EC_KEY_get0_group(tkey); srvr_ecpoint = EC_KEY_get0_public_key(tkey); if ((srvr_group == NULL) || (srvr_ecpoint == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } if ((clnt_ecdh=EC_KEY_new()) == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } if (!EC_KEY_set_group(clnt_ecdh, srvr_group)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } if (ecdh_clnt_cert) { /* Reuse key info from our certificate * We only need our private key to perform * the ECDH computation. */ const BIGNUM *priv_key; tkey = s->cert->key->privatekey->pkey.ec; priv_key = EC_KEY_get0_private_key(tkey); if (priv_key == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } if (!EC_KEY_set_private_key(clnt_ecdh, priv_key)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB); goto err; } } else { /* Generate a new ECDH key pair */ if (!(EC_KEY_generate_key(clnt_ecdh))) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } } /* use the 'p' output buffer for the ECDH key, but * make sure to clear it out afterwards */ field_size = EC_GROUP_get_degree(srvr_group); if (field_size <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL); if (n <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } /* generate master key from the result */ s->session->master_key_length = s->method->ssl3_enc \ -> generate_master_secret(s, s->session->master_key, p, n); memset(p, 0, n); /* clean up */ if (ecdh_clnt_cert) { /* Send empty client key exch message */ n = 0; } else { /* First check the size of encoding and * allocate memory accordingly. */ encoded_pt_len = EC_POINT_point2oct(srvr_group, EC_KEY_get0_public_key(clnt_ecdh), POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL); encodedPoint = (unsigned char *) OPENSSL_malloc(encoded_pt_len * sizeof(unsigned char)); bn_ctx = BN_CTX_new(); if ((encodedPoint == NULL) || (bn_ctx == NULL)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } /* Encode the public key */ n = EC_POINT_point2oct(srvr_group, EC_KEY_get0_public_key(clnt_ecdh), POINT_CONVERSION_UNCOMPRESSED, encodedPoint, encoded_pt_len, bn_ctx); *p = n; /* length of encoded point */ /* Encoded point will be copied here */ p += 1; /* copy the point */ memcpy((unsigned char *)p, encodedPoint, n); /* increment n to account for length field */ n += 1; } /* Free allocated memory */ BN_CTX_free(bn_ctx); if (encodedPoint != NULL) OPENSSL_free(encodedPoint); if (clnt_ecdh != NULL) EC_KEY_free(clnt_ecdh); EVP_PKEY_free(srvr_pub_pkey); } #endif /* !OPENSSL_NO_ECDH */ else if (alg_k & SSL_kGOST) { /* GOST key exchange message creation */ EVP_PKEY_CTX *pkey_ctx; X509 *peer_cert; size_t msglen; unsigned int md_len; int keytype; unsigned char premaster_secret[32],shared_ukm[32], tmp[256]; EVP_MD_CTX *ukm_hash; EVP_PKEY *pub_key; /* Get server sertificate PKEY and create ctx from it */ peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST01)].x509; if (!peer_cert) peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST94)].x509; if (!peer_cert) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER); goto err; } pkey_ctx=EVP_PKEY_CTX_new(pub_key=X509_get_pubkey(peer_cert),NULL); /* If we have send a certificate, and certificate key * parameters match those of server certificate, use * certificate key for key exchange */ /* Otherwise, generate ephemeral key pair */ EVP_PKEY_encrypt_init(pkey_ctx); /* Generate session key */ RAND_bytes(premaster_secret,32); /* If we have client certificate, use its secret as peer key */ if (s->s3->tmp.cert_req && s->cert->key->privatekey) { if (EVP_PKEY_derive_set_peer(pkey_ctx,s->cert->key->privatekey) <=0) { /* If there was an error - just ignore it. Ephemeral key * would be used */ ERR_clear_error(); } } /* Compute shared IV and store it in algorithm-specific * context data */ ukm_hash = EVP_MD_CTX_create(); EVP_DigestInit(ukm_hash,EVP_get_digestbynid(NID_id_GostR3411_94)); EVP_DigestUpdate(ukm_hash,s->s3->client_random,SSL3_RANDOM_SIZE); EVP_DigestUpdate(ukm_hash,s->s3->server_random,SSL3_RANDOM_SIZE); EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len); EVP_MD_CTX_destroy(ukm_hash); if (EVP_PKEY_CTX_ctrl(pkey_ctx,-1,EVP_PKEY_OP_ENCRYPT,EVP_PKEY_CTRL_SET_IV, 8,shared_ukm)<0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_LIBRARY_BUG); goto err; } /* Make GOST keytransport blob message */ /*Encapsulate it into sequence */ *(p++)=V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED; msglen=255; if (EVP_PKEY_encrypt(pkey_ctx,tmp,&msglen,premaster_secret,32)<0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_LIBRARY_BUG); goto err; } if (msglen >= 0x80) { *(p++)=0x81; *(p++)= msglen & 0xff; n=msglen+3; } else { *(p++)= msglen & 0xff; n=msglen+2; } memcpy(p, tmp, msglen); /* Check if pubkey from client certificate was used */ if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) { /* Set flag "skip certificate verify" */ s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY; } EVP_PKEY_CTX_free(pkey_ctx); s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key,premaster_secret,32); EVP_PKEY_free(pub_key); } #ifndef OPENSSL_NO_SRP else if (alg_k & SSL_kSRP) { if (s->srp_ctx.A != NULL) { /* send off the data */ n=BN_num_bytes(s->srp_ctx.A); s2n(n,p); BN_bn2bin(s->srp_ctx.A,p); n+=2; } else { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } if (s->session->srp_username != NULL) OPENSSL_free(s->session->srp_username); s->session->srp_username = BUF_strdup(s->srp_ctx.login); if (s->session->srp_username == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } if ((s->session->master_key_length = SRP_generate_client_master_secret(s,s->session->master_key))<0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } } #endif #ifndef OPENSSL_NO_PSK else if (alg_k & SSL_kPSK) { /* The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes * to return a \0-terminated identity. The last byte * is for us for simulating strnlen. */ char identity[PSK_MAX_IDENTITY_LEN + 2]; size_t identity_len; unsigned char *t = NULL; unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4]; unsigned int pre_ms_len = 0, psk_len = 0; int psk_err = 1; n = 0; if (s->psk_client_callback == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_PSK_NO_CLIENT_CB); goto err; } memset(identity, 0, sizeof(identity)); psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint, identity, sizeof(identity) - 1, psk_or_pre_ms, sizeof(psk_or_pre_ms)); if (psk_len > PSK_MAX_PSK_LEN) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto psk_err; } else if (psk_len == 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, SSL_R_PSK_IDENTITY_NOT_FOUND); goto psk_err; } identity[PSK_MAX_IDENTITY_LEN + 1] = '\0'; identity_len = strlen(identity); if (identity_len > PSK_MAX_IDENTITY_LEN) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto psk_err; } /* create PSK pre_master_secret */ pre_ms_len = 2+psk_len+2+psk_len; t = psk_or_pre_ms; memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len); s2n(psk_len, t); memset(t, 0, psk_len); t+=psk_len; s2n(psk_len, t); if (s->session->psk_identity_hint != NULL) OPENSSL_free(s->session->psk_identity_hint); s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint); if (s->ctx->psk_identity_hint != NULL && s->session->psk_identity_hint == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto psk_err; } if (s->session->psk_identity != NULL) OPENSSL_free(s->session->psk_identity); s->session->psk_identity = BUF_strdup(identity); if (s->session->psk_identity == NULL) { SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto psk_err; } s->session->master_key_length = s->method->ssl3_enc->generate_master_secret(s, s->session->master_key, psk_or_pre_ms, pre_ms_len); s2n(identity_len, p); memcpy(p, identity, identity_len); n = 2 + identity_len; psk_err = 0; psk_err: OPENSSL_cleanse(identity, sizeof(identity)); OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms)); if (psk_err != 0) { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); goto err; } } #endif else { ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n); s->state=SSL3_ST_CW_KEY_EXCH_B; } /* SSL3_ST_CW_KEY_EXCH_B */ return ssl_do_write(s); err: #ifndef OPENSSL_NO_ECDH BN_CTX_free(bn_ctx); if (encodedPoint != NULL) OPENSSL_free(encodedPoint); if (clnt_ecdh != NULL) EC_KEY_free(clnt_ecdh); EVP_PKEY_free(srvr_pub_pkey); #endif return(-1); } int ssl3_send_client_verify(SSL *s) { unsigned char *p; unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH]; EVP_PKEY *pkey; EVP_PKEY_CTX *pctx=NULL; EVP_MD_CTX mctx; unsigned u=0; unsigned long n; int j; EVP_MD_CTX_init(&mctx); if (s->state == SSL3_ST_CW_CERT_VRFY_A) { p= ssl_handshake_start(s); pkey=s->cert->key->privatekey; /* Create context from key and test if sha1 is allowed as digest */ pctx = EVP_PKEY_CTX_new(pkey,NULL); EVP_PKEY_sign_init(pctx); if (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1())>0) { if (!SSL_USE_SIGALGS(s)) s->method->ssl3_enc->cert_verify_mac(s, NID_sha1, &(data[MD5_DIGEST_LENGTH])); } else { ERR_clear_error(); } /* For TLS v1.2 send signature algorithm and signature * using agreed digest and cached handshake records. */ if (SSL_USE_SIGALGS(s)) { long hdatalen = 0; void *hdata; const EVP_MD *md = s->cert->key->digest; hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata); if (hdatalen <= 0 || !tls12_get_sigandhash(p, pkey, md)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR); goto err; } p += 2; #ifdef SSL_DEBUG fprintf(stderr, "Using TLS 1.2 with client alg %s\n", EVP_MD_name(md)); #endif if (!EVP_SignInit_ex(&mctx, md, NULL) || !EVP_SignUpdate(&mctx, hdata, hdatalen) || !EVP_SignFinal(&mctx, p + 2, &u, pkey)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_EVP_LIB); goto err; } s2n(u,p); n = u + 4; if (!ssl3_digest_cached_records(s)) goto err; } else #ifndef OPENSSL_NO_RSA if (pkey->type == EVP_PKEY_RSA) { s->method->ssl3_enc->cert_verify_mac(s, NID_md5, &(data[0])); if (RSA_sign(NID_md5_sha1, data, MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, &(p[2]), &u, pkey->pkey.rsa) <= 0 ) { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB); goto err; } s2n(u,p); n=u+2; } else #endif #ifndef OPENSSL_NO_DSA if (pkey->type == EVP_PKEY_DSA) { if (!DSA_sign(pkey->save_type, &(data[MD5_DIGEST_LENGTH]), SHA_DIGEST_LENGTH,&(p[2]), (unsigned int *)&j,pkey->pkey.dsa)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB); goto err; } s2n(j,p); n=j+2; } else #endif #ifndef OPENSSL_NO_ECDSA if (pkey->type == EVP_PKEY_EC) { if (!ECDSA_sign(pkey->save_type, &(data[MD5_DIGEST_LENGTH]), SHA_DIGEST_LENGTH,&(p[2]), (unsigned int *)&j,pkey->pkey.ec)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_ECDSA_LIB); goto err; } s2n(j,p); n=j+2; } else #endif if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001) { unsigned char signbuf[64]; int i; size_t sigsize=64; s->method->ssl3_enc->cert_verify_mac(s, NID_id_GostR3411_94, data); if (EVP_PKEY_sign(pctx, signbuf, &sigsize, data, 32) <= 0) { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY, ERR_R_INTERNAL_ERROR); goto err; } for (i=63,j=0; i>=0; j++, i--) { p[2+j]=signbuf[i]; } s2n(j,p); n=j+2; } else { SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR); goto err; } ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_VERIFY, n); s->state=SSL3_ST_CW_CERT_VRFY_B; } EVP_MD_CTX_cleanup(&mctx); EVP_PKEY_CTX_free(pctx); return ssl_do_write(s); err: EVP_MD_CTX_cleanup(&mctx); EVP_PKEY_CTX_free(pctx); return(-1); } /* Check a certificate can be used for client authentication. Currently * check cert exists, if we have a suitable digest for TLS 1.2 if * static DH client certificates can be used and optionally checks * suitability for Suite B. */ static int ssl3_check_client_certificate(SSL *s) { unsigned long alg_k; if (!s->cert || !s->cert->key->x509 || !s->cert->key->privatekey) return 0; /* If no suitable signature algorithm can't use certificate */ if (SSL_USE_SIGALGS(s) && !s->cert->key->digest) return 0; /* If strict mode check suitability of chain before using it. * This also adjusts suite B digest if necessary. */ if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT && !tls1_check_chain(s, NULL, NULL, NULL, -2)) return 0; alg_k=s->s3->tmp.new_cipher->algorithm_mkey; /* See if we can use client certificate for fixed DH */ if (alg_k & (SSL_kDHr|SSL_kDHd)) { SESS_CERT *scert = s->session->sess_cert; int i = scert->peer_cert_type; EVP_PKEY *clkey = NULL, *spkey = NULL; clkey = s->cert->key->privatekey; /* If client key not DH assume it can be used */ if (EVP_PKEY_id(clkey) != EVP_PKEY_DH) return 1; if (i >= 0) spkey = X509_get_pubkey(scert->peer_pkeys[i].x509); if (spkey) { /* Compare server and client parameters */ i = EVP_PKEY_cmp_parameters(clkey, spkey); EVP_PKEY_free(spkey); if (i != 1) return 0; } s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY; } return 1; } int ssl3_send_client_certificate(SSL *s) { X509 *x509=NULL; EVP_PKEY *pkey=NULL; int i; if (s->state == SSL3_ST_CW_CERT_A) { /* Let cert callback update client certificates if required */ if (s->cert->cert_cb) { i = s->cert->cert_cb(s, s->cert->cert_cb_arg); if (i < 0) { s->rwstate=SSL_X509_LOOKUP; return -1; } if (i == 0) { ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR); return 0; } s->rwstate=SSL_NOTHING; } if (ssl3_check_client_certificate(s)) s->state=SSL3_ST_CW_CERT_C; else s->state=SSL3_ST_CW_CERT_B; } /* We need to get a client cert */ if (s->state == SSL3_ST_CW_CERT_B) { /* If we get an error, we need to * ssl->rwstate=SSL_X509_LOOKUP; return(-1); * We then get retied later */ i=0; i = ssl_do_client_cert_cb(s, &x509, &pkey); if (i < 0) { s->rwstate=SSL_X509_LOOKUP; return(-1); } s->rwstate=SSL_NOTHING; if ((i == 1) && (pkey != NULL) && (x509 != NULL)) { s->state=SSL3_ST_CW_CERT_B; if ( !SSL_use_certificate(s,x509) || !SSL_use_PrivateKey(s,pkey)) i=0; } else if (i == 1) { i=0; SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK); } if (x509 != NULL) X509_free(x509); if (pkey != NULL) EVP_PKEY_free(pkey); if (i && !ssl3_check_client_certificate(s)) i = 0; if (i == 0) { if (s->version == SSL3_VERSION) { s->s3->tmp.cert_req=0; ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE); return(1); } else { s->s3->tmp.cert_req=2; } } /* Ok, we have a cert */ s->state=SSL3_ST_CW_CERT_C; } if (s->state == SSL3_ST_CW_CERT_C) { s->state=SSL3_ST_CW_CERT_D; if (!ssl3_output_cert_chain(s, (s->s3->tmp.cert_req == 2)?NULL:s->cert->key)) { SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE, ERR_R_INTERNAL_ERROR); ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR); return 0; } } /* SSL3_ST_CW_CERT_D */ return ssl_do_write(s); } #define has_bits(i,m) (((i)&(m)) == (m)) int ssl3_check_cert_and_algorithm(SSL *s) { int i,idx; long alg_k,alg_a; EVP_PKEY *pkey=NULL; SESS_CERT *sc; #ifndef OPENSSL_NO_RSA RSA *rsa; #endif #ifndef OPENSSL_NO_DH DH *dh; #endif alg_k=s->s3->tmp.new_cipher->algorithm_mkey; alg_a=s->s3->tmp.new_cipher->algorithm_auth; /* we don't have a certificate */ if ((alg_a & (SSL_aNULL|SSL_aKRB5)) || (alg_k & SSL_kPSK)) return(1); sc=s->session->sess_cert; if (sc == NULL) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,ERR_R_INTERNAL_ERROR); goto err; } #ifndef OPENSSL_NO_RSA rsa=s->session->sess_cert->peer_rsa_tmp; #endif #ifndef OPENSSL_NO_DH dh=s->session->sess_cert->peer_dh_tmp; #endif /* This is the passed certificate */ idx=sc->peer_cert_type; #ifndef OPENSSL_NO_ECDH if (idx == SSL_PKEY_ECC) { if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509, s) == 0) { /* check failed */ SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_BAD_ECC_CERT); goto f_err; } else { return 1; } } else if (alg_a & SSL_aECDSA) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_ECDSA_SIGNING_CERT); goto f_err; } else if (alg_k & (SSL_kECDHr|SSL_kECDHe)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_ECDH_CERT); goto f_err; } #endif pkey=X509_get_pubkey(sc->peer_pkeys[idx].x509); i=X509_certificate_type(sc->peer_pkeys[idx].x509,pkey); EVP_PKEY_free(pkey); /* Check that we have a certificate if we require one */ if ((alg_a & SSL_aRSA) && !has_bits(i,EVP_PK_RSA|EVP_PKT_SIGN)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_SIGNING_CERT); goto f_err; } #ifndef OPENSSL_NO_DSA else if ((alg_a & SSL_aDSS) && !has_bits(i,EVP_PK_DSA|EVP_PKT_SIGN)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DSA_SIGNING_CERT); goto f_err; } #endif #ifndef OPENSSL_NO_RSA if ((alg_k & SSL_kRSA) && !(has_bits(i,EVP_PK_RSA|EVP_PKT_ENC) || (rsa != NULL))) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_ENCRYPTING_CERT); goto f_err; } #endif #ifndef OPENSSL_NO_DH if ((alg_k & SSL_kDHE) && !(has_bits(i,EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL))) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_KEY); goto f_err; } else if ((alg_k & SSL_kDHr) && !SSL_USE_SIGALGS(s) && !has_bits(i,EVP_PK_DH|EVP_PKS_RSA)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_RSA_CERT); goto f_err; } #ifndef OPENSSL_NO_DSA else if ((alg_k & SSL_kDHd) && !SSL_USE_SIGALGS(s) && !has_bits(i,EVP_PK_DH|EVP_PKS_DSA)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_DSA_CERT); goto f_err; } #endif #endif if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && !has_bits(i,EVP_PKT_EXP)) { #ifndef OPENSSL_NO_RSA if (alg_k & SSL_kRSA) { if (rsa == NULL || RSA_size(rsa)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_RSA_KEY); goto f_err; } } else #endif #ifndef OPENSSL_NO_DH if (alg_k & (SSL_kDHE|SSL_kDHr|SSL_kDHd)) { if (dh == NULL || DH_size(dh)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_DH_KEY); goto f_err; } } else #endif { SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE); goto f_err; } } return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); err: return(0); } /* Check to see if handshake is full or resumed. Usually this is just a * case of checking to see if a cache hit has occurred. In the case of * session tickets we have to check the next message to be sure. */ #ifndef OPENSSL_NO_TLSEXT # ifndef OPENSSL_NO_NEXTPROTONEG int ssl3_send_next_proto(SSL *s) { unsigned int len, padding_len; unsigned char *d; if (s->state == SSL3_ST_CW_NEXT_PROTO_A) { len = s->next_proto_negotiated_len; padding_len = 32 - ((len + 2) % 32); d = (unsigned char *)s->init_buf->data; d[4] = len; memcpy(d + 5, s->next_proto_negotiated, len); d[5 + len] = padding_len; memset(d + 6 + len, 0, padding_len); *(d++)=SSL3_MT_NEXT_PROTO; l2n3(2 + len + padding_len, d); s->state = SSL3_ST_CW_NEXT_PROTO_B; s->init_num = 4 + 2 + len + padding_len; s->init_off = 0; } return ssl3_do_write(s, SSL3_RT_HANDSHAKE); } # endif #endif int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey) { int i = 0; #ifndef OPENSSL_NO_ENGINE if (s->ctx->client_cert_engine) { i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s, SSL_get_client_CA_list(s), px509, ppkey, NULL, NULL, NULL); if (i != 0) return i; } #endif if (s->ctx->client_cert_cb) i = s->ctx->client_cert_cb(s,px509,ppkey); return i; }
./CrossVul/dataset_final_sorted/CWE-310/c/good_1445_4
crossvul-cpp_data_good_5666_1
/* * AEAD: Authenticated Encryption with Associated Data * * This file provides API support for AEAD algorithms. * * Copyright (c) 2007 Herbert Xu <herbert@gondor.apana.org.au> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include <crypto/internal/aead.h> #include <linux/err.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/rtnetlink.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/seq_file.h> #include <linux/cryptouser.h> #include <net/netlink.h> #include "internal.h" static int setkey_unaligned(struct crypto_aead *tfm, const u8 *key, unsigned int keylen) { struct aead_alg *aead = crypto_aead_alg(tfm); unsigned long alignmask = crypto_aead_alignmask(tfm); int ret; u8 *buffer, *alignbuffer; unsigned long absize; absize = keylen + alignmask; buffer = kmalloc(absize, GFP_ATOMIC); if (!buffer) return -ENOMEM; alignbuffer = (u8 *)ALIGN((unsigned long)buffer, alignmask + 1); memcpy(alignbuffer, key, keylen); ret = aead->setkey(tfm, alignbuffer, keylen); memset(alignbuffer, 0, keylen); kfree(buffer); return ret; } static int setkey(struct crypto_aead *tfm, const u8 *key, unsigned int keylen) { struct aead_alg *aead = crypto_aead_alg(tfm); unsigned long alignmask = crypto_aead_alignmask(tfm); if ((unsigned long)key & alignmask) return setkey_unaligned(tfm, key, keylen); return aead->setkey(tfm, key, keylen); } int crypto_aead_setauthsize(struct crypto_aead *tfm, unsigned int authsize) { struct aead_tfm *crt = crypto_aead_crt(tfm); int err; if (authsize > crypto_aead_alg(tfm)->maxauthsize) return -EINVAL; if (crypto_aead_alg(tfm)->setauthsize) { err = crypto_aead_alg(tfm)->setauthsize(crt->base, authsize); if (err) return err; } crypto_aead_crt(crt->base)->authsize = authsize; crt->authsize = authsize; return 0; } EXPORT_SYMBOL_GPL(crypto_aead_setauthsize); static unsigned int crypto_aead_ctxsize(struct crypto_alg *alg, u32 type, u32 mask) { return alg->cra_ctxsize; } static int no_givcrypt(struct aead_givcrypt_request *req) { return -ENOSYS; } static int crypto_init_aead_ops(struct crypto_tfm *tfm, u32 type, u32 mask) { struct aead_alg *alg = &tfm->__crt_alg->cra_aead; struct aead_tfm *crt = &tfm->crt_aead; if (max(alg->maxauthsize, alg->ivsize) > PAGE_SIZE / 8) return -EINVAL; crt->setkey = tfm->__crt_alg->cra_flags & CRYPTO_ALG_GENIV ? alg->setkey : setkey; crt->encrypt = alg->encrypt; crt->decrypt = alg->decrypt; crt->givencrypt = alg->givencrypt ?: no_givcrypt; crt->givdecrypt = alg->givdecrypt ?: no_givcrypt; crt->base = __crypto_aead_cast(tfm); crt->ivsize = alg->ivsize; crt->authsize = alg->maxauthsize; return 0; } #ifdef CONFIG_NET static int crypto_aead_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_aead raead; struct aead_alg *aead = &alg->cra_aead; strncpy(raead.type, "aead", sizeof(raead.type)); strncpy(raead.geniv, aead->geniv ?: "<built-in>", sizeof(raead.geniv)); raead.blocksize = alg->cra_blocksize; raead.maxauthsize = aead->maxauthsize; raead.ivsize = aead->ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_AEAD, sizeof(struct crypto_report_aead), &raead)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } #else static int crypto_aead_report(struct sk_buff *skb, struct crypto_alg *alg) { return -ENOSYS; } #endif static void crypto_aead_show(struct seq_file *m, struct crypto_alg *alg) __attribute__ ((unused)); static void crypto_aead_show(struct seq_file *m, struct crypto_alg *alg) { struct aead_alg *aead = &alg->cra_aead; seq_printf(m, "type : aead\n"); seq_printf(m, "async : %s\n", alg->cra_flags & CRYPTO_ALG_ASYNC ? "yes" : "no"); seq_printf(m, "blocksize : %u\n", alg->cra_blocksize); seq_printf(m, "ivsize : %u\n", aead->ivsize); seq_printf(m, "maxauthsize : %u\n", aead->maxauthsize); seq_printf(m, "geniv : %s\n", aead->geniv ?: "<built-in>"); } const struct crypto_type crypto_aead_type = { .ctxsize = crypto_aead_ctxsize, .init = crypto_init_aead_ops, #ifdef CONFIG_PROC_FS .show = crypto_aead_show, #endif .report = crypto_aead_report, }; EXPORT_SYMBOL_GPL(crypto_aead_type); static int aead_null_givencrypt(struct aead_givcrypt_request *req) { return crypto_aead_encrypt(&req->areq); } static int aead_null_givdecrypt(struct aead_givcrypt_request *req) { return crypto_aead_decrypt(&req->areq); } static int crypto_init_nivaead_ops(struct crypto_tfm *tfm, u32 type, u32 mask) { struct aead_alg *alg = &tfm->__crt_alg->cra_aead; struct aead_tfm *crt = &tfm->crt_aead; if (max(alg->maxauthsize, alg->ivsize) > PAGE_SIZE / 8) return -EINVAL; crt->setkey = setkey; crt->encrypt = alg->encrypt; crt->decrypt = alg->decrypt; if (!alg->ivsize) { crt->givencrypt = aead_null_givencrypt; crt->givdecrypt = aead_null_givdecrypt; } crt->base = __crypto_aead_cast(tfm); crt->ivsize = alg->ivsize; crt->authsize = alg->maxauthsize; return 0; } #ifdef CONFIG_NET static int crypto_nivaead_report(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_aead raead; struct aead_alg *aead = &alg->cra_aead; strncpy(raead.type, "nivaead", sizeof(raead.type)); strncpy(raead.geniv, aead->geniv, sizeof(raead.geniv)); raead.blocksize = alg->cra_blocksize; raead.maxauthsize = aead->maxauthsize; raead.ivsize = aead->ivsize; if (nla_put(skb, CRYPTOCFGA_REPORT_AEAD, sizeof(struct crypto_report_aead), &raead)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } #else static int crypto_nivaead_report(struct sk_buff *skb, struct crypto_alg *alg) { return -ENOSYS; } #endif static void crypto_nivaead_show(struct seq_file *m, struct crypto_alg *alg) __attribute__ ((unused)); static void crypto_nivaead_show(struct seq_file *m, struct crypto_alg *alg) { struct aead_alg *aead = &alg->cra_aead; seq_printf(m, "type : nivaead\n"); seq_printf(m, "async : %s\n", alg->cra_flags & CRYPTO_ALG_ASYNC ? "yes" : "no"); seq_printf(m, "blocksize : %u\n", alg->cra_blocksize); seq_printf(m, "ivsize : %u\n", aead->ivsize); seq_printf(m, "maxauthsize : %u\n", aead->maxauthsize); seq_printf(m, "geniv : %s\n", aead->geniv); } const struct crypto_type crypto_nivaead_type = { .ctxsize = crypto_aead_ctxsize, .init = crypto_init_nivaead_ops, #ifdef CONFIG_PROC_FS .show = crypto_nivaead_show, #endif .report = crypto_nivaead_report, }; EXPORT_SYMBOL_GPL(crypto_nivaead_type); static int crypto_grab_nivaead(struct crypto_aead_spawn *spawn, const char *name, u32 type, u32 mask) { struct crypto_alg *alg; int err; type &= ~(CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV); type |= CRYPTO_ALG_TYPE_AEAD; mask |= CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV; alg = crypto_alg_mod_lookup(name, type, mask); if (IS_ERR(alg)) return PTR_ERR(alg); err = crypto_init_spawn(&spawn->base, alg, spawn->base.inst, mask); crypto_mod_put(alg); return err; } struct crypto_instance *aead_geniv_alloc(struct crypto_template *tmpl, struct rtattr **tb, u32 type, u32 mask) { const char *name; struct crypto_aead_spawn *spawn; struct crypto_attr_type *algt; struct crypto_instance *inst; struct crypto_alg *alg; int err; algt = crypto_get_attr_type(tb); if (IS_ERR(algt)) return ERR_CAST(algt); if ((algt->type ^ (CRYPTO_ALG_TYPE_AEAD | CRYPTO_ALG_GENIV)) & algt->mask) return ERR_PTR(-EINVAL); name = crypto_attr_alg_name(tb[1]); if (IS_ERR(name)) return ERR_CAST(name); inst = kzalloc(sizeof(*inst) + sizeof(*spawn), GFP_KERNEL); if (!inst) return ERR_PTR(-ENOMEM); spawn = crypto_instance_ctx(inst); /* Ignore async algorithms if necessary. */ mask |= crypto_requires_sync(algt->type, algt->mask); crypto_set_aead_spawn(spawn, inst); err = crypto_grab_nivaead(spawn, name, type, mask); if (err) goto err_free_inst; alg = crypto_aead_spawn_alg(spawn); err = -EINVAL; if (!alg->cra_aead.ivsize) goto err_drop_alg; /* * This is only true if we're constructing an algorithm with its * default IV generator. For the default generator we elide the * template name and double-check the IV generator. */ if (algt->mask & CRYPTO_ALG_GENIV) { if (strcmp(tmpl->name, alg->cra_aead.geniv)) goto err_drop_alg; memcpy(inst->alg.cra_name, alg->cra_name, CRYPTO_MAX_ALG_NAME); memcpy(inst->alg.cra_driver_name, alg->cra_driver_name, CRYPTO_MAX_ALG_NAME); } else { err = -ENAMETOOLONG; if (snprintf(inst->alg.cra_name, CRYPTO_MAX_ALG_NAME, "%s(%s)", tmpl->name, alg->cra_name) >= CRYPTO_MAX_ALG_NAME) goto err_drop_alg; if (snprintf(inst->alg.cra_driver_name, CRYPTO_MAX_ALG_NAME, "%s(%s)", tmpl->name, alg->cra_driver_name) >= CRYPTO_MAX_ALG_NAME) goto err_drop_alg; } inst->alg.cra_flags = CRYPTO_ALG_TYPE_AEAD | CRYPTO_ALG_GENIV; inst->alg.cra_flags |= alg->cra_flags & CRYPTO_ALG_ASYNC; inst->alg.cra_priority = alg->cra_priority; inst->alg.cra_blocksize = alg->cra_blocksize; inst->alg.cra_alignmask = alg->cra_alignmask; inst->alg.cra_type = &crypto_aead_type; inst->alg.cra_aead.ivsize = alg->cra_aead.ivsize; inst->alg.cra_aead.maxauthsize = alg->cra_aead.maxauthsize; inst->alg.cra_aead.geniv = alg->cra_aead.geniv; inst->alg.cra_aead.setkey = alg->cra_aead.setkey; inst->alg.cra_aead.setauthsize = alg->cra_aead.setauthsize; inst->alg.cra_aead.encrypt = alg->cra_aead.encrypt; inst->alg.cra_aead.decrypt = alg->cra_aead.decrypt; out: return inst; err_drop_alg: crypto_drop_aead(spawn); err_free_inst: kfree(inst); inst = ERR_PTR(err); goto out; } EXPORT_SYMBOL_GPL(aead_geniv_alloc); void aead_geniv_free(struct crypto_instance *inst) { crypto_drop_aead(crypto_instance_ctx(inst)); kfree(inst); } EXPORT_SYMBOL_GPL(aead_geniv_free); int aead_geniv_init(struct crypto_tfm *tfm) { struct crypto_instance *inst = (void *)tfm->__crt_alg; struct crypto_aead *aead; aead = crypto_spawn_aead(crypto_instance_ctx(inst)); if (IS_ERR(aead)) return PTR_ERR(aead); tfm->crt_aead.base = aead; tfm->crt_aead.reqsize += crypto_aead_reqsize(aead); return 0; } EXPORT_SYMBOL_GPL(aead_geniv_init); void aead_geniv_exit(struct crypto_tfm *tfm) { crypto_free_aead(tfm->crt_aead.base); } EXPORT_SYMBOL_GPL(aead_geniv_exit); static int crypto_nivaead_default(struct crypto_alg *alg, u32 type, u32 mask) { struct rtattr *tb[3]; struct { struct rtattr attr; struct crypto_attr_type data; } ptype; struct { struct rtattr attr; struct crypto_attr_alg data; } palg; struct crypto_template *tmpl; struct crypto_instance *inst; struct crypto_alg *larval; const char *geniv; int err; larval = crypto_larval_lookup(alg->cra_driver_name, CRYPTO_ALG_TYPE_AEAD | CRYPTO_ALG_GENIV, CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV); err = PTR_ERR(larval); if (IS_ERR(larval)) goto out; err = -EAGAIN; if (!crypto_is_larval(larval)) goto drop_larval; ptype.attr.rta_len = sizeof(ptype); ptype.attr.rta_type = CRYPTOA_TYPE; ptype.data.type = type | CRYPTO_ALG_GENIV; /* GENIV tells the template that we're making a default geniv. */ ptype.data.mask = mask | CRYPTO_ALG_GENIV; tb[0] = &ptype.attr; palg.attr.rta_len = sizeof(palg); palg.attr.rta_type = CRYPTOA_ALG; /* Must use the exact name to locate ourselves. */ memcpy(palg.data.name, alg->cra_driver_name, CRYPTO_MAX_ALG_NAME); tb[1] = &palg.attr; tb[2] = NULL; geniv = alg->cra_aead.geniv; tmpl = crypto_lookup_template(geniv); err = -ENOENT; if (!tmpl) goto kill_larval; inst = tmpl->alloc(tb); err = PTR_ERR(inst); if (IS_ERR(inst)) goto put_tmpl; if ((err = crypto_register_instance(tmpl, inst))) { tmpl->free(inst); goto put_tmpl; } /* Redo the lookup to use the instance we just registered. */ err = -EAGAIN; put_tmpl: crypto_tmpl_put(tmpl); kill_larval: crypto_larval_kill(larval); drop_larval: crypto_mod_put(larval); out: crypto_mod_put(alg); return err; } struct crypto_alg *crypto_lookup_aead(const char *name, u32 type, u32 mask) { struct crypto_alg *alg; alg = crypto_alg_mod_lookup(name, type, mask); if (IS_ERR(alg)) return alg; if (alg->cra_type == &crypto_aead_type) return alg; if (!alg->cra_aead.ivsize) return alg; crypto_mod_put(alg); alg = crypto_alg_mod_lookup(name, type | CRYPTO_ALG_TESTED, mask & ~CRYPTO_ALG_TESTED); if (IS_ERR(alg)) return alg; if (alg->cra_type == &crypto_aead_type) { if ((alg->cra_flags ^ type ^ ~mask) & CRYPTO_ALG_TESTED) { crypto_mod_put(alg); alg = ERR_PTR(-ENOENT); } return alg; } BUG_ON(!alg->cra_aead.ivsize); return ERR_PTR(crypto_nivaead_default(alg, type, mask)); } EXPORT_SYMBOL_GPL(crypto_lookup_aead); int crypto_grab_aead(struct crypto_aead_spawn *spawn, const char *name, u32 type, u32 mask) { struct crypto_alg *alg; int err; type &= ~(CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV); type |= CRYPTO_ALG_TYPE_AEAD; mask &= ~(CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV); mask |= CRYPTO_ALG_TYPE_MASK; alg = crypto_lookup_aead(name, type, mask); if (IS_ERR(alg)) return PTR_ERR(alg); err = crypto_init_spawn(&spawn->base, alg, spawn->base.inst, mask); crypto_mod_put(alg); return err; } EXPORT_SYMBOL_GPL(crypto_grab_aead); struct crypto_aead *crypto_alloc_aead(const char *alg_name, u32 type, u32 mask) { struct crypto_tfm *tfm; int err; type &= ~(CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV); type |= CRYPTO_ALG_TYPE_AEAD; mask &= ~(CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_GENIV); mask |= CRYPTO_ALG_TYPE_MASK; for (;;) { struct crypto_alg *alg; alg = crypto_lookup_aead(alg_name, type, mask); if (IS_ERR(alg)) { err = PTR_ERR(alg); goto err; } tfm = __crypto_alloc_tfm(alg, type, mask); if (!IS_ERR(tfm)) return __crypto_aead_cast(tfm); crypto_mod_put(alg); err = PTR_ERR(tfm); err: if (err != -EAGAIN) break; if (signal_pending(current)) { err = -EINTR; break; } } return ERR_PTR(err); } EXPORT_SYMBOL_GPL(crypto_alloc_aead); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Authenticated Encryption with Associated Data (AEAD)");
./CrossVul/dataset_final_sorted/CWE-310/c/good_5666_1
crossvul-cpp_data_good_1446_0
/* ssl/s3_srvr.c -*- mode:C; c-file-style: "eay" -*- */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ /* ==================================================================== * Copyright (c) 1998-2007 The OpenSSL 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: * * 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. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* ==================================================================== * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * * Portions of the attached software ("Contribution") are developed by * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project. * * The Contribution is licensed pursuant to the OpenSSL open source * license provided above. * * ECC cipher suite support in OpenSSL originally written by * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories. * */ /* ==================================================================== * Copyright 2005 Nokia. All rights reserved. * * The portions of the attached software ("Contribution") is developed by * Nokia Corporation and is licensed pursuant to the OpenSSL open source * license. * * The Contribution, originally written by Mika Kousa and Pasi Eronen of * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites * support (see RFC 4279) to OpenSSL. * * No patent licenses or other rights except those expressly stated in * the OpenSSL open source license shall be deemed granted or received * expressly, by implication, estoppel, or otherwise. * * No assurances are provided by Nokia that the Contribution does not * infringe the patent or other intellectual property rights of any third * party or that the license provides you with all the necessary rights * to make use of the Contribution. * * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR * OTHERWISE. */ #define REUSE_CIPHER_BUG #define NETSCAPE_HANG_BUG #include <stdio.h> #include "ssl_locl.h" #include "kssl_lcl.h" #include "../crypto/constant_time_locl.h" #include <openssl/buffer.h> #include <openssl/rand.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/hmac.h> #include <openssl/x509.h> #ifndef OPENSSL_NO_DH #include <openssl/dh.h> #endif #include <openssl/bn.h> #ifndef OPENSSL_NO_KRB5 #include <openssl/krb5_asn.h> #endif #include <openssl/md5.h> #ifndef OPENSSL_NO_SSL3_METHOD static const SSL_METHOD *ssl3_get_server_method(int ver); static const SSL_METHOD *ssl3_get_server_method(int ver) { if (ver == SSL3_VERSION) return(SSLv3_server_method()); else return(NULL); } IMPLEMENT_ssl3_meth_func(SSLv3_server_method, ssl3_accept, ssl_undefined_function, ssl3_get_server_method) #endif #ifndef OPENSSL_NO_SRP static int ssl_check_srp_ext_ClientHello(SSL *s, int *al) { int ret = SSL_ERROR_NONE; *al = SSL_AD_UNRECOGNIZED_NAME; if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) && (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) { if(s->srp_ctx.login == NULL) { /* RFC 5054 says SHOULD reject, we do so if There is no srp login name */ ret = SSL3_AL_FATAL; *al = SSL_AD_UNKNOWN_PSK_IDENTITY; } else { ret = SSL_srp_server_param_with_username(s,al); } } return ret; } #endif int ssl3_accept(SSL *s) { BUF_MEM *buf; unsigned long alg_k,Time=(unsigned long)time(NULL); void (*cb)(const SSL *ssl,int type,int val)=NULL; int ret= -1; int new_state,state,skip=0; RAND_add(&Time,sizeof(Time),0); ERR_clear_error(); clear_sys_error(); if (s->info_callback != NULL) cb=s->info_callback; else if (s->ctx->info_callback != NULL) cb=s->ctx->info_callback; /* init things to blank */ s->in_handshake++; if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); if (s->cert == NULL) { SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET); return(-1); } #ifndef OPENSSL_NO_HEARTBEATS /* If we're awaiting a HeartbeatResponse, pretend we * already got and don't await it anymore, because * Heartbeats don't make sense during handshakes anyway. */ if (s->tlsext_hb_pending) { s->tlsext_hb_pending = 0; s->tlsext_hb_seq++; } #endif for (;;) { state=s->state; switch (s->state) { case SSL_ST_RENEGOTIATE: s->renegotiate=1; /* s->state=SSL_ST_ACCEPT; */ case SSL_ST_BEFORE: case SSL_ST_ACCEPT: case SSL_ST_BEFORE|SSL_ST_ACCEPT: case SSL_ST_OK|SSL_ST_ACCEPT: s->server=1; if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1); if ((s->version>>8) != 3) { SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR); return -1; } if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) { SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_VERSION_TOO_LOW); return -1; } s->type=SSL_ST_ACCEPT; if (s->init_buf == NULL) { if ((buf=BUF_MEM_new()) == NULL) { ret= -1; goto end; } if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH)) { BUF_MEM_free(buf); ret= -1; goto end; } s->init_buf=buf; } if (!ssl3_setup_buffers(s)) { ret= -1; goto end; } s->init_num=0; s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY; s->s3->flags &= ~SSL3_FLAGS_CCS_OK; /* Should have been reset by ssl3_get_finished, too. */ s->s3->change_cipher_spec = 0; if (s->state != SSL_ST_RENEGOTIATE) { /* Ok, we now need to push on a buffering BIO so that * the output is sent in a way that TCP likes :-) */ if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; } ssl3_init_finished_mac(s); s->state=SSL3_ST_SR_CLNT_HELLO_A; s->ctx->stats.sess_accept++; } else if (!s->s3->send_connection_binding && !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { /* Server attempting to renegotiate with * client that doesn't support secure * renegotiation. */ SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); ret = -1; goto end; } else { /* s->state == SSL_ST_RENEGOTIATE, * we will just send a HelloRequest */ s->ctx->stats.sess_accept_renegotiate++; s->state=SSL3_ST_SW_HELLO_REQ_A; } break; case SSL3_ST_SW_HELLO_REQ_A: case SSL3_ST_SW_HELLO_REQ_B: s->shutdown=0; ret=ssl3_send_hello_request(s); if (ret <= 0) goto end; s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C; s->state=SSL3_ST_SW_FLUSH; s->init_num=0; ssl3_init_finished_mac(s); break; case SSL3_ST_SW_HELLO_REQ_C: s->state=SSL_ST_OK; break; case SSL3_ST_SR_CLNT_HELLO_A: case SSL3_ST_SR_CLNT_HELLO_B: case SSL3_ST_SR_CLNT_HELLO_C: ret=ssl3_get_client_hello(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_SRP s->state = SSL3_ST_SR_CLNT_HELLO_D; case SSL3_ST_SR_CLNT_HELLO_D: { int al; if ((ret = ssl_check_srp_ext_ClientHello(s,&al)) < 0) { /* callback indicates firther work to be done */ s->rwstate=SSL_X509_LOOKUP; goto end; } if (ret != SSL_ERROR_NONE) { ssl3_send_alert(s,SSL3_AL_FATAL,al); /* This is not really an error but the only means to for a client to detect whether srp is supported. */ if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY) SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLSEXT); ret = SSL_TLSEXT_ERR_ALERT_FATAL; ret= -1; goto end; } } #endif s->renegotiate = 2; s->state=SSL3_ST_SW_SRVR_HELLO_A; s->init_num=0; break; case SSL3_ST_SW_SRVR_HELLO_A: case SSL3_ST_SW_SRVR_HELLO_B: ret=ssl3_send_server_hello(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_TLSEXT if (s->hit) { if (s->tlsext_ticket_expected) s->state=SSL3_ST_SW_SESSION_TICKET_A; else s->state=SSL3_ST_SW_CHANGE_A; } #else if (s->hit) s->state=SSL3_ST_SW_CHANGE_A; #endif else s->state = SSL3_ST_SW_CERT_A; s->init_num = 0; break; case SSL3_ST_SW_CERT_A: case SSL3_ST_SW_CERT_B: /* Check if it is anon DH or anon ECDH, */ /* normal PSK or KRB5 or SRP */ if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aKRB5|SSL_aSRP)) && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { ret=ssl3_send_server_certificate(s); if (ret <= 0) goto end; #ifndef OPENSSL_NO_TLSEXT if (s->tlsext_status_expected) s->state=SSL3_ST_SW_CERT_STATUS_A; else s->state=SSL3_ST_SW_KEY_EXCH_A; } else { skip = 1; s->state=SSL3_ST_SW_KEY_EXCH_A; } #else } else skip=1; s->state=SSL3_ST_SW_KEY_EXCH_A; #endif s->init_num=0; break; case SSL3_ST_SW_KEY_EXCH_A: case SSL3_ST_SW_KEY_EXCH_B: alg_k = s->s3->tmp.new_cipher->algorithm_mkey; /* * clear this, it may get reset by * send_server_key_exchange */ s->s3->tmp.use_rsa_tmp=0; /* only send if a DH key exchange, fortezza or * RSA but we have a sign only certificate * * PSK: may send PSK identity hints * * For ECC ciphersuites, we send a serverKeyExchange * message only if the cipher suite is either * ECDH-anon or ECDHE. In other cases, the * server certificate contains the server's * public key for key exchange. */ if (0 /* PSK: send ServerKeyExchange if PSK identity * hint if provided */ #ifndef OPENSSL_NO_PSK || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint) #endif #ifndef OPENSSL_NO_SRP /* SRP: send ServerKeyExchange */ || (alg_k & SSL_kSRP) #endif || (alg_k & SSL_kDHE) || (alg_k & SSL_kECDHE) || ((alg_k & SSL_kRSA) && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher) ) ) ) ) { ret=ssl3_send_server_key_exchange(s); if (ret <= 0) goto end; } else skip=1; s->state=SSL3_ST_SW_CERT_REQ_A; s->init_num=0; break; case SSL3_ST_SW_CERT_REQ_A: case SSL3_ST_SW_CERT_REQ_B: if (/* don't request cert unless asked for it: */ !(s->verify_mode & SSL_VERIFY_PEER) || /* if SSL_VERIFY_CLIENT_ONCE is set, * don't request cert during re-negotiation: */ ((s->session->peer != NULL) && (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) || /* never request cert in anonymous ciphersuites * (see section "Certificate request" in SSL 3 drafts * and in RFC 2246): */ ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) && /* ... except when the application insists on verification * (against the specs, but s3_clnt.c accepts this for SSL 3) */ !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) || /* never request cert in Kerberos ciphersuites */ (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) || /* don't request certificate for SRP auth */ (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP) /* With normal PSK Certificates and * Certificate Requests are omitted */ || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { /* no cert request */ skip=1; s->s3->tmp.cert_request=0; s->state=SSL3_ST_SW_SRVR_DONE_A; if (s->s3->handshake_buffer) if (!ssl3_digest_cached_records(s)) return -1; } else { s->s3->tmp.cert_request=1; ret=ssl3_send_certificate_request(s); if (ret <= 0) goto end; #ifndef NETSCAPE_HANG_BUG s->state=SSL3_ST_SW_SRVR_DONE_A; #else s->state=SSL3_ST_SW_FLUSH; s->s3->tmp.next_state=SSL3_ST_SR_CERT_A; #endif s->init_num=0; } break; case SSL3_ST_SW_SRVR_DONE_A: case SSL3_ST_SW_SRVR_DONE_B: ret=ssl3_send_server_done(s); if (ret <= 0) goto end; s->s3->tmp.next_state=SSL3_ST_SR_CERT_A; s->state=SSL3_ST_SW_FLUSH; s->init_num=0; break; case SSL3_ST_SW_FLUSH: /* This code originally checked to see if * any data was pending using BIO_CTRL_INFO * and then flushed. This caused problems * as documented in PR#1939. The proposed * fix doesn't completely resolve this issue * as buggy implementations of BIO_CTRL_PENDING * still exist. So instead we just flush * unconditionally. */ s->rwstate=SSL_WRITING; if (BIO_flush(s->wbio) <= 0) { ret= -1; goto end; } s->rwstate=SSL_NOTHING; s->state=s->s3->tmp.next_state; break; case SSL3_ST_SR_CERT_A: case SSL3_ST_SR_CERT_B: if (s->s3->tmp.cert_request) { ret=ssl3_get_client_certificate(s); if (ret <= 0) goto end; } s->init_num=0; s->state=SSL3_ST_SR_KEY_EXCH_A; break; case SSL3_ST_SR_KEY_EXCH_A: case SSL3_ST_SR_KEY_EXCH_B: ret=ssl3_get_client_key_exchange(s); if (ret <= 0) goto end; if (ret == 2) { /* For the ECDH ciphersuites when * the client sends its ECDH pub key in * a certificate, the CertificateVerify * message is not sent. * Also for GOST ciphersuites when * the client uses its key from the certificate * for key exchange. */ #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) s->state=SSL3_ST_SR_FINISHED_A; #else if (s->s3->next_proto_neg_seen) s->state=SSL3_ST_SR_NEXT_PROTO_A; else s->state=SSL3_ST_SR_FINISHED_A; #endif s->init_num = 0; } else if (SSL_USE_SIGALGS(s)) { s->state=SSL3_ST_SR_CERT_VRFY_A; s->init_num=0; if (!s->session->peer) break; /* For sigalgs freeze the handshake buffer * at this point and digest cached records. */ if (!s->s3->handshake_buffer) { SSLerr(SSL_F_SSL3_ACCEPT,ERR_R_INTERNAL_ERROR); return -1; } s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE; if (!ssl3_digest_cached_records(s)) return -1; } else { int offset=0; int dgst_num; s->state=SSL3_ST_SR_CERT_VRFY_A; s->init_num=0; /* We need to get hashes here so if there is * a client cert, it can be verified * FIXME - digest processing for CertificateVerify * should be generalized. But it is next step */ if (s->s3->handshake_buffer) if (!ssl3_digest_cached_records(s)) return -1; for (dgst_num=0; dgst_num<SSL_MAX_DIGEST;dgst_num++) if (s->s3->handshake_dgst[dgst_num]) { int dgst_size; s->method->ssl3_enc->cert_verify_mac(s,EVP_MD_CTX_type(s->s3->handshake_dgst[dgst_num]),&(s->s3->tmp.cert_verify_md[offset])); dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]); if (dgst_size < 0) { ret = -1; goto end; } offset+=dgst_size; } } break; case SSL3_ST_SR_CERT_VRFY_A: case SSL3_ST_SR_CERT_VRFY_B: /* * This *should* be the first time we enable CCS, but be * extra careful about surrounding code changes. We need * to set this here because we don't know if we're * expecting a CertificateVerify or not. */ if (!s->s3->change_cipher_spec) s->s3->flags |= SSL3_FLAGS_CCS_OK; /* we should decide if we expected this one */ ret=ssl3_get_cert_verify(s); if (ret <= 0) goto end; #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) s->state=SSL3_ST_SR_FINISHED_A; #else if (s->s3->next_proto_neg_seen) s->state=SSL3_ST_SR_NEXT_PROTO_A; else s->state=SSL3_ST_SR_FINISHED_A; #endif s->init_num=0; break; #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) case SSL3_ST_SR_NEXT_PROTO_A: case SSL3_ST_SR_NEXT_PROTO_B: /* * Enable CCS for resumed handshakes with NPN. * In a full handshake with NPN, we end up here through * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was * already set. Receiving a CCS clears the flag, so make * sure not to re-enable it to ban duplicates. * s->s3->change_cipher_spec is set when a CCS is * processed in s3_pkt.c, and remains set until * the client's Finished message is read. */ if (!s->s3->change_cipher_spec) s->s3->flags |= SSL3_FLAGS_CCS_OK; ret=ssl3_get_next_proto(s); if (ret <= 0) goto end; s->init_num = 0; s->state=SSL3_ST_SR_FINISHED_A; break; #endif case SSL3_ST_SR_FINISHED_A: case SSL3_ST_SR_FINISHED_B: /* * Enable CCS for resumed handshakes without NPN. * In a full handshake, we end up here through * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was * already set. Receiving a CCS clears the flag, so make * sure not to re-enable it to ban duplicates. * s->s3->change_cipher_spec is set when a CCS is * processed in s3_pkt.c, and remains set until * the client's Finished message is read. */ if (!s->s3->change_cipher_spec) s->s3->flags |= SSL3_FLAGS_CCS_OK; ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A, SSL3_ST_SR_FINISHED_B); if (ret <= 0) goto end; if (s->hit) s->state=SSL_ST_OK; #ifndef OPENSSL_NO_TLSEXT else if (s->tlsext_ticket_expected) s->state=SSL3_ST_SW_SESSION_TICKET_A; #endif else s->state=SSL3_ST_SW_CHANGE_A; s->init_num=0; break; #ifndef OPENSSL_NO_TLSEXT case SSL3_ST_SW_SESSION_TICKET_A: case SSL3_ST_SW_SESSION_TICKET_B: ret=ssl3_send_newsession_ticket(s); if (ret <= 0) goto end; s->state=SSL3_ST_SW_CHANGE_A; s->init_num=0; break; case SSL3_ST_SW_CERT_STATUS_A: case SSL3_ST_SW_CERT_STATUS_B: ret=ssl3_send_cert_status(s); if (ret <= 0) goto end; s->state=SSL3_ST_SW_KEY_EXCH_A; s->init_num=0; break; #endif case SSL3_ST_SW_CHANGE_A: case SSL3_ST_SW_CHANGE_B: s->session->cipher=s->s3->tmp.new_cipher; if (!s->method->ssl3_enc->setup_key_block(s)) { ret= -1; goto end; } ret=ssl3_send_change_cipher_spec(s, SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B); if (ret <= 0) goto end; s->state=SSL3_ST_SW_FINISHED_A; s->init_num=0; if (!s->method->ssl3_enc->change_cipher_state(s, SSL3_CHANGE_CIPHER_SERVER_WRITE)) { ret= -1; goto end; } break; case SSL3_ST_SW_FINISHED_A: case SSL3_ST_SW_FINISHED_B: ret=ssl3_send_finished(s, SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B, s->method->ssl3_enc->server_finished_label, s->method->ssl3_enc->server_finished_label_len); if (ret <= 0) goto end; s->state=SSL3_ST_SW_FLUSH; if (s->hit) { #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A; #else if (s->s3->next_proto_neg_seen) { s->s3->tmp.next_state=SSL3_ST_SR_NEXT_PROTO_A; } else s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A; #endif } else s->s3->tmp.next_state=SSL_ST_OK; s->init_num=0; break; case SSL_ST_OK: /* clean a few things up */ ssl3_cleanup_key_block(s); BUF_MEM_free(s->init_buf); s->init_buf=NULL; /* remove buffering on output */ ssl_free_wbio_buffer(s); s->init_num=0; if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */ { s->renegotiate=0; s->new_session=0; ssl_update_cache(s,SSL_SESS_CACHE_SERVER); s->ctx->stats.sess_accept_good++; /* s->server=1; */ s->handshake_func=ssl3_accept; if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1); } ret = 1; goto end; /* break; */ default: SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE); ret= -1; goto end; /* break; */ } if (!s->s3->tmp.reuse_message && !skip) { if (s->debug) { if ((ret=BIO_flush(s->wbio)) <= 0) goto end; } if ((cb != NULL) && (s->state != state)) { new_state=s->state; s->state=state; cb(s,SSL_CB_ACCEPT_LOOP,1); s->state=new_state; } } skip=0; } end: /* BIO_flush(s->wbio); */ s->in_handshake--; if (cb != NULL) cb(s,SSL_CB_ACCEPT_EXIT,ret); return(ret); } int ssl3_send_hello_request(SSL *s) { if (s->state == SSL3_ST_SW_HELLO_REQ_A) { ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0); s->state=SSL3_ST_SW_HELLO_REQ_B; } /* SSL3_ST_SW_HELLO_REQ_B */ return ssl_do_write(s); } int ssl3_get_client_hello(SSL *s) { int i,j,ok,al=SSL_AD_INTERNAL_ERROR,ret= -1; unsigned int cookie_len; long n; unsigned long id; unsigned char *p,*d; SSL_CIPHER *c; #ifndef OPENSSL_NO_COMP unsigned char *q; SSL_COMP *comp=NULL; #endif STACK_OF(SSL_CIPHER) *ciphers=NULL; if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet) goto retry_cert; /* We do this so that we will respond with our native type. * If we are TLSv1 and we get SSLv3, we will respond with TLSv1, * This down switching should be handled by a different method. * If we are SSLv3, we will respond with SSLv3, even if prompted with * TLSv1. */ if (s->state == SSL3_ST_SR_CLNT_HELLO_A ) { s->state=SSL3_ST_SR_CLNT_HELLO_B; } s->first_packet=1; n=s->method->ssl_get_message(s, SSL3_ST_SR_CLNT_HELLO_B, SSL3_ST_SR_CLNT_HELLO_C, SSL3_MT_CLIENT_HELLO, SSL3_RT_MAX_PLAIN_LENGTH, &ok); if (!ok) return((int)n); s->first_packet=0; d=p=(unsigned char *)s->init_msg; /* use version from inside client hello, not from record header * (may differ: see RFC 2246, Appendix E, second paragraph) */ s->client_version=(((int)p[0])<<8)|(int)p[1]; p+=2; if (SSL_IS_DTLS(s) ? (s->client_version > s->version && s->method->version != DTLS_ANY_VERSION) : (s->client_version < s->version)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER); if ((s->client_version>>8) == SSL3_VERSION_MAJOR && !s->enc_write_ctx && !s->write_hash) { /* similar to ssl3_get_record, send alert using remote version number */ s->version = s->client_version; } al = SSL_AD_PROTOCOL_VERSION; goto f_err; } /* If we require cookies and this ClientHello doesn't * contain one, just return since we do not want to * allocate any memory yet. So check cookie length... */ if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) { unsigned int session_length, cookie_length; session_length = *(p + SSL3_RANDOM_SIZE); cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1); if (cookie_length == 0) return 1; } /* load the client random */ memcpy(s->s3->client_random,p,SSL3_RANDOM_SIZE); p+=SSL3_RANDOM_SIZE; /* get the session-id */ j= *(p++); s->hit=0; /* Versions before 0.9.7 always allow clients to resume sessions in renegotiation. * 0.9.7 and later allow this by default, but optionally ignore resumption requests * with flag SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather * than a change to default behavior so that applications relying on this for security * won't even compile against older library versions). * * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to request * renegotiation but not a new session (s->new_session remains unset): for servers, * this essentially just means that the SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION * setting will be ignored. */ if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) { if (!ssl_get_new_session(s,1)) goto err; } else { i=ssl_get_prev_session(s, p, j, d + n); /* * Only resume if the session's version matches the negotiated * version. * RFC 5246 does not provide much useful advice on resumption * with a different protocol version. It doesn't forbid it but * the sanity of such behaviour would be questionable. * In practice, clients do not accept a version mismatch and * will abort the handshake with an error. */ if (i == 1 && s->version == s->session->ssl_version) { /* previous session */ s->hit=1; } else if (i == -1) goto err; else /* i == 0 */ { if (!ssl_get_new_session(s,1)) goto err; } } p+=j; if (SSL_IS_DTLS(s)) { /* cookie stuff */ cookie_len = *(p++); /* * The ClientHello may contain a cookie even if the * HelloVerify message has not been sent--make sure that it * does not cause an overflow. */ if ( cookie_len > sizeof(s->d1->rcvd_cookie)) { /* too much data */ al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } /* verify the cookie if appropriate option is set. */ if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) && cookie_len > 0) { memcpy(s->d1->rcvd_cookie, p, cookie_len); if ( s->ctx->app_verify_cookie_cb != NULL) { if ( s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie, cookie_len) == 0) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } /* else cookie verification succeeded */ } else if ( memcmp(s->d1->rcvd_cookie, s->d1->cookie, s->d1->cookie_len) != 0) /* default verification */ { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH); goto f_err; } /* Set to -2 so if successful we return 2 */ ret = -2; } p += cookie_len; if (s->method->version == DTLS_ANY_VERSION) { /* Select version to use */ if (s->client_version <= DTLS1_2_VERSION && !(s->options & SSL_OP_NO_DTLSv1_2)) { s->version = DTLS1_2_VERSION; s->method = DTLSv1_2_server_method(); } else if (tls1_suiteb(s)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE); s->version = s->client_version; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } else if (s->client_version <= DTLS1_VERSION && !(s->options & SSL_OP_NO_DTLSv1)) { s->version = DTLS1_VERSION; s->method = DTLSv1_server_method(); } else { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER); s->version = s->client_version; al = SSL_AD_PROTOCOL_VERSION; goto f_err; } s->session->ssl_version = s->version; } } n2s(p,i); if ((i == 0) && (j != 0)) { /* we need a cipher if we are not resuming a session */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_SPECIFIED); goto f_err; } if ((p+i) >= (d+n)) { /* not enough data */ al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH); goto f_err; } if ((i > 0) && (ssl_bytes_to_cipher_list(s,p,i,&(ciphers)) == NULL)) { goto err; } p+=i; /* If it is a hit, check that the cipher is in the list */ if ((s->hit) && (i > 0)) { j=0; id=s->session->cipher->id; #ifdef CIPHER_DEBUG fprintf(stderr,"client sent %d ciphers\n",sk_SSL_CIPHER_num(ciphers)); #endif for (i=0; i<sk_SSL_CIPHER_num(ciphers); i++) { c=sk_SSL_CIPHER_value(ciphers,i); #ifdef CIPHER_DEBUG fprintf(stderr,"client [%2d of %2d]:%s\n", i,sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c)); #endif if (c->id == id) { j=1; break; } } /* Disabled because it can be used in a ciphersuite downgrade * attack: CVE-2010-4180. */ #if 0 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1)) { /* Special case as client bug workaround: the previously used cipher may * not be in the current list, the client instead might be trying to * continue using a cipher that before wasn't chosen due to server * preferences. We'll have to reject the connection if the cipher is not * enabled, though. */ c = sk_SSL_CIPHER_value(ciphers, 0); if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) { s->session->cipher = c; j = 1; } } #endif if (j == 0) { /* we need to have the cipher in the cipher * list if we are asked to reuse it */ al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_CIPHER_MISSING); goto f_err; } } /* compression */ i= *(p++); if ((p+i) > (d+n)) { /* not enough data */ al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH); goto f_err; } #ifndef OPENSSL_NO_COMP q=p; #endif for (j=0; j<i; j++) { if (p[j] == 0) break; } p+=i; if (j >= i) { /* no compress */ al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_COMPRESSION_SPECIFIED); goto f_err; } #ifndef OPENSSL_NO_TLSEXT /* TLS extensions*/ if (s->version >= SSL3_VERSION) { if (!ssl_parse_clienthello_tlsext(s,&p,d,n)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_PARSE_TLSEXT); goto err; } } /* Check if we want to use external pre-shared secret for this * handshake for not reused session only. We need to generate * server_random before calling tls_session_secret_cb in order to allow * SessionTicket processing to use it in key derivation. */ { unsigned char *pos; pos=s->s3->server_random; if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) { goto f_err; } } if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) { SSL_CIPHER *pref_cipher=NULL; s->session->master_key_length=sizeof(s->session->master_key); if(s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length, ciphers, &pref_cipher, s->tls_session_secret_cb_arg)) { s->hit=1; s->session->ciphers=ciphers; s->session->verify_result=X509_V_OK; ciphers=NULL; /* check if some cipher was preferred by call back */ pref_cipher=pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s)); if (pref_cipher == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER); goto f_err; } s->session->cipher=pref_cipher; if (s->cipher_list) sk_SSL_CIPHER_free(s->cipher_list); if (s->cipher_list_by_id) sk_SSL_CIPHER_free(s->cipher_list_by_id); s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers); s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers); } } #endif /* Worst case, we will use the NULL compression, but if we have other * options, we will now look for them. We have i-1 compression * algorithms from the client, starting at q. */ s->s3->tmp.new_compression=NULL; #ifndef OPENSSL_NO_COMP /* This only happens if we have a cache hit */ if (s->session->compress_meth != 0) { int m, comp_id = s->session->compress_meth; /* Perform sanity checks on resumed compression algorithm */ /* Can't disable compression */ if (!ssl_allow_compression(s)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } /* Look for resumed compression method */ for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) { comp=sk_SSL_COMP_value(s->ctx->comp_methods,m); if (comp_id == comp->id) { s->s3->tmp.new_compression=comp; break; } } if (s->s3->tmp.new_compression == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INVALID_COMPRESSION_ALGORITHM); goto f_err; } /* Look for resumed method in compression list */ for (m = 0; m < i; m++) { if (q[m] == comp_id) break; } if (m >= i) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING); goto f_err; } } else if (s->hit) comp = NULL; else if (ssl_allow_compression(s) && s->ctx->comp_methods) { /* See if we have a match */ int m,nn,o,v,done=0; nn=sk_SSL_COMP_num(s->ctx->comp_methods); for (m=0; m<nn; m++) { comp=sk_SSL_COMP_value(s->ctx->comp_methods,m); v=comp->id; for (o=0; o<i; o++) { if (v == q[o]) { done=1; break; } } if (done) break; } if (done) s->s3->tmp.new_compression=comp; else comp=NULL; } #else /* If compression is disabled we'd better not try to resume a session * using compression. */ if (s->session->compress_meth != 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION); goto f_err; } #endif /* Given s->session->ciphers and SSL_get_ciphers, we must * pick a cipher */ if (!s->hit) { #ifdef OPENSSL_NO_COMP s->session->compress_meth=0; #else s->session->compress_meth=(comp == NULL)?0:comp->id; #endif if (s->session->ciphers != NULL) sk_SSL_CIPHER_free(s->session->ciphers); s->session->ciphers=ciphers; if (ciphers == NULL) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_PASSED); goto f_err; } ciphers=NULL; if (!tls1_set_server_sigalgs(s)) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); goto err; } /* Let cert callback update server certificates if required */ retry_cert: if (s->cert->cert_cb) { int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg); if (rv == 0) { al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_CERT_CB_ERROR); goto f_err; } if (rv < 0) { s->rwstate=SSL_X509_LOOKUP; return -1; } s->rwstate = SSL_NOTHING; } c=ssl3_choose_cipher(s,s->session->ciphers, SSL_get_ciphers(s)); if (c == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER); goto f_err; } s->s3->tmp.new_cipher=c; /* check whether we should disable session resumption */ if (s->not_resumable_session_cb != NULL) s->session->not_resumable=s->not_resumable_session_cb(s, ((c->algorithm_mkey & (SSL_kDHE | SSL_kECDHE)) != 0)); if (s->session->not_resumable) /* do not send a session ticket */ s->tlsext_ticket_expected = 0; } else { /* Session-id reuse */ #ifdef REUSE_CIPHER_BUG STACK_OF(SSL_CIPHER) *sk; SSL_CIPHER *nc=NULL; SSL_CIPHER *ec=NULL; if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG) { sk=s->session->ciphers; for (i=0; i<sk_SSL_CIPHER_num(sk); i++) { c=sk_SSL_CIPHER_value(sk,i); if (c->algorithm_enc & SSL_eNULL) nc=c; if (SSL_C_IS_EXPORT(c)) ec=c; } if (nc != NULL) s->s3->tmp.new_cipher=nc; else if (ec != NULL) s->s3->tmp.new_cipher=ec; else s->s3->tmp.new_cipher=s->session->cipher; } else #endif s->s3->tmp.new_cipher=s->session->cipher; } if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) { if (!ssl3_digest_cached_records(s)) goto f_err; } /*- * we now have the following setup. * client_random * cipher_list - our prefered list of ciphers * ciphers - the clients prefered list of ciphers * compression - basically ignored right now * ssl version is set - sslv3 * s->session - The ssl session has been setup. * s->hit - session reuse flag * s->s3->tmp.new_cipher- the new cipher to use. */ /* Handles TLS extensions that we couldn't check earlier */ if (s->version >= SSL3_VERSION) { if (ssl_check_clienthello_tlsext_late(s) <= 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); goto err; } } if (ret < 0) ret=-ret; if (0) { f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); } err: if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers); return ret < 0 ? -1 : ret; } int ssl3_send_server_hello(SSL *s) { unsigned char *buf; unsigned char *p,*d; int i,sl; int al = 0; unsigned long l; if (s->state == SSL3_ST_SW_SRVR_HELLO_A) { buf=(unsigned char *)s->init_buf->data; #ifdef OPENSSL_NO_TLSEXT p=s->s3->server_random; if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0) return -1; #endif /* Do the message type and length last */ d=p= ssl_handshake_start(s); *(p++)=s->version>>8; *(p++)=s->version&0xff; /* Random stuff */ memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE); p+=SSL3_RANDOM_SIZE; /*- * There are several cases for the session ID to send * back in the server hello: * - For session reuse from the session cache, * we send back the old session ID. * - If stateless session reuse (using a session ticket) * is successful, we send back the client's "session ID" * (which doesn't actually identify the session). * - If it is a new session, we send back the new * session ID. * - However, if we want the new session to be single-use, * we send back a 0-length session ID. * s->hit is non-zero in either case of session reuse, * so the following won't overwrite an ID that we're supposed * to send back. */ if (s->session->not_resumable || (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER) && !s->hit)) s->session->session_id_length=0; sl=s->session->session_id_length; if (sl > (int)sizeof(s->session->session_id)) { SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR); return -1; } *(p++)=sl; memcpy(p,s->session->session_id,sl); p+=sl; /* put the cipher */ i=ssl3_put_cipher_by_char(s->s3->tmp.new_cipher,p); p+=i; /* put the compression method */ #ifdef OPENSSL_NO_COMP *(p++)=0; #else if (s->s3->tmp.new_compression == NULL) *(p++)=0; else *(p++)=s->s3->tmp.new_compression->id; #endif #ifndef OPENSSL_NO_TLSEXT if (ssl_prepare_serverhello_tlsext(s) <= 0) { SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT); return -1; } if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH, &al)) == NULL) { ssl3_send_alert(s, SSL3_AL_FATAL, al); SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,ERR_R_INTERNAL_ERROR); return -1; } #endif /* do the header */ l=(p-d); ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l); s->state=SSL3_ST_SW_SRVR_HELLO_B; } /* SSL3_ST_SW_SRVR_HELLO_B */ return ssl_do_write(s); } int ssl3_send_server_done(SSL *s) { if (s->state == SSL3_ST_SW_SRVR_DONE_A) { ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0); s->state = SSL3_ST_SW_SRVR_DONE_B; } /* SSL3_ST_SW_SRVR_DONE_B */ return ssl_do_write(s); } int ssl3_send_server_key_exchange(SSL *s) { #ifndef OPENSSL_NO_RSA unsigned char *q; int j,num; RSA *rsa; unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH]; unsigned int u; #endif #ifndef OPENSSL_NO_DH DH *dh=NULL,*dhp; #endif #ifndef OPENSSL_NO_ECDH EC_KEY *ecdh=NULL, *ecdhp; unsigned char *encodedPoint = NULL; int encodedlen = 0; int curve_id = 0; BN_CTX *bn_ctx = NULL; #endif EVP_PKEY *pkey; const EVP_MD *md = NULL; unsigned char *p,*d; int al,i; unsigned long type; int n; CERT *cert; BIGNUM *r[4]; int nr[4],kn; BUF_MEM *buf; EVP_MD_CTX md_ctx; EVP_MD_CTX_init(&md_ctx); if (s->state == SSL3_ST_SW_KEY_EXCH_A) { type=s->s3->tmp.new_cipher->algorithm_mkey; cert=s->cert; buf=s->init_buf; r[0]=r[1]=r[2]=r[3]=NULL; n=0; #ifndef OPENSSL_NO_RSA if (type & SSL_kRSA) { rsa=cert->rsa_tmp; if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) { rsa=s->cert->rsa_tmp_cb(s, SSL_C_IS_EXPORT(s->s3->tmp.new_cipher), SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)); if(rsa == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ERROR_GENERATING_TMP_RSA_KEY); goto f_err; } RSA_up_ref(rsa); cert->rsa_tmp=rsa; } if (rsa == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_KEY); goto f_err; } r[0]=rsa->n; r[1]=rsa->e; s->s3->tmp.use_rsa_tmp=1; } else #endif #ifndef OPENSSL_NO_DH if (type & SSL_kDHE) { if (s->cert->dh_tmp_auto) { dhp = ssl_get_auto_dh(s); if (dhp == NULL) { al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto f_err; } } else dhp=cert->dh_tmp; if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL)) dhp=s->cert->dh_tmp_cb(s, SSL_C_IS_EXPORT(s->s3->tmp.new_cipher), SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)); if (dhp == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY); goto f_err; } if (!ssl_security(s, SSL_SECOP_TMP_DH, DH_security_bits(dhp), 0, dhp)) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_DH_KEY_TOO_SMALL); goto f_err; } if (s->s3->tmp.dh != NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } if (s->cert->dh_tmp_auto) dh = dhp; else if ((dh=DHparams_dup(dhp)) == NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB); goto err; } s->s3->tmp.dh=dh; if ((dhp->pub_key == NULL || dhp->priv_key == NULL || (s->options & SSL_OP_SINGLE_DH_USE))) { if(!DH_generate_key(dh)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB); goto err; } } else { dh->pub_key=BN_dup(dhp->pub_key); dh->priv_key=BN_dup(dhp->priv_key); if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB); goto err; } } r[0]=dh->p; r[1]=dh->g; r[2]=dh->pub_key; } else #endif #ifndef OPENSSL_NO_ECDH if (type & SSL_kECDHE) { const EC_GROUP *group; ecdhp=cert->ecdh_tmp; if (s->cert->ecdh_tmp_auto) { /* Get NID of appropriate shared curve */ int nid = tls1_shared_curve(s, -2); if (nid != NID_undef) ecdhp = EC_KEY_new_by_curve_name(nid); } else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb) { ecdhp=s->cert->ecdh_tmp_cb(s, SSL_C_IS_EXPORT(s->s3->tmp.new_cipher), SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)); } if (ecdhp == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY); goto f_err; } if (s->s3->tmp.ecdh != NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto err; } /* Duplicate the ECDH structure. */ if (ecdhp == NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB); goto err; } if (s->cert->ecdh_tmp_auto) ecdh = ecdhp; else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB); goto err; } s->s3->tmp.ecdh=ecdh; if ((EC_KEY_get0_public_key(ecdh) == NULL) || (EC_KEY_get0_private_key(ecdh) == NULL) || (s->options & SSL_OP_SINGLE_ECDH_USE)) { if(!EC_KEY_generate_key(ecdh)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB); goto err; } } if (((group = EC_KEY_get0_group(ecdh)) == NULL) || (EC_KEY_get0_public_key(ecdh) == NULL) || (EC_KEY_get0_private_key(ecdh) == NULL)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB); goto err; } if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && (EC_GROUP_get_degree(group) > 163)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER); goto err; } /* XXX: For now, we only support ephemeral ECDH * keys over named (not generic) curves. For * supported named curves, curve_id is non-zero. */ if ((curve_id = tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group))) == 0) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNSUPPORTED_ELLIPTIC_CURVE); goto err; } /* Encode the public key. * First check the size of encoding and * allocate memory accordingly. */ encodedlen = EC_POINT_point2oct(group, EC_KEY_get0_public_key(ecdh), POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL); encodedPoint = (unsigned char *) OPENSSL_malloc(encodedlen*sizeof(unsigned char)); bn_ctx = BN_CTX_new(); if ((encodedPoint == NULL) || (bn_ctx == NULL)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE); goto err; } encodedlen = EC_POINT_point2oct(group, EC_KEY_get0_public_key(ecdh), POINT_CONVERSION_UNCOMPRESSED, encodedPoint, encodedlen, bn_ctx); if (encodedlen == 0) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB); goto err; } BN_CTX_free(bn_ctx); bn_ctx=NULL; /* XXX: For now, we only support named (not * generic) curves in ECDH ephemeral key exchanges. * In this situation, we need four additional bytes * to encode the entire ServerECDHParams * structure. */ n = 4 + encodedlen; /* We'll generate the serverKeyExchange message * explicitly so we can set these to NULLs */ r[0]=NULL; r[1]=NULL; r[2]=NULL; r[3]=NULL; } else #endif /* !OPENSSL_NO_ECDH */ #ifndef OPENSSL_NO_PSK if (type & SSL_kPSK) { /* reserve size for record length and PSK identity hint*/ n+=2+strlen(s->ctx->psk_identity_hint); } else #endif /* !OPENSSL_NO_PSK */ #ifndef OPENSSL_NO_SRP if (type & SSL_kSRP) { if ((s->srp_ctx.N == NULL) || (s->srp_ctx.g == NULL) || (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_SRP_PARAM); goto err; } r[0]=s->srp_ctx.N; r[1]=s->srp_ctx.g; r[2]=s->srp_ctx.s; r[3]=s->srp_ctx.B; } else #endif { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE); goto f_err; } for (i=0; i < 4 && r[i] != NULL; i++) { nr[i]=BN_num_bytes(r[i]); #ifndef OPENSSL_NO_SRP if ((i == 2) && (type & SSL_kSRP)) n+=1+nr[i]; else #endif n+=2+nr[i]; } if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP)) && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher,&md)) == NULL) { al=SSL_AD_DECODE_ERROR; goto f_err; } kn=EVP_PKEY_size(pkey); } else { pkey=NULL; kn=0; } if (!BUF_MEM_grow_clean(buf,n+SSL_HM_HEADER_LENGTH(s)+kn)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF); goto err; } d = p = ssl_handshake_start(s); for (i=0; i < 4 && r[i] != NULL; i++) { #ifndef OPENSSL_NO_SRP if ((i == 2) && (type & SSL_kSRP)) { *p = nr[i]; p++; } else #endif s2n(nr[i],p); BN_bn2bin(r[i],p); p+=nr[i]; } #ifndef OPENSSL_NO_ECDH if (type & SSL_kECDHE) { /* XXX: For now, we only support named (not generic) curves. * In this situation, the serverKeyExchange message has: * [1 byte CurveType], [2 byte CurveName] * [1 byte length of encoded point], followed by * the actual encoded point itself */ *p = NAMED_CURVE_TYPE; p += 1; *p = 0; p += 1; *p = curve_id; p += 1; *p = encodedlen; p += 1; memcpy((unsigned char*)p, (unsigned char *)encodedPoint, encodedlen); OPENSSL_free(encodedPoint); encodedPoint = NULL; p += encodedlen; } #endif #ifndef OPENSSL_NO_PSK if (type & SSL_kPSK) { /* copy PSK identity hint */ s2n(strlen(s->ctx->psk_identity_hint), p); strncpy((char *)p, s->ctx->psk_identity_hint, strlen(s->ctx->psk_identity_hint)); p+=strlen(s->ctx->psk_identity_hint); } #endif /* not anonymous */ if (pkey != NULL) { /* n is the length of the params, they start at &(d[4]) * and p points to the space at the end. */ #ifndef OPENSSL_NO_RSA if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) { q=md_buf; j=0; for (num=2; num > 0; num--) { EVP_MD_CTX_set_flags(&md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); EVP_DigestInit_ex(&md_ctx,(num == 2) ?s->ctx->md5:s->ctx->sha1, NULL); EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_DigestUpdate(&md_ctx,d,n); EVP_DigestFinal_ex(&md_ctx,q, (unsigned int *)&i); q+=i; j+=i; } if (RSA_sign(NID_md5_sha1, md_buf, j, &(p[2]), &u, pkey->pkey.rsa) <= 0) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_RSA); goto err; } s2n(u,p); n+=u+2; } else #endif if (md) { /* send signature algorithm */ if (SSL_USE_SIGALGS(s)) { if (!tls12_get_sigandhash(p, pkey, md)) { /* Should never happen */ al=SSL_AD_INTERNAL_ERROR; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto f_err; } p+=2; } #ifdef SSL_DEBUG fprintf(stderr, "Using hash %s\n", EVP_MD_name(md)); #endif EVP_SignInit_ex(&md_ctx, md, NULL); EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE); EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE); EVP_SignUpdate(&md_ctx,d,n); if (!EVP_SignFinal(&md_ctx,&(p[2]), (unsigned int *)&i,pkey)) { SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_EVP); goto err; } s2n(i,p); n+=i+2; if (SSL_USE_SIGALGS(s)) n+= 2; } else { /* Is this error check actually needed? */ al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_PKEY_TYPE); goto f_err; } } ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n); } s->state = SSL3_ST_SW_KEY_EXCH_B; EVP_MD_CTX_cleanup(&md_ctx); return ssl_do_write(s); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); err: #ifndef OPENSSL_NO_ECDH if (encodedPoint != NULL) OPENSSL_free(encodedPoint); BN_CTX_free(bn_ctx); #endif EVP_MD_CTX_cleanup(&md_ctx); return(-1); } int ssl3_send_certificate_request(SSL *s) { unsigned char *p,*d; int i,j,nl,off,n; STACK_OF(X509_NAME) *sk=NULL; X509_NAME *name; BUF_MEM *buf; if (s->state == SSL3_ST_SW_CERT_REQ_A) { buf=s->init_buf; d=p=ssl_handshake_start(s); /* get the list of acceptable cert types */ p++; n=ssl3_get_req_cert_type(s,p); d[0]=n; p+=n; n++; if (SSL_USE_SIGALGS(s)) { const unsigned char *psigs; unsigned char *etmp = p; nl = tls12_get_psigalgs(s, &psigs); /* Skip over length for now */ p += 2; nl = tls12_copy_sigalgs(s, p, psigs, nl); /* Now fill in length */ s2n(nl, etmp); p += nl; n += nl + 2; } off=n; p+=2; n+=2; sk=SSL_get_client_CA_list(s); nl=0; if (sk != NULL) { for (i=0; i<sk_X509_NAME_num(sk); i++) { name=sk_X509_NAME_value(sk,i); j=i2d_X509_NAME(name,NULL); if (!BUF_MEM_grow_clean(buf,SSL_HM_HEADER_LENGTH(s)+n+j+2)) { SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB); goto err; } p = ssl_handshake_start(s) + n; if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG)) { s2n(j,p); i2d_X509_NAME(name,&p); n+=2+j; nl+=2+j; } else { d=p; i2d_X509_NAME(name,&p); j-=2; s2n(j,d); j+=2; n+=j; nl+=j; } } } /* else no CA names */ p = ssl_handshake_start(s) + off; s2n(nl,p); ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n); #ifdef NETSCAPE_HANG_BUG if (!SSL_IS_DTLS(s)) { if (!BUF_MEM_grow_clean(buf, s->init_num + 4)) { SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB); goto err; } p=(unsigned char *)s->init_buf->data + s->init_num; /* do the header */ *(p++)=SSL3_MT_SERVER_DONE; *(p++)=0; *(p++)=0; *(p++)=0; s->init_num += 4; } #endif s->state = SSL3_ST_SW_CERT_REQ_B; } /* SSL3_ST_SW_CERT_REQ_B */ return ssl_do_write(s); err: return(-1); } int ssl3_get_client_key_exchange(SSL *s) { int i,al,ok; long n; unsigned long alg_k; unsigned char *p; #ifndef OPENSSL_NO_RSA RSA *rsa=NULL; EVP_PKEY *pkey=NULL; #endif #ifndef OPENSSL_NO_DH BIGNUM *pub=NULL; DH *dh_srvr, *dh_clnt = NULL; #endif #ifndef OPENSSL_NO_KRB5 KSSL_ERR kssl_err; #endif /* OPENSSL_NO_KRB5 */ #ifndef OPENSSL_NO_ECDH EC_KEY *srvr_ecdh = NULL; EVP_PKEY *clnt_pub_pkey = NULL; EC_POINT *clnt_ecpoint = NULL; BN_CTX *bn_ctx = NULL; #endif n=s->method->ssl_get_message(s, SSL3_ST_SR_KEY_EXCH_A, SSL3_ST_SR_KEY_EXCH_B, SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, /* ??? */ &ok); if (!ok) return((int)n); p=(unsigned char *)s->init_msg; alg_k=s->s3->tmp.new_cipher->algorithm_mkey; #ifndef OPENSSL_NO_RSA if (alg_k & SSL_kRSA) { unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH]; int decrypt_len; unsigned char decrypt_good, version_good; size_t j; /* FIX THIS UP EAY EAY EAY EAY */ if (s->s3->tmp.use_rsa_tmp) { if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL)) rsa=s->cert->rsa_tmp; /* Don't do a callback because rsa_tmp should * be sent already */ if (rsa == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_PKEY); goto f_err; } } else { pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey; if ( (pkey == NULL) || (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE); goto f_err; } rsa=pkey->pkey.rsa; } /* TLS and [incidentally] DTLS{0xFEFF} */ if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER) { n2s(p,i); if (n != i+2) { if (!(s->options & SSL_OP_TLS_D5_BUG)) { al = SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG); goto f_err; } else p-=2; } else n=i; } /* * Reject overly short RSA ciphertext because we want to be sure * that the buffer size makes it safe to iterate over the entire * size of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The * actual expected size is larger due to RSA padding, but the * bound is sufficient to be safe. */ if (n < SSL_MAX_MASTER_KEY_LENGTH) { al = SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG); goto f_err; } /* We must not leak whether a decryption failure occurs because * of Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see * RFC 2246, section 7.4.7.1). The code follows that advice of * the TLS RFC and generates a random premaster secret for the * case that the decrypt fails. See * https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */ /* should be RAND_bytes, but we cannot work around a failure. */ if (RAND_pseudo_bytes(rand_premaster_secret, sizeof(rand_premaster_secret)) <= 0) goto err; decrypt_len = RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING); ERR_clear_error(); /* decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. * decrypt_good will be 0xff if so and zero otherwise. */ decrypt_good = constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH); /* If the version in the decrypted pre-master secret is correct * then version_good will be 0xff, otherwise it'll be zero. * The Klima-Pokorny-Rosa extension of Bleichenbacher's attack * (http://eprint.iacr.org/2003/052/) exploits the version * number check as a "bad version oracle". Thus version checks * are done in constant time and are treated like any other * decryption error. */ version_good = constant_time_eq_8(p[0], (unsigned)(s->client_version>>8)); version_good &= constant_time_eq_8(p[1], (unsigned)(s->client_version&0xff)); /* The premaster secret must contain the same version number as * the ClientHello to detect version rollback attacks * (strangely, the protocol does not offer such protection for * DH ciphersuites). However, buggy clients exist that send the * negotiated protocol version instead if the server does not * support the requested protocol version. If * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */ if (s->options & SSL_OP_TLS_ROLLBACK_BUG) { unsigned char workaround_good; workaround_good = constant_time_eq_8(p[0], (unsigned)(s->version>>8)); workaround_good &= constant_time_eq_8(p[1], (unsigned)(s->version&0xff)); version_good |= workaround_good; } /* Both decryption and version must be good for decrypt_good * to remain non-zero (0xff). */ decrypt_good &= version_good; /* * Now copy rand_premaster_secret over from p using * decrypt_good_mask. If decryption failed, then p does not * contain valid plaintext, however, a check above guarantees * it is still sufficiently large to read from. */ for (j = 0; j < sizeof(rand_premaster_secret); j++) { p[j] = constant_time_select_8(decrypt_good, p[j], rand_premaster_secret[j]); } s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key, p,sizeof(rand_premaster_secret)); OPENSSL_cleanse(p,sizeof(rand_premaster_secret)); } else #endif #ifndef OPENSSL_NO_DH if (alg_k & (SSL_kDHE|SSL_kDHr|SSL_kDHd)) { int idx = -1; EVP_PKEY *skey = NULL; if (n) n2s(p,i); else i = 0; if (n && n != i+2) { if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG); goto err; } else { p-=2; i=(int)n; } } if (alg_k & SSL_kDHr) idx = SSL_PKEY_DH_RSA; else if (alg_k & SSL_kDHd) idx = SSL_PKEY_DH_DSA; if (idx >= 0) { skey = s->cert->pkeys[idx].privatekey; if ((skey == NULL) || (skey->type != EVP_PKEY_DH) || (skey->pkey.dh == NULL)) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE); goto f_err; } dh_srvr = skey->pkey.dh; } else if (s->s3->tmp.dh == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY); goto f_err; } else dh_srvr=s->s3->tmp.dh; if (n == 0L) { /* Get pubkey from cert */ EVP_PKEY *clkey=X509_get_pubkey(s->session->peer); if (clkey) { if (EVP_PKEY_cmp_parameters(clkey, skey) == 1) dh_clnt = EVP_PKEY_get1_DH(clkey); } if (dh_clnt == NULL) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY); goto f_err; } EVP_PKEY_free(clkey); pub = dh_clnt->pub_key; } else pub=BN_bin2bn(p,i,NULL); if (pub == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BN_LIB); goto err; } i=DH_compute_key(p,pub,dh_srvr); if (i <= 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB); BN_clear_free(pub); goto err; } DH_free(s->s3->tmp.dh); s->s3->tmp.dh=NULL; if (dh_clnt) DH_free(dh_clnt); else BN_clear_free(pub); pub=NULL; s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key,p,i); OPENSSL_cleanse(p,i); if (dh_clnt) return 2; } else #endif #ifndef OPENSSL_NO_KRB5 if (alg_k & SSL_kKRB5) { krb5_error_code krb5rc; krb5_data enc_ticket; krb5_data authenticator; krb5_data enc_pms; KSSL_CTX *kssl_ctx = s->kssl_ctx; EVP_CIPHER_CTX ciph_ctx; const EVP_CIPHER *enc = NULL; unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char pms[SSL_MAX_MASTER_KEY_LENGTH + EVP_MAX_BLOCK_LENGTH]; int padl, outl; krb5_timestamp authtime = 0; krb5_ticket_times ttimes; EVP_CIPHER_CTX_init(&ciph_ctx); if (!kssl_ctx) kssl_ctx = kssl_ctx_new(); n2s(p,i); enc_ticket.length = i; if (n < (long)(enc_ticket.length + 6)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto err; } enc_ticket.data = (char *)p; p+=enc_ticket.length; n2s(p,i); authenticator.length = i; if (n < (long)(enc_ticket.length + authenticator.length + 6)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto err; } authenticator.data = (char *)p; p+=authenticator.length; n2s(p,i); enc_pms.length = i; enc_pms.data = (char *)p; p+=enc_pms.length; /* Note that the length is checked again below, ** after decryption */ if(enc_pms.length > sizeof pms) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto err; } if (n != (long)(enc_ticket.length + authenticator.length + enc_pms.length + 6)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto err; } if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes, &kssl_err)) != 0) { #ifdef KSSL_DEBUG fprintf(stderr,"kssl_sget_tkt rtn %d [%d]\n", krb5rc, kssl_err.reason); if (kssl_err.text) fprintf(stderr,"kssl_err text= %s\n", kssl_err.text); #endif /* KSSL_DEBUG */ SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason); goto err; } /* Note: no authenticator is not considered an error, ** but will return authtime == 0. */ if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator, &authtime, &kssl_err)) != 0) { #ifdef KSSL_DEBUG fprintf(stderr,"kssl_check_authent rtn %d [%d]\n", krb5rc, kssl_err.reason); if (kssl_err.text) fprintf(stderr,"kssl_err text= %s\n", kssl_err.text); #endif /* KSSL_DEBUG */ SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, kssl_err.reason); goto err; } if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc); goto err; } #ifdef KSSL_DEBUG kssl_ctx_show(kssl_ctx); #endif /* KSSL_DEBUG */ enc = kssl_map_enc(kssl_ctx->enctype); if (enc == NULL) goto err; memset(iv, 0, sizeof iv); /* per RFC 1510 */ if (!EVP_DecryptInit_ex(&ciph_ctx,enc,NULL,kssl_ctx->key,iv)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DECRYPTION_FAILED); goto err; } if (!EVP_DecryptUpdate(&ciph_ctx, pms,&outl, (unsigned char *)enc_pms.data, enc_pms.length)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DECRYPTION_FAILED); goto err; } if (outl > SSL_MAX_MASTER_KEY_LENGTH) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto err; } if (!EVP_DecryptFinal_ex(&ciph_ctx,&(pms[outl]),&padl)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DECRYPTION_FAILED); goto err; } outl += padl; if (outl > SSL_MAX_MASTER_KEY_LENGTH) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto err; } if (!((pms[0] == (s->client_version>>8)) && (pms[1] == (s->client_version & 0xff)))) { /* The premaster secret must contain the same version number as the * ClientHello to detect version rollback attacks (strangely, the * protocol does not offer such protection for DH ciphersuites). * However, buggy clients exist that send random bytes instead of * the protocol version. * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. * (Perhaps we should have a separate BUG value for the Kerberos cipher) */ if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_AD_DECODE_ERROR); goto err; } } EVP_CIPHER_CTX_cleanup(&ciph_ctx); s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key, pms, outl); if (kssl_ctx->client_princ) { size_t len = strlen(kssl_ctx->client_princ); if ( len < SSL_MAX_KRB5_PRINCIPAL_LENGTH ) { s->session->krb5_client_princ_len = len; memcpy(s->session->krb5_client_princ,kssl_ctx->client_princ,len); } } /*- Was doing kssl_ctx_free() here, * but it caused problems for apache. * kssl_ctx = kssl_ctx_free(kssl_ctx); * if (s->kssl_ctx) s->kssl_ctx = NULL; */ } else #endif /* OPENSSL_NO_KRB5 */ #ifndef OPENSSL_NO_ECDH if (alg_k & (SSL_kECDHE|SSL_kECDHr|SSL_kECDHe)) { int ret = 1; int field_size = 0; const EC_KEY *tkey; const EC_GROUP *group; const BIGNUM *priv_key; /* initialize structures for server's ECDH key pair */ if ((srvr_ecdh = EC_KEY_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } /* Let's get server private key and group information */ if (alg_k & (SSL_kECDHr|SSL_kECDHe)) { /* use the certificate */ tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec; } else { /* use the ephermeral values we saved when * generating the ServerKeyExchange msg. */ tkey = s->s3->tmp.ecdh; } group = EC_KEY_get0_group(tkey); priv_key = EC_KEY_get0_private_key(tkey); if (!EC_KEY_set_group(srvr_ecdh, group) || !EC_KEY_set_private_key(srvr_ecdh, priv_key)) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB); goto err; } /* Let's get client's public key */ if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } if (n == 0L) { /* Client Publickey was in Client Certificate */ if (alg_k & SSL_kECDHE) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY); goto f_err; } if (((clnt_pub_pkey=X509_get_pubkey(s->session->peer)) == NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) { /* XXX: For now, we do not support client * authentication using ECDH certificates * so this branch (n == 0L) of the code is * never executed. When that support is * added, we ought to ensure the key * received in the certificate is * authorized for key agreement. * ECDH_compute_key implicitly checks that * the two ECDH shares are for the same * group. */ al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNABLE_TO_DECODE_ECDH_CERTS); goto f_err; } if (EC_POINT_copy(clnt_ecpoint, EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec)) == 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB); goto err; } ret = 2; /* Skip certificate verify processing */ } else { /* Get client's public key from encoded point * in the ClientKeyExchange message. */ if ((bn_ctx = BN_CTX_new()) == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } /* Get encoded point length */ i = *p; p += 1; if (n != 1 + i) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB); goto err; } if (EC_POINT_oct2point(group, clnt_ecpoint, p, i, bn_ctx) == 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB); goto err; } /* p is pointing to somewhere in the buffer * currently, so set it to the start */ p=(unsigned char *)s->init_buf->data; } /* Compute the shared pre-master secret */ field_size = EC_GROUP_get_degree(group); if (field_size <= 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } i = ECDH_compute_key(p, (field_size+7)/8, clnt_ecpoint, srvr_ecdh, NULL); if (i <= 0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB); goto err; } EVP_PKEY_free(clnt_pub_pkey); EC_POINT_free(clnt_ecpoint); EC_KEY_free(srvr_ecdh); BN_CTX_free(bn_ctx); EC_KEY_free(s->s3->tmp.ecdh); s->s3->tmp.ecdh = NULL; /* Compute the master secret */ s->session->master_key_length = s->method->ssl3_enc-> \ generate_master_secret(s, s->session->master_key, p, i); OPENSSL_cleanse(p, i); return (ret); } else #endif #ifndef OPENSSL_NO_PSK if (alg_k & SSL_kPSK) { unsigned char *t = NULL; unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4]; unsigned int pre_ms_len = 0, psk_len = 0; int psk_err = 1; char tmp_id[PSK_MAX_IDENTITY_LEN+1]; al=SSL_AD_HANDSHAKE_FAILURE; n2s(p,i); if (n != i+2) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH); goto psk_err; } if (i > PSK_MAX_IDENTITY_LEN) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_DATA_LENGTH_TOO_LONG); goto psk_err; } if (s->psk_server_callback == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_PSK_NO_SERVER_CB); goto psk_err; } /* Create guaranteed NULL-terminated identity * string for the callback */ memcpy(tmp_id, p, i); memset(tmp_id+i, 0, PSK_MAX_IDENTITY_LEN+1-i); psk_len = s->psk_server_callback(s, tmp_id, psk_or_pre_ms, sizeof(psk_or_pre_ms)); OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN+1); if (psk_len > PSK_MAX_PSK_LEN) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR); goto psk_err; } else if (psk_len == 0) { /* PSK related to the given identity not found */ SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_PSK_IDENTITY_NOT_FOUND); al=SSL_AD_UNKNOWN_PSK_IDENTITY; goto psk_err; } /* create PSK pre_master_secret */ pre_ms_len=2+psk_len+2+psk_len; t = psk_or_pre_ms; memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len); s2n(psk_len, t); memset(t, 0, psk_len); t+=psk_len; s2n(psk_len, t); if (s->session->psk_identity != NULL) OPENSSL_free(s->session->psk_identity); s->session->psk_identity = BUF_strdup((char *)p); if (s->session->psk_identity == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto psk_err; } if (s->session->psk_identity_hint != NULL) OPENSSL_free(s->session->psk_identity_hint); s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint); if (s->ctx->psk_identity_hint != NULL && s->session->psk_identity_hint == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto psk_err; } s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key, psk_or_pre_ms, pre_ms_len); psk_err = 0; psk_err: OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms)); if (psk_err != 0) goto f_err; } else #endif #ifndef OPENSSL_NO_SRP if (alg_k & SSL_kSRP) { int param_len; n2s(p,i); param_len=i+2; if (param_len > n) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_SRP_A_LENGTH); goto f_err; } if (!(s->srp_ctx.A=BN_bin2bn(p,i,NULL))) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_BN_LIB); goto err; } if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) { al=SSL_AD_ILLEGAL_PARAMETER; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS); goto f_err; } if (s->session->srp_username != NULL) OPENSSL_free(s->session->srp_username); s->session->srp_username = BUF_strdup(s->srp_ctx.login); if (s->session->srp_username == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); goto err; } if ((s->session->master_key_length = SRP_generate_server_master_secret(s,s->session->master_key))<0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR); goto err; } p+=i; } else #endif /* OPENSSL_NO_SRP */ if (alg_k & SSL_kGOST) { int ret = 0; EVP_PKEY_CTX *pkey_ctx; EVP_PKEY *client_pub_pkey = NULL, *pk = NULL; unsigned char premaster_secret[32], *start; size_t outlen=32, inlen; unsigned long alg_a; int Ttag, Tclass; long Tlen; /* Get our certificate private key*/ alg_a = s->s3->tmp.new_cipher->algorithm_auth; if (alg_a & SSL_aGOST94) pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey; else if (alg_a & SSL_aGOST01) pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey; pkey_ctx = EVP_PKEY_CTX_new(pk,NULL); EVP_PKEY_decrypt_init(pkey_ctx); /* If client certificate is present and is of the same type, maybe * use it for key exchange. Don't mind errors from * EVP_PKEY_derive_set_peer, because it is completely valid to use * a client certificate for authorization only. */ client_pub_pkey = X509_get_pubkey(s->session->peer); if (client_pub_pkey) { if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0) ERR_clear_error(); } /* Decrypt session key */ if (ASN1_get_object((const unsigned char **)&p, &Tlen, &Ttag, &Tclass, n) != V_ASN1_CONSTRUCTED || Ttag != V_ASN1_SEQUENCE || Tclass != V_ASN1_UNIVERSAL) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED); goto gerr; } start = p; inlen = Tlen; if (EVP_PKEY_decrypt(pkey_ctx,premaster_secret,&outlen,start,inlen) <=0) { SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED); goto gerr; } /* Generate master secret */ s->session->master_key_length= s->method->ssl3_enc->generate_master_secret(s, s->session->master_key,premaster_secret,32); /* Check if pubkey from client certificate was used */ if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0) ret = 2; else ret = 1; gerr: EVP_PKEY_free(client_pub_pkey); EVP_PKEY_CTX_free(pkey_ctx); if (ret) return ret; else goto err; } else { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE); goto f_err; } return(1); f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) || defined(OPENSSL_NO_SRP) err: #endif #ifndef OPENSSL_NO_ECDH EVP_PKEY_free(clnt_pub_pkey); EC_POINT_free(clnt_ecpoint); if (srvr_ecdh != NULL) EC_KEY_free(srvr_ecdh); BN_CTX_free(bn_ctx); #endif return(-1); } int ssl3_get_cert_verify(SSL *s) { EVP_PKEY *pkey=NULL; unsigned char *p; int al,ok,ret=0; long n; int type=0,i,j; X509 *peer; const EVP_MD *md = NULL; EVP_MD_CTX mctx; EVP_MD_CTX_init(&mctx); n=s->method->ssl_get_message(s, SSL3_ST_SR_CERT_VRFY_A, SSL3_ST_SR_CERT_VRFY_B, -1, SSL3_RT_MAX_PLAIN_LENGTH, &ok); if (!ok) return((int)n); if (s->session->peer != NULL) { peer=s->session->peer; pkey=X509_get_pubkey(peer); type=X509_certificate_type(peer,pkey); } else { peer=NULL; pkey=NULL; } if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY) { s->s3->tmp.reuse_message=1; if (peer != NULL) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE); goto f_err; } ret=1; goto end; } if (peer == NULL) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED); al=SSL_AD_UNEXPECTED_MESSAGE; goto f_err; } if (!(type & EVP_PKT_SIGN)) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE); al=SSL_AD_ILLEGAL_PARAMETER; goto f_err; } if (s->s3->change_cipher_spec) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY); al=SSL_AD_UNEXPECTED_MESSAGE; goto f_err; } /* we now have a signature that we need to verify */ p=(unsigned char *)s->init_msg; /* Check for broken implementations of GOST ciphersuites */ /* If key is GOST and n is exactly 64, it is bare * signature without length field */ if (n==64 && (pkey->type==NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001) ) { i=64; } else { if (SSL_USE_SIGALGS(s)) { int rv = tls12_check_peer_sigalg(&md, s, p, pkey); if (rv == -1) { al = SSL_AD_INTERNAL_ERROR; goto f_err; } else if (rv == 0) { al = SSL_AD_DECODE_ERROR; goto f_err; } #ifdef SSL_DEBUG fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md)); #endif p += 2; n -= 2; } n2s(p,i); n-=2; if (i > n) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH); al=SSL_AD_DECODE_ERROR; goto f_err; } } j=EVP_PKEY_size(pkey); if ((i > j) || (n > j) || (n <= 0)) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE); al=SSL_AD_DECODE_ERROR; goto f_err; } if (SSL_USE_SIGALGS(s)) { long hdatalen = 0; void *hdata; hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata); if (hdatalen <= 0) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR); al=SSL_AD_INTERNAL_ERROR; goto f_err; } #ifdef SSL_DEBUG fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n", EVP_MD_name(md)); #endif if (!EVP_VerifyInit_ex(&mctx, md, NULL) || !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB); al=SSL_AD_INTERNAL_ERROR; goto f_err; } if (EVP_VerifyFinal(&mctx, p , i, pkey) <= 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_SIGNATURE); goto f_err; } } else #ifndef OPENSSL_NO_RSA if (pkey->type == EVP_PKEY_RSA) { i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md, MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i, pkey->pkey.rsa); if (i < 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT); goto f_err; } if (i == 0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE); goto f_err; } } else #endif #ifndef OPENSSL_NO_DSA if (pkey->type == EVP_PKEY_DSA) { j=DSA_verify(pkey->save_type, &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]), SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa); if (j <= 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE); goto f_err; } } else #endif #ifndef OPENSSL_NO_ECDSA if (pkey->type == EVP_PKEY_EC) { j=ECDSA_verify(pkey->save_type, &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]), SHA_DIGEST_LENGTH,p,i,pkey->pkey.ec); if (j <= 0) { /* bad signature */ al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE); goto f_err; } } else #endif if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001) { unsigned char signature[64]; int idx; EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey,NULL); EVP_PKEY_verify_init(pctx); if (i!=64) { fprintf(stderr,"GOST signature length is %d",i); } for (idx=0;idx<64;idx++) { signature[63-idx]=p[idx]; } j=EVP_PKEY_verify(pctx,signature,64,s->s3->tmp.cert_verify_md,32); EVP_PKEY_CTX_free(pctx); if (j<=0) { al=SSL_AD_DECRYPT_ERROR; SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE); goto f_err; } } else { SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR); al=SSL_AD_UNSUPPORTED_CERTIFICATE; goto f_err; } ret=1; if (0) { f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); } end: if (s->s3->handshake_buffer) { BIO_free(s->s3->handshake_buffer); s->s3->handshake_buffer = NULL; s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE; } EVP_MD_CTX_cleanup(&mctx); EVP_PKEY_free(pkey); return(ret); } int ssl3_get_client_certificate(SSL *s) { int i,ok,al,ret= -1; X509 *x=NULL; unsigned long l,nc,llen,n; const unsigned char *p,*q; unsigned char *d; STACK_OF(X509) *sk=NULL; n=s->method->ssl_get_message(s, SSL3_ST_SR_CERT_A, SSL3_ST_SR_CERT_B, -1, s->max_cert_list, &ok); if (!ok) return((int)n); if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) { if ( (s->verify_mode & SSL_VERIFY_PEER) && (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) { SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE); al=SSL_AD_HANDSHAKE_FAILURE; goto f_err; } /* If tls asked for a client cert, the client must return a 0 list */ if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request) { SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST); al=SSL_AD_UNEXPECTED_MESSAGE; goto f_err; } s->s3->tmp.reuse_message=1; return(1); } if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) { al=SSL_AD_UNEXPECTED_MESSAGE; SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_WRONG_MESSAGE_TYPE); goto f_err; } p=d=(unsigned char *)s->init_msg; if ((sk=sk_X509_new_null()) == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE); goto err; } n2l3(p,llen); if (llen+3 != n) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_LENGTH_MISMATCH); goto f_err; } for (nc=0; nc<llen; ) { n2l3(p,l); if ((l+nc+3) > llen) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH); goto f_err; } q=p; x=d2i_X509(NULL,&p,l); if (x == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_ASN1_LIB); goto err; } if (p != (q+l)) { al=SSL_AD_DECODE_ERROR; SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH); goto f_err; } if (!sk_X509_push(sk,x)) { SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE); goto err; } x=NULL; nc+=l+3; } if (sk_X509_num(sk) <= 0) { /* TLS does not mind 0 certs returned */ if (s->version == SSL3_VERSION) { al=SSL_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATES_RETURNED); goto f_err; } /* Fail for TLS only if we required a certificate */ else if ((s->verify_mode & SSL_VERIFY_PEER) && (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) { SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE); al=SSL_AD_HANDSHAKE_FAILURE; goto f_err; } /* No client certificate so digest cached records */ if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s)) { al=SSL_AD_INTERNAL_ERROR; goto f_err; } } else { EVP_PKEY *pkey; i=ssl_verify_cert_chain(s,sk); if (i <= 0) { al=ssl_verify_alarm_type(s->verify_result); SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED); goto f_err; } if (i > 1) { SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, i); al = SSL_AD_HANDSHAKE_FAILURE; goto f_err; } pkey = X509_get_pubkey(sk_X509_value(sk, 0)); if (pkey == NULL) { al=SSL3_AD_HANDSHAKE_FAILURE; SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_UNKNOWN_CERTIFICATE_TYPE); goto f_err; } EVP_PKEY_free(pkey); } if (s->session->peer != NULL) /* This should not be needed */ X509_free(s->session->peer); s->session->peer=sk_X509_shift(sk); s->session->verify_result = s->verify_result; /* With the current implementation, sess_cert will always be NULL * when we arrive here. */ if (s->session->sess_cert == NULL) { s->session->sess_cert = ssl_sess_cert_new(); if (s->session->sess_cert == NULL) { SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE); goto err; } } if (s->session->sess_cert->cert_chain != NULL) sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free); s->session->sess_cert->cert_chain=sk; /* Inconsistency alert: cert_chain does *not* include the * peer's own certificate, while we do include it in s3_clnt.c */ sk=NULL; ret=1; if (0) { f_err: ssl3_send_alert(s,SSL3_AL_FATAL,al); } err: if (x != NULL) X509_free(x); if (sk != NULL) sk_X509_pop_free(sk,X509_free); return(ret); } int ssl3_send_server_certificate(SSL *s) { CERT_PKEY *cpk; if (s->state == SSL3_ST_SW_CERT_A) { cpk=ssl_get_server_send_pkey(s); if (cpk == NULL) { /* VRS: allow null cert if auth == KRB5 */ if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5)) { SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR); return(0); } } if (!ssl3_output_cert_chain(s,cpk)) { SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR); return(0); } s->state=SSL3_ST_SW_CERT_B; } /* SSL3_ST_SW_CERT_B */ return ssl_do_write(s); } #ifndef OPENSSL_NO_TLSEXT /* send a new session ticket (not necessarily for a new session) */ int ssl3_send_newsession_ticket(SSL *s) { if (s->state == SSL3_ST_SW_SESSION_TICKET_A) { unsigned char *p, *senc, *macstart; const unsigned char *const_p; int len, slen_full, slen; SSL_SESSION *sess; unsigned int hlen; EVP_CIPHER_CTX ctx; HMAC_CTX hctx; SSL_CTX *tctx = s->initial_ctx; unsigned char iv[EVP_MAX_IV_LENGTH]; unsigned char key_name[16]; /* get session encoding length */ slen_full = i2d_SSL_SESSION(s->session, NULL); /* Some length values are 16 bits, so forget it if session is * too long */ if (slen_full > 0xFF00) return -1; senc = OPENSSL_malloc(slen_full); if (!senc) return -1; p = senc; i2d_SSL_SESSION(s->session, &p); /* create a fresh copy (not shared with other threads) to clean up */ const_p = senc; sess = d2i_SSL_SESSION(NULL, &const_p, slen_full); if (sess == NULL) { OPENSSL_free(senc); return -1; } sess->session_id_length = 0; /* ID is irrelevant for the ticket */ slen = i2d_SSL_SESSION(sess, NULL); if (slen > slen_full) /* shouldn't ever happen */ { OPENSSL_free(senc); return -1; } p = senc; i2d_SSL_SESSION(sess, &p); SSL_SESSION_free(sess); /*- * Grow buffer if need be: the length calculation is as * follows handshake_header_length + * 4 (ticket lifetime hint) + 2 (ticket length) + * 16 (key name) + max_iv_len (iv length) + * session_length + max_enc_block_size (max encrypted session * length) + max_md_size (HMAC). */ if (!BUF_MEM_grow(s->init_buf, SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen)) return -1; p = ssl_handshake_start(s); EVP_CIPHER_CTX_init(&ctx); HMAC_CTX_init(&hctx); /* Initialize HMAC and cipher contexts. If callback present * it does all the work otherwise use generated values * from parent ctx. */ if (tctx->tlsext_ticket_key_cb) { if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx, &hctx, 1) < 0) { OPENSSL_free(senc); return -1; } } else { RAND_pseudo_bytes(iv, 16); EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, tctx->tlsext_tick_aes_key, iv); HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16, tlsext_tick_md(), NULL); memcpy(key_name, tctx->tlsext_tick_key_name, 16); } /* Ticket lifetime hint (advisory only): * We leave this unspecified for resumed session (for simplicity), * and guess that tickets for new sessions will live as long * as their sessions. */ l2n(s->hit ? 0 : s->session->timeout, p); /* Skip ticket length for now */ p += 2; /* Output key name */ macstart = p; memcpy(p, key_name, 16); p += 16; /* output IV */ memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx)); p += EVP_CIPHER_CTX_iv_length(&ctx); /* Encrypt session data */ EVP_EncryptUpdate(&ctx, p, &len, senc, slen); p += len; EVP_EncryptFinal(&ctx, p, &len); p += len; EVP_CIPHER_CTX_cleanup(&ctx); HMAC_Update(&hctx, macstart, p - macstart); HMAC_Final(&hctx, p, &hlen); HMAC_CTX_cleanup(&hctx); p += hlen; /* Now write out lengths: p points to end of data written */ /* Total length */ len = p - ssl_handshake_start(s); ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len); /* Skip ticket lifetime hint */ p = ssl_handshake_start(s) + 4; s2n(len - 6, p); s->state=SSL3_ST_SW_SESSION_TICKET_B; OPENSSL_free(senc); } /* SSL3_ST_SW_SESSION_TICKET_B */ return ssl_do_write(s); } int ssl3_send_cert_status(SSL *s) { if (s->state == SSL3_ST_SW_CERT_STATUS_A) { unsigned char *p; /*- * Grow buffer if need be: the length calculation is as * follows 1 (message type) + 3 (message length) + * 1 (ocsp response type) + 3 (ocsp response length) * + (ocsp response) */ if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen)) return -1; p=(unsigned char *)s->init_buf->data; /* do the header */ *(p++)=SSL3_MT_CERTIFICATE_STATUS; /* message length */ l2n3(s->tlsext_ocsp_resplen + 4, p); /* status type */ *(p++)= s->tlsext_status_type; /* length of OCSP response */ l2n3(s->tlsext_ocsp_resplen, p); /* actual response */ memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen); /* number of bytes to write */ s->init_num = 8 + s->tlsext_ocsp_resplen; s->state=SSL3_ST_SW_CERT_STATUS_B; s->init_off = 0; } /* SSL3_ST_SW_CERT_STATUS_B */ return(ssl3_do_write(s,SSL3_RT_HANDSHAKE)); } # ifndef OPENSSL_NO_NEXTPROTONEG /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It * sets the next_proto member in s if found */ int ssl3_get_next_proto(SSL *s) { int ok; int proto_len, padding_len; long n; const unsigned char *p; /* Clients cannot send a NextProtocol message if we didn't see the * extension in their ClientHello */ if (!s->s3->next_proto_neg_seen) { SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION); return -1; } n=s->method->ssl_get_message(s, SSL3_ST_SR_NEXT_PROTO_A, SSL3_ST_SR_NEXT_PROTO_B, SSL3_MT_NEXT_PROTO, 514, /* See the payload format below */ &ok); if (!ok) return((int)n); /* s->state doesn't reflect whether ChangeCipherSpec has been received * in this handshake, but s->s3->change_cipher_spec does (will be reset * by ssl3_get_finished). */ if (!s->s3->change_cipher_spec) { SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS); return -1; } if (n < 2) return 0; /* The body must be > 1 bytes long */ p=(unsigned char *)s->init_msg; /*- * The payload looks like: * uint8 proto_len; * uint8 proto[proto_len]; * uint8 padding_len; * uint8 padding[padding_len]; */ proto_len = p[0]; if (proto_len + 2 > s->init_num) return 0; padding_len = p[proto_len + 1]; if (proto_len + padding_len + 2 != s->init_num) return 0; s->next_proto_negotiated = OPENSSL_malloc(proto_len); if (!s->next_proto_negotiated) { SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,ERR_R_MALLOC_FAILURE); return 0; } memcpy(s->next_proto_negotiated, p + 1, proto_len); s->next_proto_negotiated_len = proto_len; return 1; } # endif #endif
./CrossVul/dataset_final_sorted/CWE-310/c/good_1446_0
crossvul-cpp_data_good_1210_0
/* * This file is part of the KeepKey project. * * Copyright (C) 2015 KeepKey LLC * * 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 3 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, see <http://www.gnu.org/licenses/>. */ #include "keepkey/board/keepkey_board.h" #include "keepkey/board/layout.h" #include "keepkey/board/messages.h" #include "trezor/crypto/bip39.h" #include "trezor/crypto/memzero.h" #include "keepkey/firmware/app_layout.h" #include "keepkey/board/confirm_sm.h" #include "keepkey/firmware/fsm.h" #include "keepkey/firmware/home_sm.h" #include "keepkey/firmware/pin_sm.h" #include "keepkey/firmware/recovery_cipher.h" #include "keepkey/firmware/storage.h" #include "keepkey/rand/rng.h" #include <string.h> #include <stdio.h> #define MAX_UNCYPHERED_WORDS (3) static bool recovery_started = false; static bool enforce_wordlist; static bool dry_run; static bool awaiting_character; static CONFIDENTIAL char mnemonic[MNEMONIC_BUF]; static char english_alphabet[ENGLISH_ALPHABET_BUF] = "abcdefghijklmnopqrstuvwxyz"; static CONFIDENTIAL char cipher[ENGLISH_ALPHABET_BUF]; #if DEBUG_LINK static char auto_completed_word[CURRENT_WORD_BUF]; #endif static void format_current_word(char *current_word, bool auto_completed); static uint32_t get_current_word_pos(void); static void get_current_word(char *current_word); static void recovery_abort(void) { if (!dry_run) { storage_reset(); } recovery_started = false; awaiting_character = false; memzero(mnemonic, sizeof(mnemonic)); memzero(cipher, sizeof(cipher)); } /// Formats the passed word to show position in mnemonic as well as characters /// left. /// /// \param current_word[in] The string to format. /// \param auto_completed[in] Whether to format as an auto completed word. static void format_current_word(char *current_word, bool auto_completed) { static char CONFIDENTIAL temp_word[CURRENT_WORD_BUF]; uint32_t word_num = get_current_word_pos() + 1; snprintf(temp_word, CURRENT_WORD_BUF, "%" PRIu32 ".%s", word_num, current_word); /* Pad with dashes */ size_t pos_len = strlen(current_word); if (pos_len < 4) { for (size_t i = 0; i < 4 - pos_len; i++) { strlcat(temp_word, "-", CURRENT_WORD_BUF); } } /* Mark as auto completed */ if(auto_completed) { temp_word[strlen(temp_word) + 1] = '\0'; temp_word[strlen(temp_word)] = '~'; } strlcpy(current_word, temp_word, CURRENT_WORD_BUF); memzero(temp_word, sizeof(temp_word)); } /* * get_current_word_pos() - Returns the current word position in the mnemonic * * INPUT * none * OUTPUT * position in mnemonic */ static uint32_t get_current_word_pos(void) { char *pos_num = strchr(mnemonic, ' '); uint32_t word_pos = 0; while(pos_num != NULL) { word_pos++; pos_num = strchr(++pos_num, ' '); } return word_pos; } /// \returns the current word being entered by parsing the mnemonic thus far /// \param current_word[out] Array to populate with current word. static void get_current_word(char *current_word) { char *pos = strrchr(mnemonic, ' '); if(pos) { pos++; strlcpy(current_word, pos, CURRENT_WORD_BUF); } else { strlcpy(current_word, mnemonic, CURRENT_WORD_BUF); } } bool exact_str_match(const char *str1, const char *str2, uint32_t len) { volatile uint32_t match = 0; // Access through volatile ptrs to prevent compiler optimizations that // might leak timing information. const char volatile * volatile str1_v = str1; const char volatile * volatile str2_v = str2; for(uint32_t i = 0; i < len && i < CURRENT_WORD_BUF; i++) { if(str1_v[i] == str2_v[i]) { match++; } else { match--; } } return match == len; } bool attempt_auto_complete(char *partial_word) { // Do lookup through volatile pointers to prevent the compiler from // optimizing this loop into something that can leak timing information. const char *const volatile * volatile wordlist = (const char *const volatile *)mnemonic_wordlist(); uint32_t partial_word_len = strlen(partial_word), match = 0, found = 0; bool precise_match = false; static uint16_t CONFIDENTIAL permute[2049]; for (int i = 0; i < 2049; i++) { permute[i] = i; } random_permute_u16(permute, 2048); // We don't want the compiler to see through the fact that we're randomly // permuting the order of iteration of the next few loops, in case it's // smart enough to see through that and remove the permutation, so we tell // it we've touched all of memory with some inline asm, and scare it off. // This acts as an optimization barrier. asm volatile ("" ::: "memory"); // Look for precise matches first (including null termination) for (uint32_t volatile i = 0; wordlist[permute[i]] != 0; i++) { if (exact_str_match(partial_word, wordlist[permute[i]], partial_word_len + 1)) { strlcpy(partial_word, wordlist[permute[i]], CURRENT_WORD_BUF); precise_match = true; } } random_permute_u16(permute, 2048); asm volatile ("" ::: "memory"); // Followed by partial matches (ignoring null termination) for (uint32_t volatile i = 0; wordlist[permute[i]] != 0; i++) { if (exact_str_match(partial_word, wordlist[permute[i]], partial_word_len)) { match++; found = i; } } if (precise_match) { memzero(permute, sizeof(permute)); return true; } /* Autocomplete if we can */ if (match == 1) { strlcpy(partial_word, wordlist[permute[found]], CURRENT_WORD_BUF); memzero(permute, sizeof(permute)); return true; } memzero(permute, sizeof(permute)); return false; } /* * recovery_cipher_init() - Display standard notification on LCD screen * * INPUT * - passphrase_protection: whether to use passphrase protection * - pin_protection: whether to use pin protection * - language: language for device * - label: label for device * - _enforce_wordlist: whether to enforce bip 39 word list * OUTPUT * none */ void recovery_cipher_init(bool passphrase_protection, bool pin_protection, const char *language, const char *label, bool _enforce_wordlist, uint32_t _auto_lock_delay_ms, uint32_t _u2f_counter, bool _dry_run) { enforce_wordlist = _enforce_wordlist; dry_run = _dry_run; if (!dry_run) { if (pin_protection) { if (!change_pin()) { recovery_abort(); fsm_sendFailure(FailureType_Failure_ActionCancelled, "PINs do not match"); layoutHome(); return; } } else { storage_setPin(""); } storage_setPassphraseProtected(passphrase_protection); storage_setLanguage(language); storage_setLabel(label); storage_setAutoLockDelayMs(_auto_lock_delay_ms); storage_setU2FCounter(_u2f_counter); } else if (!pin_protect("Enter Your PIN")) { layoutHome(); return; } if (!confirm(ButtonRequestType_ButtonRequest_Other, dry_run ? "Recovery Dry Run" : "Recovery", "When entering your recovery seed, use the substitution cipher " "and check that each word shows up correctly on the screen.")) { fsm_sendFailure(FailureType_Failure_ActionCancelled, "Recovery cancelled"); if (!dry_run) storage_reset(); layoutHome(); return; } /* Clear mnemonic */ memset(mnemonic, 0, sizeof(mnemonic) / sizeof(char)); /* Set to recovery cipher mode and generate and show next cipher */ awaiting_character = true; recovery_started = true; next_character(); } /* * next_character() - Randomizes cipher and displays it for next character entry * * INPUT * none * OUTPUT * none */ void next_character(void) { if (!recovery_started) { recovery_abort(); fsm_sendFailure(FailureType_Failure_UnexpectedMessage, "Not in Recovery mode"); layoutHome(); return; } /* Scramble cipher */ strlcpy(cipher, english_alphabet, ENGLISH_ALPHABET_BUF); random_permute_char(cipher, strlen(cipher)); static char CONFIDENTIAL current_word[CURRENT_WORD_BUF]; get_current_word(current_word); /* Words should never be longer than 4 characters */ if (strlen(current_word) > 4) { memzero(current_word, sizeof(current_word)); recovery_abort(); fsm_sendFailure(FailureType_Failure_SyntaxError, "Words were not entered correctly. Make sure you are using the substition cipher."); layoutHome(); return; } CharacterRequest resp; memset(&resp, 0, sizeof(CharacterRequest)); resp.word_pos = get_current_word_pos(); resp.character_pos = strlen(current_word); msg_write(MessageType_MessageType_CharacterRequest, &resp); /* Attempt to auto complete if we have at least 3 characters */ bool auto_completed = false; if (strlen(current_word) >= 3) { auto_completed = attempt_auto_complete(current_word); } #if DEBUG_LINK if (auto_completed) { strlcpy(auto_completed_word, current_word, CURRENT_WORD_BUF); } else { auto_completed_word[0] = '\0'; } #endif /* Format current word and display it along with cipher */ format_current_word(current_word, auto_completed); /* Show cipher and partial word */ layout_cipher(current_word, cipher); memzero(current_word, sizeof(current_word)); } /* * recovery_character() - Decodes character received from host * * INPUT * - character: string to decode * OUTPUT * none */ void recovery_character(const char *character) { if (!awaiting_character || !recovery_started) { recovery_abort(); fsm_sendFailure(FailureType_Failure_UnexpectedMessage, "Not in Recovery mode"); layoutHome(); return; } if (strlen(mnemonic) + 1 > MNEMONIC_BUF - 1) { recovery_abort(); fsm_sendFailure(FailureType_Failure_UnexpectedMessage, "Too many characters attempted during recovery"); layoutHome(); return; } char *pos = strchr(cipher, character[0]); // If not a space and not a legitmate cipher character, send failure. if (character[0] != ' ' && pos == NULL) { recovery_abort(); fsm_sendFailure(FailureType_Failure_SyntaxError, "Character must be from a to z"); layoutHome(); return; } // Count of words we think the user has entered without using the cipher: static int uncyphered_word_count = 0; static bool definitely_using_cipher = false; static CONFIDENTIAL char coded_word[12]; static CONFIDENTIAL char decoded_word[12]; if (!mnemonic[0]) { uncyphered_word_count = 0; definitely_using_cipher = false; memzero(coded_word, sizeof(coded_word)); memzero(decoded_word, sizeof(decoded_word)); } char decoded_character[2] = " "; if (character[0] != ' ') { // Decode character using cipher if not space decoded_character[0] = english_alphabet[(int)(pos - cipher)]; strlcat(coded_word, character, sizeof(coded_word)); strlcat(decoded_word, decoded_character, sizeof(decoded_word)); if (enforce_wordlist && 4 <= strlen(coded_word)) { // Check & bail if the user is entering their seed without using the // cipher. Note that for each word, this can give false positives about // ~0.4% of the time (2048/26^4). bool maybe_not_using_cipher = attempt_auto_complete(coded_word); bool maybe_using_cipher = attempt_auto_complete(decoded_word); if (!maybe_not_using_cipher && maybe_using_cipher) { // Decrease the overall false positive rate by detecting that a // user has entered a word which is definitely using the // cipher. definitely_using_cipher = true; } else if (maybe_not_using_cipher && !definitely_using_cipher && MAX_UNCYPHERED_WORDS < uncyphered_word_count++) { recovery_abort(); fsm_sendFailure(FailureType_Failure_SyntaxError, "Words were not entered correctly. Make sure you are using the substition cipher."); layoutHome(); return; } } } else { memzero(coded_word, sizeof(coded_word)); memzero(decoded_word, sizeof(decoded_word)); } // concat to mnemonic strlcat(mnemonic, decoded_character, MNEMONIC_BUF); next_character(); } /* * recovery_delete_character() - Deletes previously received recovery character * * INPUT * none * OUTPUT * none */ void recovery_delete_character(void) { if (!recovery_started) { recovery_abort(); fsm_sendFailure(FailureType_Failure_UnexpectedMessage, "Not in Recovery mode"); layoutHome(); return; } if(strlen(mnemonic) > 0) { mnemonic[strlen(mnemonic) - 1] = '\0'; } next_character(); } /* * recovery_cipher_finalize() - Finished mnemonic entry * * INPUT * none * OUTPUT * none */ void recovery_cipher_finalize(void) { if (!recovery_started) { recovery_abort(); fsm_sendFailure(FailureType_Failure_UnexpectedMessage, "Not in Recovery mode"); layoutHome(); return; } static char CONFIDENTIAL new_mnemonic[MNEMONIC_BUF] = ""; static char CONFIDENTIAL temp_word[CURRENT_WORD_BUF]; volatile bool auto_completed = true; /* Attempt to autocomplete each word */ char *tok = strtok(mnemonic, " "); while(tok) { strlcpy(temp_word, tok, CURRENT_WORD_BUF); auto_completed &= attempt_auto_complete(temp_word); strlcat(new_mnemonic, temp_word, MNEMONIC_BUF); strlcat(new_mnemonic, " ", MNEMONIC_BUF); tok = strtok(NULL, " "); } memzero(temp_word, sizeof(temp_word)); if (!auto_completed && !enforce_wordlist) { if (!dry_run) { storage_reset(); } fsm_sendFailure(FailureType_Failure_SyntaxError, "Words were not entered correctly. Make sure you are using the substition cipher."); awaiting_character = false; layoutHome(); return; } /* Truncate additional space at the end */ new_mnemonic[MAX(0u, strnlen(new_mnemonic, sizeof(new_mnemonic)) - 1)] = '\0'; if (!dry_run && (!enforce_wordlist || mnemonic_check(new_mnemonic))) { storage_setMnemonic(new_mnemonic); memzero(new_mnemonic, sizeof(new_mnemonic)); if (!enforce_wordlist) { // not enforcing => mark storage as imported storage_setImported(true); } storage_commit(); fsm_sendSuccess("Device recovered"); } else if (dry_run) { bool match = storage_isInitialized() && storage_containsMnemonic(new_mnemonic); if (match) { review(ButtonRequestType_ButtonRequest_Other, "Recovery Dry Run", "The seed is valid and MATCHES the one in the device."); fsm_sendSuccess("The seed is valid and matches the one in the device."); } else if (mnemonic_check(new_mnemonic)) { review(ButtonRequestType_ButtonRequest_Other, "Recovery Dry Run", "The seed is valid, but DOES NOT MATCH the one in the device."); fsm_sendFailure(FailureType_Failure_Other, "The seed is valid, but does not match the one in the device."); } else { review(ButtonRequestType_ButtonRequest_Other, "Recovery Dry Run", "The seed is INVALID, and DOES NOT MATCH the one in the device."); fsm_sendFailure(FailureType_Failure_Other, "The seed is invalid, and does not match the one in the device."); } memzero(new_mnemonic, sizeof(new_mnemonic)); } else { session_clear(true); fsm_sendFailure(FailureType_Failure_SyntaxError, "Invalid mnemonic, are words in correct order?"); recovery_abort(); } memzero(new_mnemonic, sizeof(new_mnemonic)); awaiting_character = false; memzero(mnemonic, sizeof(mnemonic)); memzero(cipher, sizeof(cipher)); layoutHome(); } /* * recovery_cipher_abort() - Aborts recovery cipher process * * INPUT * none * OUTPUT * true/false of whether recovery was aborted */ bool recovery_cipher_abort(void) { recovery_started = false; if (awaiting_character) { awaiting_character = false; return true; } return false; } #if DEBUG_LINK /* * recovery_get_cipher() - Gets current cipher being show on display * * INPUT * none * OUTPUT * current cipher */ const char *recovery_get_cipher(void) { return cipher; } /* * recovery_get_auto_completed_word() - Gets last auto completed word * * INPUT * none * OUTPUT * last auto completed word */ const char *recovery_get_auto_completed_word(void) { return auto_completed_word; } #endif
./CrossVul/dataset_final_sorted/CWE-354/c/good_1210_0
crossvul-cpp_data_bad_1210_0
/* * This file is part of the KeepKey project. * * Copyright (C) 2015 KeepKey LLC * * 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 3 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, see <http://www.gnu.org/licenses/>. */ #include "keepkey/board/keepkey_board.h" #include "keepkey/board/layout.h" #include "keepkey/board/messages.h" #include "trezor/crypto/bip39.h" #include "trezor/crypto/memzero.h" #include "keepkey/firmware/app_layout.h" #include "keepkey/board/confirm_sm.h" #include "keepkey/firmware/fsm.h" #include "keepkey/firmware/home_sm.h" #include "keepkey/firmware/pin_sm.h" #include "keepkey/firmware/recovery_cipher.h" #include "keepkey/firmware/storage.h" #include "keepkey/rand/rng.h" #include <string.h> #include <stdio.h> #define MAX_UNCYPHERED_WORDS (3) static bool enforce_wordlist; static bool dry_run; static bool awaiting_character; static CONFIDENTIAL char mnemonic[MNEMONIC_BUF]; static char english_alphabet[ENGLISH_ALPHABET_BUF] = "abcdefghijklmnopqrstuvwxyz"; static CONFIDENTIAL char cipher[ENGLISH_ALPHABET_BUF]; #if DEBUG_LINK static char auto_completed_word[CURRENT_WORD_BUF]; #endif static void format_current_word(char *current_word, bool auto_completed); static uint32_t get_current_word_pos(void); static void get_current_word(char *current_word); static void recovery_abort(void) { if (!dry_run) { storage_reset(); } awaiting_character = false; memzero(mnemonic, sizeof(mnemonic)); memzero(cipher, sizeof(cipher)); } /// Formats the passed word to show position in mnemonic as well as characters /// left. /// /// \param current_word[in] The string to format. /// \param auto_completed[in] Whether to format as an auto completed word. static void format_current_word(char *current_word, bool auto_completed) { static char CONFIDENTIAL temp_word[CURRENT_WORD_BUF]; uint32_t word_num = get_current_word_pos() + 1; snprintf(temp_word, CURRENT_WORD_BUF, "%" PRIu32 ".%s", word_num, current_word); /* Pad with dashes */ size_t pos_len = strlen(current_word); if (pos_len < 4) { for (size_t i = 0; i < 4 - pos_len; i++) { strlcat(temp_word, "-", CURRENT_WORD_BUF); } } /* Mark as auto completed */ if(auto_completed) { temp_word[strlen(temp_word) + 1] = '\0'; temp_word[strlen(temp_word)] = '~'; } strlcpy(current_word, temp_word, CURRENT_WORD_BUF); memzero(temp_word, sizeof(temp_word)); } /* * get_current_word_pos() - Returns the current word position in the mnemonic * * INPUT * none * OUTPUT * position in mnemonic */ static uint32_t get_current_word_pos(void) { char *pos_num = strchr(mnemonic, ' '); uint32_t word_pos = 0; while(pos_num != NULL) { word_pos++; pos_num = strchr(++pos_num, ' '); } return word_pos; } /// \returns the current word being entered by parsing the mnemonic thus far /// \param current_word[out] Array to populate with current word. static void get_current_word(char *current_word) { char *pos = strrchr(mnemonic, ' '); if(pos) { pos++; strlcpy(current_word, pos, CURRENT_WORD_BUF); } else { strlcpy(current_word, mnemonic, CURRENT_WORD_BUF); } } bool exact_str_match(const char *str1, const char *str2, uint32_t len) { volatile uint32_t match = 0; // Access through volatile ptrs to prevent compiler optimizations that // might leak timing information. const char volatile * volatile str1_v = str1; const char volatile * volatile str2_v = str2; for(uint32_t i = 0; i < len && i < CURRENT_WORD_BUF; i++) { if(str1_v[i] == str2_v[i]) { match++; } else { match--; } } return match == len; } bool attempt_auto_complete(char *partial_word) { // Do lookup through volatile pointers to prevent the compiler from // optimizing this loop into something that can leak timing information. const char *const volatile * volatile wordlist = (const char *const volatile *)mnemonic_wordlist(); uint32_t partial_word_len = strlen(partial_word), match = 0, found = 0; bool precise_match = false; static uint16_t CONFIDENTIAL permute[2049]; for (int i = 0; i < 2049; i++) { permute[i] = i; } random_permute_u16(permute, 2048); // We don't want the compiler to see through the fact that we're randomly // permuting the order of iteration of the next few loops, in case it's // smart enough to see through that and remove the permutation, so we tell // it we've touched all of memory with some inline asm, and scare it off. // This acts as an optimization barrier. asm volatile ("" ::: "memory"); // Look for precise matches first (including null termination) for (uint32_t volatile i = 0; wordlist[permute[i]] != 0; i++) { if (exact_str_match(partial_word, wordlist[permute[i]], partial_word_len + 1)) { strlcpy(partial_word, wordlist[permute[i]], CURRENT_WORD_BUF); precise_match = true; } } random_permute_u16(permute, 2048); asm volatile ("" ::: "memory"); // Followed by partial matches (ignoring null termination) for (uint32_t volatile i = 0; wordlist[permute[i]] != 0; i++) { if (exact_str_match(partial_word, wordlist[permute[i]], partial_word_len)) { match++; found = i; } } if (precise_match) { memzero(permute, sizeof(permute)); return true; } /* Autocomplete if we can */ if (match == 1) { strlcpy(partial_word, wordlist[permute[found]], CURRENT_WORD_BUF); memzero(permute, sizeof(permute)); return true; } memzero(permute, sizeof(permute)); return false; } /* * recovery_cipher_init() - Display standard notification on LCD screen * * INPUT * - passphrase_protection: whether to use passphrase protection * - pin_protection: whether to use pin protection * - language: language for device * - label: label for device * - _enforce_wordlist: whether to enforce bip 39 word list * OUTPUT * none */ void recovery_cipher_init(bool passphrase_protection, bool pin_protection, const char *language, const char *label, bool _enforce_wordlist, uint32_t _auto_lock_delay_ms, uint32_t _u2f_counter, bool _dry_run) { enforce_wordlist = _enforce_wordlist; dry_run = _dry_run; if (!dry_run) { if (pin_protection) { if (!change_pin()) { recovery_abort(); fsm_sendFailure(FailureType_Failure_ActionCancelled, "PINs do not match"); layoutHome(); return; } } else { storage_setPin(""); } storage_setPassphraseProtected(passphrase_protection); storage_setLanguage(language); storage_setLabel(label); storage_setAutoLockDelayMs(_auto_lock_delay_ms); storage_setU2FCounter(_u2f_counter); } else if (!pin_protect("Enter Your PIN")) { layoutHome(); return; } if (!confirm(ButtonRequestType_ButtonRequest_Other, dry_run ? "Recovery Dry Run" : "Recovery", "When entering your recovery seed, use the substitution cipher " "and check that each word shows up correctly on the screen.")) { fsm_sendFailure(FailureType_Failure_ActionCancelled, "Recovery cancelled"); if (!dry_run) storage_reset(); layoutHome(); return; } /* Clear mnemonic */ memset(mnemonic, 0, sizeof(mnemonic) / sizeof(char)); /* Set to recovery cipher mode and generate and show next cipher */ awaiting_character = true; next_character(); } /* * next_character() - Randomizes cipher and displays it for next character entry * * INPUT * none * OUTPUT * none */ void next_character(void) { /* Scramble cipher */ strlcpy(cipher, english_alphabet, ENGLISH_ALPHABET_BUF); random_permute_char(cipher, strlen(cipher)); static char CONFIDENTIAL current_word[CURRENT_WORD_BUF]; get_current_word(current_word); /* Words should never be longer than 4 characters */ if (strlen(current_word) > 4) { memzero(current_word, sizeof(current_word)); recovery_abort(); fsm_sendFailure(FailureType_Failure_SyntaxError, "Words were not entered correctly. Make sure you are using the substition cipher."); layoutHome(); return; } CharacterRequest resp; memset(&resp, 0, sizeof(CharacterRequest)); resp.word_pos = get_current_word_pos(); resp.character_pos = strlen(current_word); msg_write(MessageType_MessageType_CharacterRequest, &resp); /* Attempt to auto complete if we have at least 3 characters */ bool auto_completed = false; if (strlen(current_word) >= 3) { auto_completed = attempt_auto_complete(current_word); } #if DEBUG_LINK if (auto_completed) { strlcpy(auto_completed_word, current_word, CURRENT_WORD_BUF); } else { auto_completed_word[0] = '\0'; } #endif /* Format current word and display it along with cipher */ format_current_word(current_word, auto_completed); /* Show cipher and partial word */ layout_cipher(current_word, cipher); memzero(current_word, sizeof(current_word)); } /* * recovery_character() - Decodes character received from host * * INPUT * - character: string to decode * OUTPUT * none */ void recovery_character(const char *character) { if (!awaiting_character) { recovery_abort(); fsm_sendFailure(FailureType_Failure_UnexpectedMessage, "Not in Recovery mode"); layoutHome(); return; } if (strlen(mnemonic) + 1 > MNEMONIC_BUF - 1) { recovery_abort(); fsm_sendFailure(FailureType_Failure_UnexpectedMessage, "Too many characters attempted during recovery"); layoutHome(); return; } char *pos = strchr(cipher, character[0]); // If not a space and not a legitmate cipher character, send failure. if (character[0] != ' ' && pos == NULL) { recovery_abort(); fsm_sendFailure(FailureType_Failure_SyntaxError, "Character must be from a to z"); layoutHome(); return; } // Count of words we think the user has entered without using the cipher: static int uncyphered_word_count = 0; static bool definitely_using_cipher = false; static CONFIDENTIAL char coded_word[12]; static CONFIDENTIAL char decoded_word[12]; if (!mnemonic[0]) { uncyphered_word_count = 0; definitely_using_cipher = false; memzero(coded_word, sizeof(coded_word)); memzero(decoded_word, sizeof(decoded_word)); } char decoded_character[2] = " "; if (character[0] != ' ') { // Decode character using cipher if not space decoded_character[0] = english_alphabet[(int)(pos - cipher)]; strlcat(coded_word, character, sizeof(coded_word)); strlcat(decoded_word, decoded_character, sizeof(decoded_word)); if (enforce_wordlist && 4 <= strlen(coded_word)) { // Check & bail if the user is entering their seed without using the // cipher. Note that for each word, this can give false positives about // ~0.4% of the time (2048/26^4). bool maybe_not_using_cipher = attempt_auto_complete(coded_word); bool maybe_using_cipher = attempt_auto_complete(decoded_word); if (!maybe_not_using_cipher && maybe_using_cipher) { // Decrease the overall false positive rate by detecting that a // user has entered a word which is definitely using the // cipher. definitely_using_cipher = true; } else if (maybe_not_using_cipher && !definitely_using_cipher && MAX_UNCYPHERED_WORDS < uncyphered_word_count++) { recovery_abort(); fsm_sendFailure(FailureType_Failure_SyntaxError, "Words were not entered correctly. Make sure you are using the substition cipher."); layoutHome(); return; } } } else { memzero(coded_word, sizeof(coded_word)); memzero(decoded_word, sizeof(decoded_word)); } // concat to mnemonic strlcat(mnemonic, decoded_character, MNEMONIC_BUF); next_character(); } /* * recovery_delete_character() - Deletes previously received recovery character * * INPUT * none * OUTPUT * none */ void recovery_delete_character(void) { if(strlen(mnemonic) > 0) { mnemonic[strlen(mnemonic) - 1] = '\0'; } next_character(); } /* * recovery_cipher_finalize() - Finished mnemonic entry * * INPUT * none * OUTPUT * none */ void recovery_cipher_finalize(void) { static char CONFIDENTIAL new_mnemonic[MNEMONIC_BUF] = ""; static char CONFIDENTIAL temp_word[CURRENT_WORD_BUF]; volatile bool auto_completed = true; /* Attempt to autocomplete each word */ char *tok = strtok(mnemonic, " "); while(tok) { strlcpy(temp_word, tok, CURRENT_WORD_BUF); auto_completed &= attempt_auto_complete(temp_word); strlcat(new_mnemonic, temp_word, MNEMONIC_BUF); strlcat(new_mnemonic, " ", MNEMONIC_BUF); tok = strtok(NULL, " "); } memzero(temp_word, sizeof(temp_word)); if (!auto_completed && !enforce_wordlist) { if (!dry_run) { storage_reset(); } fsm_sendFailure(FailureType_Failure_SyntaxError, "Words were not entered correctly. Make sure you are using the substition cipher."); awaiting_character = false; layoutHome(); return; } /* Truncate additional space at the end */ new_mnemonic[strlen(new_mnemonic) - 1] = '\0'; if (!dry_run && (!enforce_wordlist || mnemonic_check(new_mnemonic))) { storage_setMnemonic(new_mnemonic); memzero(new_mnemonic, sizeof(new_mnemonic)); if (!enforce_wordlist) { // not enforcing => mark storage as imported storage_setImported(true); } storage_commit(); fsm_sendSuccess("Device recovered"); } else if (dry_run) { bool match = storage_isInitialized() && storage_containsMnemonic(new_mnemonic); if (match) { review(ButtonRequestType_ButtonRequest_Other, "Recovery Dry Run", "The seed is valid and MATCHES the one in the device."); fsm_sendSuccess("The seed is valid and matches the one in the device."); } else if (mnemonic_check(new_mnemonic)) { review(ButtonRequestType_ButtonRequest_Other, "Recovery Dry Run", "The seed is valid, but DOES NOT MATCH the one in the device."); fsm_sendFailure(FailureType_Failure_Other, "The seed is valid, but does not match the one in the device."); } else { review(ButtonRequestType_ButtonRequest_Other, "Recovery Dry Run", "The seed is INVALID, and DOES NOT MATCH the one in the device."); fsm_sendFailure(FailureType_Failure_Other, "The seed is invalid, and does not match the one in the device."); } memzero(new_mnemonic, sizeof(new_mnemonic)); } else { session_clear(true); fsm_sendFailure(FailureType_Failure_SyntaxError, "Invalid mnemonic, are words in correct order?"); recovery_abort(); } memzero(new_mnemonic, sizeof(new_mnemonic)); awaiting_character = false; memzero(mnemonic, sizeof(mnemonic)); memzero(cipher, sizeof(cipher)); layoutHome(); } /* * recovery_cipher_abort() - Aborts recovery cipher process * * INPUT * none * OUTPUT * true/false of whether recovery was aborted */ bool recovery_cipher_abort(void) { if (awaiting_character) { awaiting_character = false; return true; } return false; } #if DEBUG_LINK /* * recovery_get_cipher() - Gets current cipher being show on display * * INPUT * none * OUTPUT * current cipher */ const char *recovery_get_cipher(void) { return cipher; } /* * recovery_get_auto_completed_word() - Gets last auto completed word * * INPUT * none * OUTPUT * last auto completed word */ const char *recovery_get_auto_completed_word(void) { return auto_completed_word; } #endif
./CrossVul/dataset_final_sorted/CWE-354/c/bad_1210_0
crossvul-cpp_data_good_4604_0
/* $OpenBSD: smtp_session.c,v 1.422 2020/01/28 21:35:00 gilles Exp $ */ /* * Copyright (c) 2008 Gilles Chehade <gilles@poolp.org> * Copyright (c) 2008 Pierre-Yves Ritschard <pyr@openbsd.org> * Copyright (c) 2008-2009 Jacek Masiulaniec <jacekm@dobremiasto.net> * Copyright (c) 2012 Eric Faurot <eric@openbsd.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, 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 <sys/types.h> #include <sys/queue.h> #include <sys/tree.h> #include <sys/socket.h> #include <sys/uio.h> #include <netinet/in.h> #include <ctype.h> #include <errno.h> #include <event.h> #include <imsg.h> #include <limits.h> #include <inttypes.h> #include <openssl/ssl.h> #include <resolv.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <vis.h> #include "smtpd.h" #include "log.h" #include "ssl.h" #include "rfc5322.h" #define SMTP_LINE_MAX 65535 #define DATA_HIWAT 65535 #define APPEND_DOMAIN_BUFFER_SIZE SMTP_LINE_MAX enum smtp_state { STATE_NEW = 0, STATE_CONNECTED, STATE_TLS, STATE_HELO, STATE_AUTH_INIT, STATE_AUTH_USERNAME, STATE_AUTH_PASSWORD, STATE_AUTH_FINALIZE, STATE_BODY, STATE_QUIT, }; enum session_flags { SF_EHLO = 0x0001, SF_8BITMIME = 0x0002, SF_SECURE = 0x0004, SF_AUTHENTICATED = 0x0008, SF_BOUNCE = 0x0010, SF_VERIFIED = 0x0020, SF_BADINPUT = 0x0080, }; enum { TX_OK = 0, TX_ERROR_ENVELOPE, TX_ERROR_SIZE, TX_ERROR_IO, TX_ERROR_LOOP, TX_ERROR_MALFORMED, TX_ERROR_RESOURCES, TX_ERROR_INTERNAL, }; enum smtp_command { CMD_HELO = 0, CMD_EHLO, CMD_STARTTLS, CMD_AUTH, CMD_MAIL_FROM, CMD_RCPT_TO, CMD_DATA, CMD_RSET, CMD_QUIT, CMD_HELP, CMD_WIZ, CMD_NOOP, CMD_COMMIT, }; struct smtp_rcpt { TAILQ_ENTRY(smtp_rcpt) entry; uint64_t evpid; struct mailaddr maddr; size_t destcount; }; struct smtp_tx { struct smtp_session *session; uint32_t msgid; struct envelope evp; size_t rcptcount; size_t destcount; TAILQ_HEAD(, smtp_rcpt) rcpts; time_t time; int error; size_t datain; size_t odatalen; FILE *ofile; struct io *filter; struct rfc5322_parser *parser; int rcvcount; int has_date; int has_message_id; uint8_t junk; }; struct smtp_session { uint64_t id; struct io *io; struct listener *listener; void *ssl_ctx; struct sockaddr_storage ss; char rdns[HOST_NAME_MAX+1]; char smtpname[HOST_NAME_MAX+1]; int fcrdns; int flags; enum smtp_state state; uint8_t banner_sent; char helo[LINE_MAX]; char cmd[LINE_MAX]; char username[SMTPD_MAXMAILADDRSIZE]; size_t mailcount; struct event pause; struct smtp_tx *tx; enum smtp_command last_cmd; enum filter_phase filter_phase; const char *filter_param; uint8_t junk; }; #define ADVERTISE_TLS(s) \ ((s)->listener->flags & F_STARTTLS && !((s)->flags & SF_SECURE)) #define ADVERTISE_AUTH(s) \ ((s)->listener->flags & F_AUTH && (s)->flags & SF_SECURE && \ !((s)->flags & SF_AUTHENTICATED)) #define ADVERTISE_EXT_DSN(s) \ ((s)->listener->flags & F_EXT_DSN) #define SESSION_FILTERED(s) \ ((s)->listener->flags & F_FILTERED) #define SESSION_DATA_FILTERED(s) \ ((s)->listener->flags & F_FILTERED) static int smtp_mailaddr(struct mailaddr *, char *, int, char **, const char *); static void smtp_session_init(void); static void smtp_lookup_servername(struct smtp_session *); static void smtp_getnameinfo_cb(void *, int, const char *, const char *); static void smtp_getaddrinfo_cb(void *, int, struct addrinfo *); static void smtp_connected(struct smtp_session *); static void smtp_send_banner(struct smtp_session *); static void smtp_tls_verified(struct smtp_session *); static void smtp_io(struct io *, int, void *); static void smtp_enter_state(struct smtp_session *, int); static void smtp_reply(struct smtp_session *, char *, ...); static void smtp_command(struct smtp_session *, char *); static void smtp_rfc4954_auth_plain(struct smtp_session *, char *); static void smtp_rfc4954_auth_login(struct smtp_session *, char *); static void smtp_free(struct smtp_session *, const char *); static const char *smtp_strstate(int); static void smtp_cert_init(struct smtp_session *); static void smtp_cert_init_cb(void *, int, const char *, const void *, size_t); static void smtp_cert_verify(struct smtp_session *); static void smtp_cert_verify_cb(void *, int); static void smtp_auth_failure_pause(struct smtp_session *); static void smtp_auth_failure_resume(int, short, void *); static int smtp_tx(struct smtp_session *); static void smtp_tx_free(struct smtp_tx *); static void smtp_tx_create_message(struct smtp_tx *); static void smtp_tx_mail_from(struct smtp_tx *, const char *); static void smtp_tx_rcpt_to(struct smtp_tx *, const char *); static void smtp_tx_open_message(struct smtp_tx *); static void smtp_tx_commit(struct smtp_tx *); static void smtp_tx_rollback(struct smtp_tx *); static int smtp_tx_dataline(struct smtp_tx *, const char *); static int smtp_tx_filtered_dataline(struct smtp_tx *, const char *); static void smtp_tx_eom(struct smtp_tx *); static void smtp_filter_fd(struct smtp_tx *, int); static int smtp_message_fd(struct smtp_tx *, int); static void smtp_message_begin(struct smtp_tx *); static void smtp_message_end(struct smtp_tx *); static int smtp_filter_printf(struct smtp_tx *, const char *, ...) __attribute__((__format__ (printf, 2, 3))); static int smtp_message_printf(struct smtp_tx *, const char *, ...) __attribute__((__format__ (printf, 2, 3))); static int smtp_check_rset(struct smtp_session *, const char *); static int smtp_check_helo(struct smtp_session *, const char *); static int smtp_check_ehlo(struct smtp_session *, const char *); static int smtp_check_auth(struct smtp_session *s, const char *); static int smtp_check_starttls(struct smtp_session *, const char *); static int smtp_check_mail_from(struct smtp_session *, const char *); static int smtp_check_rcpt_to(struct smtp_session *, const char *); static int smtp_check_data(struct smtp_session *, const char *); static int smtp_check_noparam(struct smtp_session *, const char *); static void smtp_filter_phase(enum filter_phase, struct smtp_session *, const char *); static void smtp_proceed_connected(struct smtp_session *); static void smtp_proceed_rset(struct smtp_session *, const char *); static void smtp_proceed_helo(struct smtp_session *, const char *); static void smtp_proceed_ehlo(struct smtp_session *, const char *); static void smtp_proceed_auth(struct smtp_session *, const char *); static void smtp_proceed_starttls(struct smtp_session *, const char *); static void smtp_proceed_mail_from(struct smtp_session *, const char *); static void smtp_proceed_rcpt_to(struct smtp_session *, const char *); static void smtp_proceed_data(struct smtp_session *, const char *); static void smtp_proceed_noop(struct smtp_session *, const char *); static void smtp_proceed_help(struct smtp_session *, const char *); static void smtp_proceed_wiz(struct smtp_session *, const char *); static void smtp_proceed_quit(struct smtp_session *, const char *); static void smtp_proceed_commit(struct smtp_session *, const char *); static void smtp_proceed_rollback(struct smtp_session *, const char *); static void smtp_filter_begin(struct smtp_session *); static void smtp_filter_end(struct smtp_session *); static void smtp_filter_data_begin(struct smtp_session *); static void smtp_filter_data_end(struct smtp_session *); static void smtp_report_link_connect(struct smtp_session *, const char *, int, const struct sockaddr_storage *, const struct sockaddr_storage *); static void smtp_report_link_greeting(struct smtp_session *, const char *); static void smtp_report_link_identify(struct smtp_session *, const char *, const char *); static void smtp_report_link_tls(struct smtp_session *, const char *); static void smtp_report_link_disconnect(struct smtp_session *); static void smtp_report_link_auth(struct smtp_session *, const char *, const char *); static void smtp_report_tx_reset(struct smtp_session *, uint32_t); static void smtp_report_tx_begin(struct smtp_session *, uint32_t); static void smtp_report_tx_mail(struct smtp_session *, uint32_t, const char *, int); static void smtp_report_tx_rcpt(struct smtp_session *, uint32_t, const char *, int); static void smtp_report_tx_envelope(struct smtp_session *, uint32_t, uint64_t); static void smtp_report_tx_data(struct smtp_session *, uint32_t, int); static void smtp_report_tx_commit(struct smtp_session *, uint32_t, size_t); static void smtp_report_tx_rollback(struct smtp_session *, uint32_t); static void smtp_report_protocol_client(struct smtp_session *, const char *); static void smtp_report_protocol_server(struct smtp_session *, const char *); static void smtp_report_filter_response(struct smtp_session *, int, int, const char *); static void smtp_report_timeout(struct smtp_session *); static struct { int code; enum filter_phase filter_phase; const char *cmd; int (*check)(struct smtp_session *, const char *); void (*proceed)(struct smtp_session *, const char *); } commands[] = { { CMD_HELO, FILTER_HELO, "HELO", smtp_check_helo, smtp_proceed_helo }, { CMD_EHLO, FILTER_EHLO, "EHLO", smtp_check_ehlo, smtp_proceed_ehlo }, { CMD_STARTTLS, FILTER_STARTTLS, "STARTTLS", smtp_check_starttls, smtp_proceed_starttls }, { CMD_AUTH, FILTER_AUTH, "AUTH", smtp_check_auth, smtp_proceed_auth }, { CMD_MAIL_FROM, FILTER_MAIL_FROM, "MAIL FROM", smtp_check_mail_from, smtp_proceed_mail_from }, { CMD_RCPT_TO, FILTER_RCPT_TO, "RCPT TO", smtp_check_rcpt_to, smtp_proceed_rcpt_to }, { CMD_DATA, FILTER_DATA, "DATA", smtp_check_data, smtp_proceed_data }, { CMD_RSET, FILTER_RSET, "RSET", smtp_check_rset, smtp_proceed_rset }, { CMD_QUIT, FILTER_QUIT, "QUIT", smtp_check_noparam, smtp_proceed_quit }, { CMD_NOOP, FILTER_NOOP, "NOOP", smtp_check_noparam, smtp_proceed_noop }, { CMD_HELP, FILTER_HELP, "HELP", smtp_check_noparam, smtp_proceed_help }, { CMD_WIZ, FILTER_WIZ, "WIZ", smtp_check_noparam, smtp_proceed_wiz }, { CMD_COMMIT, FILTER_COMMIT, ".", smtp_check_noparam, smtp_proceed_commit }, { -1, 0, NULL, NULL }, }; static struct tree wait_lka_helo; static struct tree wait_lka_mail; static struct tree wait_lka_rcpt; static struct tree wait_parent_auth; static struct tree wait_queue_msg; static struct tree wait_queue_fd; static struct tree wait_queue_commit; static struct tree wait_ssl_init; static struct tree wait_ssl_verify; static struct tree wait_filters; static struct tree wait_filter_fd; static void header_append_domain_buffer(char *buffer, char *domain, size_t len) { size_t i; int escape, quote, comment, bracket; int has_domain, has_bracket, has_group; int pos_bracket, pos_component, pos_insert; char copy[APPEND_DOMAIN_BUFFER_SIZE]; escape = quote = comment = bracket = 0; has_domain = has_bracket = has_group = 0; pos_bracket = pos_insert = pos_component = 0; for (i = 0; buffer[i]; ++i) { if (buffer[i] == '(' && !escape && !quote) comment++; if (buffer[i] == '"' && !escape && !comment) quote = !quote; if (buffer[i] == ')' && !escape && !quote && comment) comment--; if (buffer[i] == '\\' && !escape && !comment && !quote) escape = 1; else escape = 0; if (buffer[i] == '<' && !escape && !comment && !quote && !bracket) { bracket++; has_bracket = 1; } if (buffer[i] == '>' && !escape && !comment && !quote && bracket) { bracket--; pos_bracket = i; } if (buffer[i] == '@' && !escape && !comment && !quote) has_domain = 1; if (buffer[i] == ':' && !escape && !comment && !quote) has_group = 1; /* update insert point if not in comment and not on a whitespace */ if (!comment && buffer[i] != ')' && !isspace((unsigned char)buffer[i])) pos_component = i; } /* parse error, do not attempt to modify */ if (escape || quote || comment || bracket) return; /* domain already present, no need to modify */ if (has_domain) return; /* address is group, skip */ if (has_group) return; /* there's an address between brackets, just append domain */ if (has_bracket) { pos_bracket--; while (isspace((unsigned char)buffer[pos_bracket])) pos_bracket--; if (buffer[pos_bracket] == '<') return; pos_insert = pos_bracket + 1; } else { /* otherwise append address to last component */ pos_insert = pos_component + 1; /* empty address */ if (buffer[pos_component] == '\0' || isspace((unsigned char)buffer[pos_component])) return; } if (snprintf(copy, sizeof copy, "%.*s@%s%s", (int)pos_insert, buffer, domain, buffer+pos_insert) >= (int)sizeof copy) return; memcpy(buffer, copy, len); } static void header_address_rewrite_buffer(char *buffer, const char *address, size_t len) { size_t i; int address_len; int escape, quote, comment, bracket; int has_bracket, has_group; int pos_bracket_beg, pos_bracket_end, pos_component_beg, pos_component_end; int insert_beg, insert_end; char copy[APPEND_DOMAIN_BUFFER_SIZE]; escape = quote = comment = bracket = 0; has_bracket = has_group = 0; pos_bracket_beg = pos_bracket_end = pos_component_beg = pos_component_end = 0; for (i = 0; buffer[i]; ++i) { if (buffer[i] == '(' && !escape && !quote) comment++; if (buffer[i] == '"' && !escape && !comment) quote = !quote; if (buffer[i] == ')' && !escape && !quote && comment) comment--; if (buffer[i] == '\\' && !escape && !comment && !quote) escape = 1; else escape = 0; if (buffer[i] == '<' && !escape && !comment && !quote && !bracket) { bracket++; has_bracket = 1; pos_bracket_beg = i+1; } if (buffer[i] == '>' && !escape && !comment && !quote && bracket) { bracket--; pos_bracket_end = i; } if (buffer[i] == ':' && !escape && !comment && !quote) has_group = 1; /* update insert point if not in comment and not on a whitespace */ if (!comment && buffer[i] != ')' && !isspace((unsigned char)buffer[i])) pos_component_end = i; } /* parse error, do not attempt to modify */ if (escape || quote || comment || bracket) return; /* address is group, skip */ if (has_group) return; /* there's an address between brackets, just replace everything brackets */ if (has_bracket) { insert_beg = pos_bracket_beg; insert_end = pos_bracket_end; } else { if (pos_component_end == 0) pos_component_beg = 0; else { for (pos_component_beg = pos_component_end; pos_component_beg >= 0; --pos_component_beg) if (buffer[pos_component_beg] == ')' || isspace(buffer[pos_component_beg])) break; pos_component_beg += 1; pos_component_end += 1; } insert_beg = pos_component_beg; insert_end = pos_component_end; } /* check that masquerade won' t overflow */ address_len = strlen(address); if (strlen(buffer) - (insert_end - insert_beg) + address_len >= len) return; (void)strlcpy(copy, buffer, sizeof copy); (void)strlcpy(copy+insert_beg, address, sizeof (copy) - insert_beg); (void)strlcat(copy, buffer+insert_end, sizeof (copy)); memcpy(buffer, copy, len); } static void header_domain_append_callback(struct smtp_tx *tx, const char *hdr, const char *val) { size_t i, j, linelen; int escape, quote, comment, skip; char buffer[APPEND_DOMAIN_BUFFER_SIZE]; const char *line, *end; if (smtp_message_printf(tx, "%s:", hdr) == -1) return; j = 0; escape = quote = comment = skip = 0; memset(buffer, 0, sizeof buffer); for (line = val; line; line = end) { end = strchr(line, '\n'); if (end) { linelen = end - line; end++; } else linelen = strlen(line); for (i = 0; i < linelen; ++i) { if (line[i] == '(' && !escape && !quote) comment++; if (line[i] == '"' && !escape && !comment) quote = !quote; if (line[i] == ')' && !escape && !quote && comment) comment--; if (line[i] == '\\' && !escape && !comment && !quote) escape = 1; else escape = 0; /* found a separator, buffer contains a full address */ if (line[i] == ',' && !escape && !quote && !comment) { if (!skip && j + strlen(tx->session->listener->hostname) + 1 < sizeof buffer) { header_append_domain_buffer(buffer, tx->session->listener->hostname, sizeof buffer); if (tx->session->flags & SF_AUTHENTICATED && tx->session->listener->sendertable[0] && tx->session->listener->flags & F_MASQUERADE && !(strcasecmp(hdr, "From"))) header_address_rewrite_buffer(buffer, mailaddr_to_text(&tx->evp.sender), sizeof buffer); } if (smtp_message_printf(tx, "%s,", buffer) == -1) return; j = 0; skip = 0; memset(buffer, 0, sizeof buffer); } else { if (skip) { if (smtp_message_printf(tx, "%c", line[i]) == -1) return; } else { buffer[j++] = line[i]; if (j == sizeof (buffer) - 1) { if (smtp_message_printf(tx, "%s", buffer) == -1) return; skip = 1; j = 0; memset(buffer, 0, sizeof buffer); } } } } if (skip) { if (smtp_message_printf(tx, "\n") == -1) return; } else { buffer[j++] = '\n'; if (j == sizeof (buffer) - 1) { if (smtp_message_printf(tx, "%s", buffer) == -1) return; skip = 1; j = 0; memset(buffer, 0, sizeof buffer); } } } /* end of header, if buffer is not empty we'll process it */ if (buffer[0]) { if (j + strlen(tx->session->listener->hostname) + 1 < sizeof buffer) { header_append_domain_buffer(buffer, tx->session->listener->hostname, sizeof buffer); if (tx->session->flags & SF_AUTHENTICATED && tx->session->listener->sendertable[0] && tx->session->listener->flags & F_MASQUERADE && !(strcasecmp(hdr, "From"))) header_address_rewrite_buffer(buffer, mailaddr_to_text(&tx->evp.sender), sizeof buffer); } smtp_message_printf(tx, "%s", buffer); } } static void smtp_session_init(void) { static int init = 0; if (!init) { tree_init(&wait_lka_helo); tree_init(&wait_lka_mail); tree_init(&wait_lka_rcpt); tree_init(&wait_parent_auth); tree_init(&wait_queue_msg); tree_init(&wait_queue_fd); tree_init(&wait_queue_commit); tree_init(&wait_ssl_init); tree_init(&wait_ssl_verify); tree_init(&wait_filters); tree_init(&wait_filter_fd); init = 1; } } int smtp_session(struct listener *listener, int sock, const struct sockaddr_storage *ss, const char *hostname, struct io *io) { struct smtp_session *s; smtp_session_init(); if ((s = calloc(1, sizeof(*s))) == NULL) return (-1); s->id = generate_uid(); s->listener = listener; memmove(&s->ss, ss, sizeof(*ss)); if (io != NULL) s->io = io; else s->io = io_new(); io_set_callback(s->io, smtp_io, s); io_set_fd(s->io, sock); io_set_timeout(s->io, SMTPD_SESSION_TIMEOUT * 1000); io_set_write(s->io); s->state = STATE_NEW; (void)strlcpy(s->smtpname, listener->hostname, sizeof(s->smtpname)); log_trace(TRACE_SMTP, "smtp: %p: connected to listener %p " "[hostname=%s, port=%d, tag=%s]", s, listener, listener->hostname, ntohs(listener->port), listener->tag); /* For local enqueueing, the hostname is already set */ if (hostname) { s->flags |= SF_AUTHENTICATED; /* A bit of a hack */ if (!strcmp(hostname, "localhost")) s->flags |= SF_BOUNCE; (void)strlcpy(s->rdns, hostname, sizeof(s->rdns)); s->fcrdns = 1; smtp_lookup_servername(s); } else { resolver_getnameinfo((struct sockaddr *)&s->ss, NI_NAMEREQD, smtp_getnameinfo_cb, s); } /* session may have been freed by now */ return (0); } static void smtp_getnameinfo_cb(void *arg, int gaierrno, const char *host, const char *serv) { struct smtp_session *s = arg; struct addrinfo hints; if (gaierrno) { (void)strlcpy(s->rdns, "<unknown>", sizeof(s->rdns)); if (gaierrno == EAI_NODATA || gaierrno == EAI_NONAME) s->fcrdns = 0; else { log_warnx("getnameinfo: %s: %s", ss_to_text(&s->ss), gai_strerror(gaierrno)); s->fcrdns = -1; } smtp_lookup_servername(s); return; } (void)strlcpy(s->rdns, host, sizeof(s->rdns)); memset(&hints, 0, sizeof(hints)); hints.ai_family = s->ss.ss_family; hints.ai_socktype = SOCK_STREAM; resolver_getaddrinfo(s->rdns, NULL, &hints, smtp_getaddrinfo_cb, s); } static void smtp_getaddrinfo_cb(void *arg, int gaierrno, struct addrinfo *ai0) { struct smtp_session *s = arg; struct addrinfo *ai; char fwd[64], rev[64]; if (gaierrno) { if (gaierrno == EAI_NODATA || gaierrno == EAI_NONAME) s->fcrdns = 0; else { log_warnx("getaddrinfo: %s: %s", s->rdns, gai_strerror(gaierrno)); s->fcrdns = -1; } } else { strlcpy(rev, ss_to_text(&s->ss), sizeof(rev)); for (ai = ai0; ai; ai = ai->ai_next) { strlcpy(fwd, sa_to_text(ai->ai_addr), sizeof(fwd)); if (!strcmp(fwd, rev)) { s->fcrdns = 1; break; } } freeaddrinfo(ai0); } smtp_lookup_servername(s); } void smtp_session_imsg(struct mproc *p, struct imsg *imsg) { struct smtp_session *s; struct smtp_rcpt *rcpt; char user[SMTPD_MAXMAILADDRSIZE]; char tmp[SMTP_LINE_MAX]; struct msg m; const char *line, *helo; uint64_t reqid, evpid; uint32_t msgid; int status, success; int filter_response; const char *filter_param; uint8_t i; switch (imsg->hdr.type) { case IMSG_SMTP_CHECK_SENDER: m_msg(&m, imsg); m_get_id(&m, &reqid); m_get_int(&m, &status); m_end(&m); s = tree_xpop(&wait_lka_mail, reqid); switch (status) { case LKA_OK: smtp_tx_create_message(s->tx); break; case LKA_PERMFAIL: smtp_tx_free(s->tx); smtp_reply(s, "%d %s", 530, "Sender rejected"); break; case LKA_TEMPFAIL: smtp_tx_free(s->tx); smtp_reply(s, "421 %s Temporary Error", esc_code(ESC_STATUS_TEMPFAIL, ESC_OTHER_MAIL_SYSTEM_STATUS)); break; } return; case IMSG_SMTP_EXPAND_RCPT: m_msg(&m, imsg); m_get_id(&m, &reqid); m_get_int(&m, &status); m_get_string(&m, &line); m_end(&m); s = tree_xpop(&wait_lka_rcpt, reqid); tmp[0] = '\0'; if (s->tx->evp.rcpt.user[0]) { (void)strlcpy(tmp, s->tx->evp.rcpt.user, sizeof tmp); if (s->tx->evp.rcpt.domain[0]) { (void)strlcat(tmp, "@", sizeof tmp); (void)strlcat(tmp, s->tx->evp.rcpt.domain, sizeof tmp); } } switch (status) { case LKA_OK: fatalx("unexpected ok"); case LKA_PERMFAIL: smtp_reply(s, "%s: <%s>", line, tmp); break; case LKA_TEMPFAIL: smtp_reply(s, "%s: <%s>", line, tmp); break; } return; case IMSG_SMTP_LOOKUP_HELO: m_msg(&m, imsg); m_get_id(&m, &reqid); s = tree_xpop(&wait_lka_helo, reqid); m_get_int(&m, &status); if (status == LKA_OK) { m_get_string(&m, &helo); (void)strlcpy(s->smtpname, helo, sizeof(s->smtpname)); } m_end(&m); smtp_connected(s); return; case IMSG_SMTP_MESSAGE_CREATE: m_msg(&m, imsg); m_get_id(&m, &reqid); m_get_int(&m, &success); s = tree_xpop(&wait_queue_msg, reqid); if (success) { m_get_msgid(&m, &msgid); s->tx->msgid = msgid; s->tx->evp.id = msgid_to_evpid(msgid); s->tx->rcptcount = 0; smtp_reply(s, "250 %s Ok", esc_code(ESC_STATUS_OK, ESC_OTHER_STATUS)); } else { smtp_reply(s, "421 %s Temporary Error", esc_code(ESC_STATUS_TEMPFAIL, ESC_OTHER_MAIL_SYSTEM_STATUS)); smtp_tx_free(s->tx); smtp_enter_state(s, STATE_QUIT); } m_end(&m); return; case IMSG_SMTP_MESSAGE_OPEN: m_msg(&m, imsg); m_get_id(&m, &reqid); m_get_int(&m, &success); m_end(&m); s = tree_xpop(&wait_queue_fd, reqid); if (!success || imsg->fd == -1) { if (imsg->fd != -1) close(imsg->fd); smtp_reply(s, "421 %s Temporary Error", esc_code(ESC_STATUS_TEMPFAIL, ESC_OTHER_MAIL_SYSTEM_STATUS)); smtp_enter_state(s, STATE_QUIT); return; } log_debug("smtp: %p: fd %d from queue", s, imsg->fd); if (smtp_message_fd(s->tx, imsg->fd)) { if (!SESSION_DATA_FILTERED(s)) smtp_message_begin(s->tx); else smtp_filter_data_begin(s); } return; case IMSG_FILTER_SMTP_DATA_BEGIN: m_msg(&m, imsg); m_get_id(&m, &reqid); m_get_int(&m, &success); m_end(&m); s = tree_xpop(&wait_filter_fd, reqid); if (!success || imsg->fd == -1) { if (imsg->fd != -1) close(imsg->fd); smtp_reply(s, "421 %s Temporary Error", esc_code(ESC_STATUS_TEMPFAIL, ESC_OTHER_MAIL_SYSTEM_STATUS)); smtp_enter_state(s, STATE_QUIT); return; } log_debug("smtp: %p: fd %d from lka", s, imsg->fd); smtp_filter_fd(s->tx, imsg->fd); smtp_message_begin(s->tx); return; case IMSG_QUEUE_ENVELOPE_SUBMIT: m_msg(&m, imsg); m_get_id(&m, &reqid); m_get_int(&m, &success); s = tree_xget(&wait_lka_rcpt, reqid); if (success) { m_get_evpid(&m, &evpid); s->tx->evp.id = evpid; s->tx->destcount++; smtp_report_tx_envelope(s, s->tx->msgid, evpid); } else s->tx->error = TX_ERROR_ENVELOPE; m_end(&m); return; case IMSG_QUEUE_ENVELOPE_COMMIT: m_msg(&m, imsg); m_get_id(&m, &reqid); m_get_int(&m, &success); m_end(&m); if (!success) fatalx("commit evp failed: not supposed to happen"); s = tree_xpop(&wait_lka_rcpt, reqid); if (s->tx->error) { /* * If an envelope failed, we can't cancel the last * RCPT only so we must cancel the whole transaction * and close the connection. */ smtp_reply(s, "421 %s Temporary failure", esc_code(ESC_STATUS_TEMPFAIL, ESC_OTHER_MAIL_SYSTEM_STATUS)); smtp_enter_state(s, STATE_QUIT); } else { rcpt = xcalloc(1, sizeof(*rcpt)); rcpt->evpid = s->tx->evp.id; rcpt->destcount = s->tx->destcount; rcpt->maddr = s->tx->evp.rcpt; TAILQ_INSERT_TAIL(&s->tx->rcpts, rcpt, entry); s->tx->destcount = 0; s->tx->rcptcount++; smtp_reply(s, "250 %s %s: Recipient ok", esc_code(ESC_STATUS_OK, ESC_DESTINATION_ADDRESS_VALID), esc_description(ESC_DESTINATION_ADDRESS_VALID)); } return; case IMSG_SMTP_MESSAGE_COMMIT: m_msg(&m, imsg); m_get_id(&m, &reqid); m_get_int(&m, &success); m_end(&m); s = tree_xpop(&wait_queue_commit, reqid); if (!success) { smtp_reply(s, "421 %s Temporary failure", esc_code(ESC_STATUS_TEMPFAIL, ESC_OTHER_MAIL_SYSTEM_STATUS)); smtp_tx_free(s->tx); smtp_enter_state(s, STATE_QUIT); return; } smtp_reply(s, "250 %s %08x Message accepted for delivery", esc_code(ESC_STATUS_OK, ESC_OTHER_STATUS), s->tx->msgid); smtp_report_tx_commit(s, s->tx->msgid, s->tx->odatalen); smtp_report_tx_reset(s, s->tx->msgid); log_info("%016"PRIx64" smtp message " "msgid=%08x size=%zu nrcpt=%zu proto=%s", s->id, s->tx->msgid, s->tx->odatalen, s->tx->rcptcount, s->flags & SF_EHLO ? "ESMTP" : "SMTP"); TAILQ_FOREACH(rcpt, &s->tx->rcpts, entry) { log_info("%016"PRIx64" smtp envelope " "evpid=%016"PRIx64" from=<%s%s%s> to=<%s%s%s>", s->id, rcpt->evpid, s->tx->evp.sender.user, s->tx->evp.sender.user[0] == '\0' ? "" : "@", s->tx->evp.sender.domain, rcpt->maddr.user, rcpt->maddr.user[0] == '\0' ? "" : "@", rcpt->maddr.domain); } smtp_tx_free(s->tx); s->mailcount++; smtp_enter_state(s, STATE_HELO); return; case IMSG_SMTP_AUTHENTICATE: m_msg(&m, imsg); m_get_id(&m, &reqid); m_get_int(&m, &success); m_end(&m); s = tree_xpop(&wait_parent_auth, reqid); strnvis(user, s->username, sizeof user, VIS_WHITE | VIS_SAFE); if (success == LKA_OK) { log_info("%016"PRIx64" smtp " "authentication user=%s " "result=ok", s->id, user); s->flags |= SF_AUTHENTICATED; smtp_report_link_auth(s, user, "pass"); smtp_reply(s, "235 %s Authentication succeeded", esc_code(ESC_STATUS_OK, ESC_OTHER_STATUS)); } else if (success == LKA_PERMFAIL) { log_info("%016"PRIx64" smtp " "authentication user=%s " "result=permfail", s->id, user); smtp_report_link_auth(s, user, "fail"); smtp_auth_failure_pause(s); return; } else if (success == LKA_TEMPFAIL) { log_info("%016"PRIx64" smtp " "authentication user=%s " "result=tempfail", s->id, user); smtp_report_link_auth(s, user, "error"); smtp_reply(s, "421 %s Temporary failure", esc_code(ESC_STATUS_TEMPFAIL, ESC_OTHER_MAIL_SYSTEM_STATUS)); } else fatalx("bad lka response"); smtp_enter_state(s, STATE_HELO); return; case IMSG_FILTER_SMTP_PROTOCOL: m_msg(&m, imsg); m_get_id(&m, &reqid); m_get_int(&m, &filter_response); if (filter_response != FILTER_PROCEED && filter_response != FILTER_JUNK) m_get_string(&m, &filter_param); else filter_param = NULL; m_end(&m); s = tree_xpop(&wait_filters, reqid); switch (filter_response) { case FILTER_REJECT: case FILTER_DISCONNECT: if (!valid_smtp_response(filter_param) || (filter_param[0] != '4' && filter_param[0] != '5')) filter_param = "421 Internal server error"; if (!strncmp(filter_param, "421", 3)) filter_response = FILTER_DISCONNECT; smtp_report_filter_response(s, s->filter_phase, filter_response, filter_param); smtp_reply(s, "%s", filter_param); if (filter_response == FILTER_DISCONNECT) smtp_enter_state(s, STATE_QUIT); else if (s->filter_phase == FILTER_COMMIT) smtp_proceed_rollback(s, NULL); break; case FILTER_JUNK: if (s->tx) s->tx->junk = 1; else s->junk = 1; /* fallthrough */ case FILTER_PROCEED: filter_param = s->filter_param; /* fallthrough */ case FILTER_REWRITE: smtp_report_filter_response(s, s->filter_phase, filter_response, filter_param == s->filter_param ? NULL : filter_param); if (s->filter_phase == FILTER_CONNECT) { smtp_proceed_connected(s); return; } for (i = 0; i < nitems(commands); ++i) if (commands[i].filter_phase == s->filter_phase) { if (filter_response == FILTER_REWRITE) if (!commands[i].check(s, filter_param)) break; commands[i].proceed(s, filter_param); break; } break; } return; } log_warnx("smtp_session_imsg: unexpected %s imsg", imsg_to_str(imsg->hdr.type)); fatalx(NULL); } static void smtp_tls_verified(struct smtp_session *s) { X509 *x; x = SSL_get_peer_certificate(io_tls(s->io)); if (x) { log_info("%016"PRIx64" smtp " "client-cert-check result=\"%s\"", s->id, (s->flags & SF_VERIFIED) ? "success" : "failure"); X509_free(x); } if (s->listener->flags & F_SMTPS) { stat_increment("smtp.smtps", 1); io_set_write(s->io); smtp_send_banner(s); } else { stat_increment("smtp.tls", 1); smtp_enter_state(s, STATE_HELO); } } static void smtp_io(struct io *io, int evt, void *arg) { struct smtp_session *s = arg; char *line; size_t len; int eom; log_trace(TRACE_IO, "smtp: %p: %s %s", s, io_strevent(evt), io_strio(io)); switch (evt) { case IO_TLSREADY: log_info("%016"PRIx64" smtp tls ciphers=%s", s->id, ssl_to_text(io_tls(s->io))); smtp_report_link_tls(s, ssl_to_text(io_tls(s->io))); s->flags |= SF_SECURE; s->helo[0] = '\0'; smtp_cert_verify(s); break; case IO_DATAIN: nextline: line = io_getline(s->io, &len); if ((line == NULL && io_datalen(s->io) >= SMTP_LINE_MAX) || (line && len >= SMTP_LINE_MAX)) { s->flags |= SF_BADINPUT; smtp_reply(s, "500 %s Line too long", esc_code(ESC_STATUS_PERMFAIL, ESC_OTHER_STATUS)); smtp_enter_state(s, STATE_QUIT); io_set_write(io); return; } /* No complete line received */ if (line == NULL) return; /* Message body */ eom = 0; if (s->state == STATE_BODY) { if (strcmp(line, ".")) { s->tx->datain += strlen(line) + 1; if (s->tx->datain > env->sc_maxsize) s->tx->error = TX_ERROR_SIZE; } eom = (s->tx->filter == NULL) ? smtp_tx_dataline(s->tx, line) : smtp_tx_filtered_dataline(s->tx, line); if (eom == 0) goto nextline; } /* Pipelining not supported */ if (io_datalen(s->io)) { s->flags |= SF_BADINPUT; smtp_reply(s, "500 %s %s: Pipelining not supported", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); smtp_enter_state(s, STATE_QUIT); io_set_write(io); return; } if (eom) { io_set_write(io); if (s->tx->filter == NULL) smtp_tx_eom(s->tx); return; } /* Must be a command */ if (strlcpy(s->cmd, line, sizeof(s->cmd)) >= sizeof(s->cmd)) { s->flags |= SF_BADINPUT; smtp_reply(s, "500 %s Command line too long", esc_code(ESC_STATUS_PERMFAIL, ESC_OTHER_STATUS)); smtp_enter_state(s, STATE_QUIT); io_set_write(io); return; } io_set_write(io); smtp_command(s, line); break; case IO_LOWAT: if (s->state == STATE_QUIT) { log_info("%016"PRIx64" smtp disconnected " "reason=quit", s->id); smtp_free(s, "done"); break; } /* Wait for the client to start tls */ if (s->state == STATE_TLS) { smtp_cert_init(s); break; } io_set_read(io); break; case IO_TIMEOUT: log_info("%016"PRIx64" smtp disconnected " "reason=timeout", s->id); smtp_report_timeout(s); smtp_free(s, "timeout"); break; case IO_DISCONNECTED: log_info("%016"PRIx64" smtp disconnected " "reason=disconnect", s->id); smtp_free(s, "disconnected"); break; case IO_ERROR: log_info("%016"PRIx64" smtp disconnected " "reason=\"io-error: %s\"", s->id, io_error(io)); smtp_free(s, "IO error"); break; default: fatalx("smtp_io()"); } } static void smtp_command(struct smtp_session *s, char *line) { char *args; int cmd, i; log_trace(TRACE_SMTP, "smtp: %p: <<< %s", s, line); /* * These states are special. */ if (s->state == STATE_AUTH_INIT) { smtp_report_protocol_client(s, "********"); smtp_rfc4954_auth_plain(s, line); return; } if (s->state == STATE_AUTH_USERNAME || s->state == STATE_AUTH_PASSWORD) { smtp_report_protocol_client(s, "********"); smtp_rfc4954_auth_login(s, line); return; } if (s->state == STATE_HELO && strncasecmp(line, "AUTH PLAIN ", 11) == 0) smtp_report_protocol_client(s, "AUTH PLAIN ********"); else smtp_report_protocol_client(s, line); /* * Unlike other commands, "mail from" and "rcpt to" contain a * space in the command name. */ if (strncasecmp("mail from:", line, 10) == 0 || strncasecmp("rcpt to:", line, 8) == 0) args = strchr(line, ':'); else args = strchr(line, ' '); if (args) { *args++ = '\0'; while (isspace((unsigned char)*args)) args++; } cmd = -1; for (i = 0; commands[i].code != -1; i++) if (!strcasecmp(line, commands[i].cmd)) { cmd = commands[i].code; break; } s->last_cmd = cmd; switch (cmd) { /* * INIT */ case CMD_HELO: if (!smtp_check_helo(s, args)) break; smtp_filter_phase(FILTER_HELO, s, args); break; case CMD_EHLO: if (!smtp_check_ehlo(s, args)) break; smtp_filter_phase(FILTER_EHLO, s, args); break; /* * SETUP */ case CMD_STARTTLS: if (!smtp_check_starttls(s, args)) break; smtp_filter_phase(FILTER_STARTTLS, s, NULL); break; case CMD_AUTH: if (!smtp_check_auth(s, args)) break; smtp_filter_phase(FILTER_AUTH, s, args); break; case CMD_MAIL_FROM: if (!smtp_check_mail_from(s, args)) break; smtp_filter_phase(FILTER_MAIL_FROM, s, args); break; /* * TRANSACTION */ case CMD_RCPT_TO: if (!smtp_check_rcpt_to(s, args)) break; smtp_filter_phase(FILTER_RCPT_TO, s, args); break; case CMD_RSET: if (!smtp_check_rset(s, args)) break; smtp_filter_phase(FILTER_RSET, s, NULL); break; case CMD_DATA: if (!smtp_check_data(s, args)) break; smtp_filter_phase(FILTER_DATA, s, NULL); break; /* * ANY */ case CMD_QUIT: if (!smtp_check_noparam(s, args)) break; smtp_filter_phase(FILTER_QUIT, s, NULL); break; case CMD_NOOP: if (!smtp_check_noparam(s, args)) break; smtp_filter_phase(FILTER_NOOP, s, NULL); break; case CMD_HELP: if (!smtp_check_noparam(s, args)) break; smtp_proceed_help(s, NULL); break; case CMD_WIZ: if (!smtp_check_noparam(s, args)) break; smtp_proceed_wiz(s, NULL); break; default: smtp_reply(s, "500 %s %s: Command unrecognized", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); break; } } static int smtp_check_rset(struct smtp_session *s, const char *args) { if (!smtp_check_noparam(s, args)) return 0; if (s->helo[0] == '\0') { smtp_reply(s, "503 %s %s: Command not allowed at this point.", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } return 1; } static int smtp_check_helo(struct smtp_session *s, const char *args) { if (!s->banner_sent) { smtp_reply(s, "503 %s %s: Command not allowed at this point.", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (s->helo[0]) { smtp_reply(s, "503 %s %s: Already identified", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (args == NULL) { smtp_reply(s, "501 %s %s: HELO requires domain name", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (!valid_domainpart(args)) { smtp_reply(s, "501 %s %s: Invalid domain name", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND_ARGUMENTS), esc_description(ESC_INVALID_COMMAND_ARGUMENTS)); return 0; } return 1; } static int smtp_check_ehlo(struct smtp_session *s, const char *args) { if (!s->banner_sent) { smtp_reply(s, "503 %s %s: Command not allowed at this point.", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (s->helo[0]) { smtp_reply(s, "503 %s %s: Already identified", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (args == NULL) { smtp_reply(s, "501 %s %s: EHLO requires domain name", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (!valid_domainpart(args)) { smtp_reply(s, "501 %s %s: Invalid domain name", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND_ARGUMENTS), esc_description(ESC_INVALID_COMMAND_ARGUMENTS)); return 0; } return 1; } static int smtp_check_auth(struct smtp_session *s, const char *args) { if (s->helo[0] == '\0' || s->tx) { smtp_reply(s, "503 %s %s: Command not allowed at this point.", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (s->flags & SF_AUTHENTICATED) { smtp_reply(s, "503 %s %s: Already authenticated", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (!ADVERTISE_AUTH(s)) { smtp_reply(s, "503 %s %s: Command not supported", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (args == NULL) { smtp_reply(s, "501 %s %s: No parameters given", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND_ARGUMENTS), esc_description(ESC_INVALID_COMMAND_ARGUMENTS)); return 0; } return 1; } static int smtp_check_starttls(struct smtp_session *s, const char *args) { if (s->helo[0] == '\0' || s->tx) { smtp_reply(s, "503 %s %s: Command not allowed at this point.", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (!(s->listener->flags & F_STARTTLS)) { smtp_reply(s, "503 %s %s: Command not supported", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (s->flags & SF_SECURE) { smtp_reply(s, "503 %s %s: Channel already secured", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (args != NULL) { smtp_reply(s, "501 %s %s: No parameters allowed", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND_ARGUMENTS), esc_description(ESC_INVALID_COMMAND_ARGUMENTS)); return 0; } return 1; } static int smtp_check_mail_from(struct smtp_session *s, const char *args) { char *copy; char tmp[SMTP_LINE_MAX]; struct mailaddr sender; (void)strlcpy(tmp, args, sizeof tmp); copy = tmp; if (s->helo[0] == '\0' || s->tx) { smtp_reply(s, "503 %s %s: Command not allowed at this point.", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (s->listener->flags & F_STARTTLS_REQUIRE && !(s->flags & SF_SECURE)) { smtp_reply(s, "530 %s %s: Must issue a STARTTLS command first", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (s->listener->flags & F_AUTH_REQUIRE && !(s->flags & SF_AUTHENTICATED)) { smtp_reply(s, "530 %s %s: Must issue an AUTH command first", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (s->mailcount >= env->sc_session_max_mails) { /* we can pretend we had too many recipients */ smtp_reply(s, "452 %s %s: Too many messages sent", esc_code(ESC_STATUS_TEMPFAIL, ESC_TOO_MANY_RECIPIENTS), esc_description(ESC_TOO_MANY_RECIPIENTS)); return 0; } if (smtp_mailaddr(&sender, copy, 1, &copy, s->smtpname) == 0) { smtp_reply(s, "553 %s Sender address syntax error", esc_code(ESC_STATUS_PERMFAIL, ESC_OTHER_ADDRESS_STATUS)); return 0; } return 1; } static int smtp_check_rcpt_to(struct smtp_session *s, const char *args) { char *copy; char tmp[SMTP_LINE_MAX]; (void)strlcpy(tmp, args, sizeof tmp); copy = tmp; if (s->tx == NULL) { smtp_reply(s, "503 %s %s: Command not allowed at this point.", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (s->tx->rcptcount >= env->sc_session_max_rcpt) { smtp_reply(s->tx->session, "451 %s %s: Too many recipients", esc_code(ESC_STATUS_TEMPFAIL, ESC_TOO_MANY_RECIPIENTS), esc_description(ESC_TOO_MANY_RECIPIENTS)); return 0; } if (smtp_mailaddr(&s->tx->evp.rcpt, copy, 0, &copy, s->tx->session->smtpname) == 0) { smtp_reply(s->tx->session, "501 %s Recipient address syntax error", esc_code(ESC_STATUS_PERMFAIL, ESC_BAD_DESTINATION_MAILBOX_ADDRESS_SYNTAX)); return 0; } return 1; } static int smtp_check_data(struct smtp_session *s, const char *args) { if (!smtp_check_noparam(s, args)) return 0; if (s->tx == NULL) { smtp_reply(s, "503 %s %s: Command not allowed at this point.", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (s->tx->rcptcount == 0) { smtp_reply(s, "503 %s %s: No recipient specified", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND_ARGUMENTS), esc_description(ESC_INVALID_COMMAND_ARGUMENTS)); return 0; } return 1; } static int smtp_check_noparam(struct smtp_session *s, const char *args) { if (args != NULL) { smtp_reply(s, "500 %s %s: command does not accept arguments.", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND_ARGUMENTS), esc_description(ESC_INVALID_COMMAND_ARGUMENTS)); return 0; } return 1; } static void smtp_query_filters(enum filter_phase phase, struct smtp_session *s, const char *args) { m_create(p_lka, IMSG_FILTER_SMTP_PROTOCOL, 0, 0, -1); m_add_id(p_lka, s->id); m_add_int(p_lka, phase); m_add_string(p_lka, args); m_close(p_lka); tree_xset(&wait_filters, s->id, s); } static void smtp_filter_begin(struct smtp_session *s) { if (!SESSION_FILTERED(s)) return; m_create(p_lka, IMSG_FILTER_SMTP_BEGIN, 0, 0, -1); m_add_id(p_lka, s->id); m_add_string(p_lka, s->listener->filter_name); m_close(p_lka); } static void smtp_filter_end(struct smtp_session *s) { if (!SESSION_FILTERED(s)) return; m_create(p_lka, IMSG_FILTER_SMTP_END, 0, 0, -1); m_add_id(p_lka, s->id); m_close(p_lka); } static void smtp_filter_data_begin(struct smtp_session *s) { if (!SESSION_FILTERED(s)) return; m_create(p_lka, IMSG_FILTER_SMTP_DATA_BEGIN, 0, 0, -1); m_add_id(p_lka, s->id); m_close(p_lka); tree_xset(&wait_filter_fd, s->id, s); } static void smtp_filter_data_end(struct smtp_session *s) { if (!SESSION_FILTERED(s)) return; if (s->tx->filter == NULL) return; io_free(s->tx->filter); s->tx->filter = NULL; m_create(p_lka, IMSG_FILTER_SMTP_DATA_END, 0, 0, -1); m_add_id(p_lka, s->id); m_close(p_lka); } static void smtp_filter_phase(enum filter_phase phase, struct smtp_session *s, const char *param) { uint8_t i; s->filter_phase = phase; s->filter_param = param; if (SESSION_FILTERED(s)) { smtp_query_filters(phase, s, param ? param : ""); return; } if (s->filter_phase == FILTER_CONNECT) { smtp_proceed_connected(s); return; } for (i = 0; i < nitems(commands); ++i) if (commands[i].filter_phase == s->filter_phase) { commands[i].proceed(s, param); break; } } static void smtp_proceed_rset(struct smtp_session *s, const char *args) { smtp_reply(s, "250 %s Reset state", esc_code(ESC_STATUS_OK, ESC_OTHER_STATUS)); if (s->tx) { if (s->tx->msgid) smtp_tx_rollback(s->tx); smtp_tx_free(s->tx); } } static void smtp_proceed_helo(struct smtp_session *s, const char *args) { (void)strlcpy(s->helo, args, sizeof(s->helo)); s->flags &= SF_SECURE | SF_AUTHENTICATED | SF_VERIFIED; smtp_report_link_identify(s, "HELO", s->helo); smtp_enter_state(s, STATE_HELO); smtp_reply(s, "250 %s Hello %s %s%s%s, pleased to meet you", s->smtpname, s->helo, s->ss.ss_family == AF_INET6 ? "" : "[", ss_to_text(&s->ss), s->ss.ss_family == AF_INET6 ? "" : "]"); } static void smtp_proceed_ehlo(struct smtp_session *s, const char *args) { (void)strlcpy(s->helo, args, sizeof(s->helo)); s->flags &= SF_SECURE | SF_AUTHENTICATED | SF_VERIFIED; s->flags |= SF_EHLO; s->flags |= SF_8BITMIME; smtp_report_link_identify(s, "EHLO", s->helo); smtp_enter_state(s, STATE_HELO); smtp_reply(s, "250-%s Hello %s %s%s%s, pleased to meet you", s->smtpname, s->helo, s->ss.ss_family == AF_INET6 ? "" : "[", ss_to_text(&s->ss), s->ss.ss_family == AF_INET6 ? "" : "]"); smtp_reply(s, "250-8BITMIME"); smtp_reply(s, "250-ENHANCEDSTATUSCODES"); smtp_reply(s, "250-SIZE %zu", env->sc_maxsize); if (ADVERTISE_EXT_DSN(s)) smtp_reply(s, "250-DSN"); if (ADVERTISE_TLS(s)) smtp_reply(s, "250-STARTTLS"); if (ADVERTISE_AUTH(s)) smtp_reply(s, "250-AUTH PLAIN LOGIN"); smtp_reply(s, "250 HELP"); } static void smtp_proceed_auth(struct smtp_session *s, const char *args) { char tmp[SMTP_LINE_MAX]; char *eom, *method; (void)strlcpy(tmp, args, sizeof tmp); method = tmp; eom = strchr(tmp, ' '); if (eom == NULL) eom = strchr(tmp, '\t'); if (eom != NULL) *eom++ = '\0'; if (strcasecmp(method, "PLAIN") == 0) smtp_rfc4954_auth_plain(s, eom); else if (strcasecmp(method, "LOGIN") == 0) smtp_rfc4954_auth_login(s, eom); else smtp_reply(s, "504 %s %s: AUTH method \"%s\" not supported", esc_code(ESC_STATUS_PERMFAIL, ESC_SECURITY_FEATURES_NOT_SUPPORTED), esc_description(ESC_SECURITY_FEATURES_NOT_SUPPORTED), method); } static void smtp_proceed_starttls(struct smtp_session *s, const char *args) { smtp_reply(s, "220 %s Ready to start TLS", esc_code(ESC_STATUS_OK, ESC_OTHER_STATUS)); smtp_enter_state(s, STATE_TLS); } static void smtp_proceed_mail_from(struct smtp_session *s, const char *args) { char *copy; char tmp[SMTP_LINE_MAX]; (void)strlcpy(tmp, args, sizeof tmp); copy = tmp; if (!smtp_tx(s)) { smtp_reply(s, "421 %s Temporary Error", esc_code(ESC_STATUS_TEMPFAIL, ESC_OTHER_MAIL_SYSTEM_STATUS)); smtp_enter_state(s, STATE_QUIT); return; } if (smtp_mailaddr(&s->tx->evp.sender, copy, 1, &copy, s->smtpname) == 0) { smtp_reply(s, "553 %s Sender address syntax error", esc_code(ESC_STATUS_PERMFAIL, ESC_OTHER_ADDRESS_STATUS)); smtp_tx_free(s->tx); return; } smtp_tx_mail_from(s->tx, args); } static void smtp_proceed_rcpt_to(struct smtp_session *s, const char *args) { smtp_tx_rcpt_to(s->tx, args); } static void smtp_proceed_data(struct smtp_session *s, const char *args) { smtp_tx_open_message(s->tx); } static void smtp_proceed_quit(struct smtp_session *s, const char *args) { smtp_reply(s, "221 %s Bye", esc_code(ESC_STATUS_OK, ESC_OTHER_STATUS)); smtp_enter_state(s, STATE_QUIT); } static void smtp_proceed_noop(struct smtp_session *s, const char *args) { smtp_reply(s, "250 %s Ok", esc_code(ESC_STATUS_OK, ESC_OTHER_STATUS)); } static void smtp_proceed_help(struct smtp_session *s, const char *args) { const char *code = esc_code(ESC_STATUS_OK, ESC_OTHER_STATUS); smtp_reply(s, "214-%s This is " SMTPD_NAME, code); smtp_reply(s, "214-%s To report bugs in the implementation, " "please contact bugs@openbsd.org", code); smtp_reply(s, "214-%s with full details", code); smtp_reply(s, "214 %s End of HELP info", code); } static void smtp_proceed_wiz(struct smtp_session *s, const char *args) { smtp_reply(s, "500 %s %s: this feature is not supported yet ;-)", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); } static void smtp_proceed_commit(struct smtp_session *s, const char *args) { smtp_message_end(s->tx); } static void smtp_proceed_rollback(struct smtp_session *s, const char *args) { struct smtp_tx *tx; tx = s->tx; fclose(tx->ofile); tx->ofile = NULL; smtp_tx_rollback(tx); smtp_tx_free(tx); smtp_enter_state(s, STATE_HELO); } static void smtp_rfc4954_auth_plain(struct smtp_session *s, char *arg) { char buf[1024], *user, *pass; int len; switch (s->state) { case STATE_HELO: if (arg == NULL) { smtp_enter_state(s, STATE_AUTH_INIT); smtp_reply(s, "334 "); return; } smtp_enter_state(s, STATE_AUTH_INIT); /* FALLTHROUGH */ case STATE_AUTH_INIT: /* String is not NUL terminated, leave room. */ if ((len = base64_decode(arg, (unsigned char *)buf, sizeof(buf) - 1)) == -1) goto abort; /* buf is a byte string, NUL terminate. */ buf[len] = '\0'; /* * Skip "foo" in "foo\0user\0pass", if present. */ user = memchr(buf, '\0', len); if (user == NULL || user >= buf + len - 2) goto abort; user++; /* skip NUL */ if (strlcpy(s->username, user, sizeof(s->username)) >= sizeof(s->username)) goto abort; pass = memchr(user, '\0', len - (user - buf)); if (pass == NULL || pass >= buf + len - 2) goto abort; pass++; /* skip NUL */ m_create(p_lka, IMSG_SMTP_AUTHENTICATE, 0, 0, -1); m_add_id(p_lka, s->id); m_add_string(p_lka, s->listener->authtable); m_add_string(p_lka, user); m_add_string(p_lka, pass); m_close(p_lka); tree_xset(&wait_parent_auth, s->id, s); return; default: fatal("smtp_rfc4954_auth_plain: unknown state"); } abort: smtp_reply(s, "501 %s %s: Syntax error", esc_code(ESC_STATUS_PERMFAIL, ESC_SYNTAX_ERROR), esc_description(ESC_SYNTAX_ERROR)); smtp_enter_state(s, STATE_HELO); } static void smtp_rfc4954_auth_login(struct smtp_session *s, char *arg) { char buf[LINE_MAX]; switch (s->state) { case STATE_HELO: smtp_enter_state(s, STATE_AUTH_USERNAME); if (arg != NULL && *arg != '\0') { smtp_rfc4954_auth_login(s, arg); return; } smtp_reply(s, "334 VXNlcm5hbWU6"); return; case STATE_AUTH_USERNAME: memset(s->username, 0, sizeof(s->username)); if (base64_decode(arg, (unsigned char *)s->username, sizeof(s->username) - 1) == -1) goto abort; smtp_enter_state(s, STATE_AUTH_PASSWORD); smtp_reply(s, "334 UGFzc3dvcmQ6"); return; case STATE_AUTH_PASSWORD: memset(buf, 0, sizeof(buf)); if (base64_decode(arg, (unsigned char *)buf, sizeof(buf)-1) == -1) goto abort; m_create(p_lka, IMSG_SMTP_AUTHENTICATE, 0, 0, -1); m_add_id(p_lka, s->id); m_add_string(p_lka, s->listener->authtable); m_add_string(p_lka, s->username); m_add_string(p_lka, buf); m_close(p_lka); tree_xset(&wait_parent_auth, s->id, s); return; default: fatal("smtp_rfc4954_auth_login: unknown state"); } abort: smtp_reply(s, "501 %s %s: Syntax error", esc_code(ESC_STATUS_PERMFAIL, ESC_SYNTAX_ERROR), esc_description(ESC_SYNTAX_ERROR)); smtp_enter_state(s, STATE_HELO); } static void smtp_lookup_servername(struct smtp_session *s) { if (s->listener->hostnametable[0]) { m_create(p_lka, IMSG_SMTP_LOOKUP_HELO, 0, 0, -1); m_add_id(p_lka, s->id); m_add_string(p_lka, s->listener->hostnametable); m_add_sockaddr(p_lka, (struct sockaddr*)&s->listener->ss); m_close(p_lka); tree_xset(&wait_lka_helo, s->id, s); return; } smtp_connected(s); } static void smtp_connected(struct smtp_session *s) { smtp_enter_state(s, STATE_CONNECTED); log_info("%016"PRIx64" smtp connected address=%s host=%s", s->id, ss_to_text(&s->ss), s->rdns); smtp_filter_begin(s); smtp_report_link_connect(s, s->rdns, s->fcrdns, &s->ss, &s->listener->ss); smtp_filter_phase(FILTER_CONNECT, s, ss_to_text(&s->ss)); } static void smtp_proceed_connected(struct smtp_session *s) { if (s->listener->flags & F_SMTPS) smtp_cert_init(s); else smtp_send_banner(s); } static void smtp_send_banner(struct smtp_session *s) { smtp_reply(s, "220 %s ESMTP %s", s->smtpname, SMTPD_NAME); s->banner_sent = 1; smtp_report_link_greeting(s, s->smtpname); } void smtp_enter_state(struct smtp_session *s, int newstate) { log_trace(TRACE_SMTP, "smtp: %p: %s -> %s", s, smtp_strstate(s->state), smtp_strstate(newstate)); s->state = newstate; } static void smtp_reply(struct smtp_session *s, char *fmt, ...) { va_list ap; int n; char buf[LINE_MAX*2], tmp[LINE_MAX*2]; va_start(ap, fmt); n = vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); if (n < 0) fatalx("smtp_reply: response format error"); if (n < 4) fatalx("smtp_reply: response too short"); if (n >= (int)sizeof buf) { /* only first three bytes are used by SMTP logic, * so if _our_ reply does not fit entirely in the * buffer, it's ok to truncate. */ } log_trace(TRACE_SMTP, "smtp: %p: >>> %s", s, buf); smtp_report_protocol_server(s, buf); switch (buf[0]) { case '2': if (s->tx) { if (s->last_cmd == CMD_MAIL_FROM) { smtp_report_tx_begin(s, s->tx->msgid); smtp_report_tx_mail(s, s->tx->msgid, s->cmd + 10, 1); } else if (s->last_cmd == CMD_RCPT_TO) smtp_report_tx_rcpt(s, s->tx->msgid, s->cmd + 8, 1); } break; case '3': if (s->tx) { if (s->last_cmd == CMD_DATA) smtp_report_tx_data(s, s->tx->msgid, 1); } break; case '5': case '4': /* do not report smtp_tx_mail/smtp_tx_rcpt errors * if they happened outside of a transaction. */ if (s->tx) { if (s->last_cmd == CMD_MAIL_FROM) smtp_report_tx_mail(s, s->tx->msgid, s->cmd + 10, buf[0] == '4' ? -1 : 0); else if (s->last_cmd == CMD_RCPT_TO) smtp_report_tx_rcpt(s, s->tx->msgid, s->cmd + 8, buf[0] == '4' ? -1 : 0); else if (s->last_cmd == CMD_DATA && s->tx->rcptcount) smtp_report_tx_data(s, s->tx->msgid, buf[0] == '4' ? -1 : 0); } if (s->flags & SF_BADINPUT) { log_info("%016"PRIx64" smtp " "bad-input result=\"%.*s\"", s->id, n, buf); } else if (s->state == STATE_AUTH_INIT) { log_info("%016"PRIx64" smtp " "failed-command " "command=\"AUTH PLAIN (...)\" result=\"%.*s\"", s->id, n, buf); } else if (s->state == STATE_AUTH_USERNAME) { log_info("%016"PRIx64" smtp " "failed-command " "command=\"AUTH LOGIN (username)\" result=\"%.*s\"", s->id, n, buf); } else if (s->state == STATE_AUTH_PASSWORD) { log_info("%016"PRIx64" smtp " "failed-command " "command=\"AUTH LOGIN (password)\" result=\"%.*s\"", s->id, n, buf); } else { strnvis(tmp, s->cmd, sizeof tmp, VIS_SAFE | VIS_CSTYLE); log_info("%016"PRIx64" smtp " "failed-command command=\"%s\" " "result=\"%.*s\"", s->id, tmp, n, buf); } break; } io_xprintf(s->io, "%s\r\n", buf); } static void smtp_free(struct smtp_session *s, const char * reason) { if (s->tx) { if (s->tx->msgid) smtp_tx_rollback(s->tx); smtp_tx_free(s->tx); } smtp_report_link_disconnect(s); smtp_filter_end(s); if (s->flags & SF_SECURE && s->listener->flags & F_SMTPS) stat_decrement("smtp.smtps", 1); if (s->flags & SF_SECURE && s->listener->flags & F_STARTTLS) stat_decrement("smtp.tls", 1); io_free(s->io); free(s); smtp_collect(); } static int smtp_mailaddr(struct mailaddr *maddr, char *line, int mailfrom, char **args, const char *domain) { char *p, *e; if (line == NULL) return (0); if (*line != '<') return (0); e = strchr(line, '>'); if (e == NULL) return (0); *e++ = '\0'; while (*e == ' ') e++; *args = e; if (!text_to_mailaddr(maddr, line + 1)) return (0); p = strchr(maddr->user, ':'); if (p != NULL) { p++; memmove(maddr->user, p, strlen(p) + 1); } /* accept empty return-path in MAIL FROM, required for bounces */ if (mailfrom && maddr->user[0] == '\0' && maddr->domain[0] == '\0') return (1); /* no or invalid user-part, reject */ if (maddr->user[0] == '\0' || !valid_localpart(maddr->user)) return (0); /* no domain part, local user */ if (maddr->domain[0] == '\0') { (void)strlcpy(maddr->domain, domain, sizeof(maddr->domain)); } if (!valid_domainpart(maddr->domain)) return (0); return (1); } static void smtp_cert_init(struct smtp_session *s) { const char *name; int fallback; if (s->listener->pki_name[0]) { name = s->listener->pki_name; fallback = 0; } else { name = s->smtpname; fallback = 1; } if (cert_init(name, fallback, smtp_cert_init_cb, s)) tree_xset(&wait_ssl_init, s->id, s); } static void smtp_cert_init_cb(void *arg, int status, const char *name, const void *cert, size_t cert_len) { struct smtp_session *s = arg; void *ssl, *ssl_ctx; tree_pop(&wait_ssl_init, s->id); if (status == CA_FAIL) { log_info("%016"PRIx64" smtp disconnected " "reason=ca-failure", s->id); smtp_free(s, "CA failure"); return; } ssl_ctx = dict_get(env->sc_ssl_dict, name); ssl = ssl_smtp_init(ssl_ctx, s->listener->flags & F_TLS_VERIFY); io_set_read(s->io); io_start_tls(s->io, ssl); } static void smtp_cert_verify(struct smtp_session *s) { const char *name; int fallback; if (s->listener->ca_name[0]) { name = s->listener->ca_name; fallback = 0; } else { name = s->smtpname; fallback = 1; } if (cert_verify(io_tls(s->io), name, fallback, smtp_cert_verify_cb, s)) { tree_xset(&wait_ssl_verify, s->id, s); io_pause(s->io, IO_IN); } } static void smtp_cert_verify_cb(void *arg, int status) { struct smtp_session *s = arg; const char *reason = NULL; int resume; resume = tree_pop(&wait_ssl_verify, s->id) != NULL; switch (status) { case CERT_OK: reason = "cert-ok"; s->flags |= SF_VERIFIED; break; case CERT_NOCA: reason = "no-ca"; break; case CERT_NOCERT: reason = "no-client-cert"; break; case CERT_INVALID: reason = "cert-invalid"; break; default: reason = "cert-check-failed"; break; } log_debug("smtp: %p: smtp_cert_verify_cb: %s", s, reason); if (!(s->flags & SF_VERIFIED) && (s->listener->flags & F_TLS_VERIFY)) { log_info("%016"PRIx64" smtp disconnected " " reason=%s", s->id, reason); smtp_free(s, "SSL certificate check failed"); return; } smtp_tls_verified(s); if (resume) io_resume(s->io, IO_IN); } static void smtp_auth_failure_resume(int fd, short event, void *p) { struct smtp_session *s = p; smtp_reply(s, "535 Authentication failed"); smtp_enter_state(s, STATE_HELO); } static void smtp_auth_failure_pause(struct smtp_session *s) { struct timeval tv; tv.tv_sec = 0; tv.tv_usec = arc4random_uniform(1000000); log_trace(TRACE_SMTP, "smtp: timing-attack protection triggered, " "will defer answer for %lu microseconds", tv.tv_usec); evtimer_set(&s->pause, smtp_auth_failure_resume, s); evtimer_add(&s->pause, &tv); } static int smtp_tx(struct smtp_session *s) { struct smtp_tx *tx; tx = calloc(1, sizeof(*tx)); if (tx == NULL) return 0; TAILQ_INIT(&tx->rcpts); s->tx = tx; tx->session = s; /* setup the envelope */ tx->evp.ss = s->ss; (void)strlcpy(tx->evp.tag, s->listener->tag, sizeof(tx->evp.tag)); (void)strlcpy(tx->evp.smtpname, s->smtpname, sizeof(tx->evp.smtpname)); (void)strlcpy(tx->evp.hostname, s->rdns, sizeof tx->evp.hostname); (void)strlcpy(tx->evp.helo, s->helo, sizeof(tx->evp.helo)); (void)strlcpy(tx->evp.username, s->username, sizeof(tx->evp.username)); if (s->flags & SF_BOUNCE) tx->evp.flags |= EF_BOUNCE; if (s->flags & SF_AUTHENTICATED) tx->evp.flags |= EF_AUTHENTICATED; if ((tx->parser = rfc5322_parser_new()) == NULL) { free(tx); return 0; } return 1; } static void smtp_tx_free(struct smtp_tx *tx) { struct smtp_rcpt *rcpt; rfc5322_free(tx->parser); while ((rcpt = TAILQ_FIRST(&tx->rcpts))) { TAILQ_REMOVE(&tx->rcpts, rcpt, entry); free(rcpt); } if (tx->ofile) fclose(tx->ofile); tx->session->tx = NULL; free(tx); } static void smtp_tx_mail_from(struct smtp_tx *tx, const char *line) { char *opt; char *copy; char tmp[SMTP_LINE_MAX]; (void)strlcpy(tmp, line, sizeof tmp); copy = tmp; if (smtp_mailaddr(&tx->evp.sender, copy, 1, &copy, tx->session->smtpname) == 0) { smtp_reply(tx->session, "553 %s Sender address syntax error", esc_code(ESC_STATUS_PERMFAIL, ESC_OTHER_ADDRESS_STATUS)); smtp_tx_free(tx); return; } while ((opt = strsep(&copy, " "))) { if (*opt == '\0') continue; if (strncasecmp(opt, "AUTH=", 5) == 0) log_debug("debug: smtp: AUTH in MAIL FROM command"); else if (strncasecmp(opt, "SIZE=", 5) == 0) log_debug("debug: smtp: SIZE in MAIL FROM command"); else if (strcasecmp(opt, "BODY=7BIT") == 0) /* XXX only for this transaction */ tx->session->flags &= ~SF_8BITMIME; else if (strcasecmp(opt, "BODY=8BITMIME") == 0) ; else if (ADVERTISE_EXT_DSN(tx->session) && strncasecmp(opt, "RET=", 4) == 0) { opt += 4; if (strcasecmp(opt, "HDRS") == 0) tx->evp.dsn_ret = DSN_RETHDRS; else if (strcasecmp(opt, "FULL") == 0) tx->evp.dsn_ret = DSN_RETFULL; } else if (ADVERTISE_EXT_DSN(tx->session) && strncasecmp(opt, "ENVID=", 6) == 0) { opt += 6; if (strlcpy(tx->evp.dsn_envid, opt, sizeof(tx->evp.dsn_envid)) >= sizeof(tx->evp.dsn_envid)) { smtp_reply(tx->session, "503 %s %s: option too large, truncated: %s", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND_ARGUMENTS), esc_description(ESC_INVALID_COMMAND_ARGUMENTS), opt); smtp_tx_free(tx); return; } } else { smtp_reply(tx->session, "503 %s %s: Unsupported option %s", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND_ARGUMENTS), esc_description(ESC_INVALID_COMMAND_ARGUMENTS), opt); smtp_tx_free(tx); return; } } /* only check sendertable if defined and user has authenticated */ if (tx->session->flags & SF_AUTHENTICATED && tx->session->listener->sendertable[0]) { m_create(p_lka, IMSG_SMTP_CHECK_SENDER, 0, 0, -1); m_add_id(p_lka, tx->session->id); m_add_string(p_lka, tx->session->listener->sendertable); m_add_string(p_lka, tx->session->username); m_add_mailaddr(p_lka, &tx->evp.sender); m_close(p_lka); tree_xset(&wait_lka_mail, tx->session->id, tx->session); } else smtp_tx_create_message(tx); } static void smtp_tx_create_message(struct smtp_tx *tx) { m_create(p_queue, IMSG_SMTP_MESSAGE_CREATE, 0, 0, -1); m_add_id(p_queue, tx->session->id); m_close(p_queue); tree_xset(&wait_queue_msg, tx->session->id, tx->session); } static void smtp_tx_rcpt_to(struct smtp_tx *tx, const char *line) { char *opt, *p; char *copy; char tmp[SMTP_LINE_MAX]; (void)strlcpy(tmp, line, sizeof tmp); copy = tmp; if (tx->rcptcount >= env->sc_session_max_rcpt) { smtp_reply(tx->session, "451 %s %s: Too many recipients", esc_code(ESC_STATUS_TEMPFAIL, ESC_TOO_MANY_RECIPIENTS), esc_description(ESC_TOO_MANY_RECIPIENTS)); return; } if (smtp_mailaddr(&tx->evp.rcpt, copy, 0, &copy, tx->session->smtpname) == 0) { smtp_reply(tx->session, "501 %s Recipient address syntax error", esc_code(ESC_STATUS_PERMFAIL, ESC_BAD_DESTINATION_MAILBOX_ADDRESS_SYNTAX)); return; } while ((opt = strsep(&copy, " "))) { if (*opt == '\0') continue; if (ADVERTISE_EXT_DSN(tx->session) && strncasecmp(opt, "NOTIFY=", 7) == 0) { opt += 7; while ((p = strsep(&opt, ","))) { if (strcasecmp(p, "SUCCESS") == 0) tx->evp.dsn_notify |= DSN_SUCCESS; else if (strcasecmp(p, "FAILURE") == 0) tx->evp.dsn_notify |= DSN_FAILURE; else if (strcasecmp(p, "DELAY") == 0) tx->evp.dsn_notify |= DSN_DELAY; else if (strcasecmp(p, "NEVER") == 0) tx->evp.dsn_notify |= DSN_NEVER; } if (tx->evp.dsn_notify & DSN_NEVER && tx->evp.dsn_notify & (DSN_SUCCESS | DSN_FAILURE | DSN_DELAY)) { smtp_reply(tx->session, "553 NOTIFY option NEVER cannot be" " combined with other options"); return; } } else if (ADVERTISE_EXT_DSN(tx->session) && strncasecmp(opt, "ORCPT=", 6) == 0) { opt += 6; if (!text_to_mailaddr(&tx->evp.dsn_orcpt, opt)) { smtp_reply(tx->session, "553 ORCPT address syntax error"); return; } } else { smtp_reply(tx->session, "503 Unsupported option %s", opt); return; } } m_create(p_lka, IMSG_SMTP_EXPAND_RCPT, 0, 0, -1); m_add_id(p_lka, tx->session->id); m_add_envelope(p_lka, &tx->evp); m_close(p_lka); tree_xset(&wait_lka_rcpt, tx->session->id, tx->session); } static void smtp_tx_open_message(struct smtp_tx *tx) { m_create(p_queue, IMSG_SMTP_MESSAGE_OPEN, 0, 0, -1); m_add_id(p_queue, tx->session->id); m_add_msgid(p_queue, tx->msgid); m_close(p_queue); tree_xset(&wait_queue_fd, tx->session->id, tx->session); } static void smtp_tx_commit(struct smtp_tx *tx) { m_create(p_queue, IMSG_SMTP_MESSAGE_COMMIT, 0, 0, -1); m_add_id(p_queue, tx->session->id); m_add_msgid(p_queue, tx->msgid); m_close(p_queue); tree_xset(&wait_queue_commit, tx->session->id, tx->session); smtp_filter_data_end(tx->session); } static void smtp_tx_rollback(struct smtp_tx *tx) { m_create(p_queue, IMSG_SMTP_MESSAGE_ROLLBACK, 0, 0, -1); m_add_msgid(p_queue, tx->msgid); m_close(p_queue); smtp_report_tx_rollback(tx->session, tx->msgid); smtp_report_tx_reset(tx->session, tx->msgid); smtp_filter_data_end(tx->session); } static int smtp_tx_dataline(struct smtp_tx *tx, const char *line) { struct rfc5322_result res; int r; log_trace(TRACE_SMTP, "<<< [MSG] %s", line); if (!strcmp(line, ".")) { smtp_report_protocol_client(tx->session, "."); log_trace(TRACE_SMTP, "<<< [EOM]"); if (tx->error) return 1; line = NULL; } else { /* ignore data line if an error is set */ if (tx->error) return 0; /* escape lines starting with a '.' */ if (line[0] == '.') line += 1; } if (rfc5322_push(tx->parser, line) == -1) { log_warnx("failed to push dataline"); tx->error = TX_ERROR_INTERNAL; return 0; } for(;;) { r = rfc5322_next(tx->parser, &res); switch (r) { case -1: if (errno == ENOMEM) tx->error = TX_ERROR_INTERNAL; else tx->error = TX_ERROR_MALFORMED; return 0; case RFC5322_NONE: /* Need more data */ return 0; case RFC5322_HEADER_START: /* ignore bcc */ if (!strcasecmp("Bcc", res.hdr)) continue; if (!strcasecmp("To", res.hdr) || !strcasecmp("Cc", res.hdr) || !strcasecmp("From", res.hdr)) { rfc5322_unfold_header(tx->parser); continue; } if (!strcasecmp("Received", res.hdr)) { if (++tx->rcvcount >= MAX_HOPS_COUNT) { log_warnx("warn: loop detected"); tx->error = TX_ERROR_LOOP; return 0; } } else if (!tx->has_date && !strcasecmp("Date", res.hdr)) tx->has_date = 1; else if (!tx->has_message_id && !strcasecmp("Message-Id", res.hdr)) tx->has_message_id = 1; smtp_message_printf(tx, "%s:%s\n", res.hdr, res.value); break; case RFC5322_HEADER_CONT: if (!strcasecmp("Bcc", res.hdr) || !strcasecmp("To", res.hdr) || !strcasecmp("Cc", res.hdr) || !strcasecmp("From", res.hdr)) continue; smtp_message_printf(tx, "%s\n", res.value); break; case RFC5322_HEADER_END: if (!strcasecmp("To", res.hdr) || !strcasecmp("Cc", res.hdr) || !strcasecmp("From", res.hdr)) header_domain_append_callback(tx, res.hdr, res.value); break; case RFC5322_END_OF_HEADERS: if (tx->session->listener->local || tx->session->listener->port == 587) { if (!tx->has_date) { log_debug("debug: %p: adding Date", tx); smtp_message_printf(tx, "Date: %s\n", time_to_text(tx->time)); } if (!tx->has_message_id) { log_debug("debug: %p: adding Message-ID", tx); smtp_message_printf(tx, "Message-ID: <%016"PRIx64"@%s>\n", generate_uid(), tx->session->listener->hostname); } } break; case RFC5322_BODY_START: case RFC5322_BODY: smtp_message_printf(tx, "%s\n", res.value); break; case RFC5322_END_OF_MESSAGE: return 1; default: fatalx("%s", __func__); } } } static int smtp_tx_filtered_dataline(struct smtp_tx *tx, const char *line) { if (!strcmp(line, ".")) line = NULL; else { /* ignore data line if an error is set */ if (tx->error) return 0; } io_printf(tx->filter, "%s\n", line ? line : "."); return line ? 0 : 1; } static void smtp_tx_eom(struct smtp_tx *tx) { smtp_filter_phase(FILTER_COMMIT, tx->session, NULL); } static int smtp_message_fd(struct smtp_tx *tx, int fd) { struct smtp_session *s; s = tx->session; log_debug("smtp: %p: message fd %d", s, fd); if ((tx->ofile = fdopen(fd, "w")) == NULL) { close(fd); smtp_reply(s, "421 %s Temporary Error", esc_code(ESC_STATUS_TEMPFAIL, ESC_OTHER_MAIL_SYSTEM_STATUS)); smtp_enter_state(s, STATE_QUIT); return 0; } return 1; } static void filter_session_io(struct io *io, int evt, void *arg) { struct smtp_tx*tx = arg; char*line = NULL; ssize_t len; log_trace(TRACE_IO, "filter session io (smtp): %p: %s %s", tx, io_strevent(evt), io_strio(io)); switch (evt) { case IO_DATAIN: nextline: line = io_getline(tx->filter, &len); /* No complete line received */ if (line == NULL) return; if (smtp_tx_dataline(tx, line)) { smtp_tx_eom(tx); return; } goto nextline; } } static void smtp_filter_fd(struct smtp_tx *tx, int fd) { struct smtp_session *s; s = tx->session; log_debug("smtp: %p: filter fd %d", s, fd); tx->filter = io_new(); io_set_fd(tx->filter, fd); io_set_callback(tx->filter, filter_session_io, tx); } static void smtp_message_begin(struct smtp_tx *tx) { struct smtp_session *s; X509 *x; int (*m_printf)(struct smtp_tx *, const char *, ...); m_printf = smtp_message_printf; if (tx->filter) m_printf = smtp_filter_printf; s = tx->session; log_debug("smtp: %p: message begin", s); smtp_reply(s, "354 Enter mail, end with \".\"" " on a line by itself"); if (s->junk || (s->tx && s->tx->junk)) m_printf(tx, "X-Spam: Yes\n"); m_printf(tx, "Received: "); if (!(s->listener->flags & F_MASK_SOURCE)) { m_printf(tx, "from %s (%s %s%s%s)", s->helo, s->rdns, s->ss.ss_family == AF_INET6 ? "" : "[", ss_to_text(&s->ss), s->ss.ss_family == AF_INET6 ? "" : "]"); } m_printf(tx, "\n\tby %s (%s) with %sSMTP%s%s id %08x", s->smtpname, SMTPD_NAME, s->flags & SF_EHLO ? "E" : "", s->flags & SF_SECURE ? "S" : "", s->flags & SF_AUTHENTICATED ? "A" : "", tx->msgid); if (s->flags & SF_SECURE) { x = SSL_get_peer_certificate(io_tls(s->io)); m_printf(tx, " (%s:%s:%d:%s)", SSL_get_version(io_tls(s->io)), SSL_get_cipher_name(io_tls(s->io)), SSL_get_cipher_bits(io_tls(s->io), NULL), (s->flags & SF_VERIFIED) ? "YES" : (x ? "FAIL" : "NO")); X509_free(x); if (s->listener->flags & F_RECEIVEDAUTH) { m_printf(tx, " auth=%s", s->username[0] ? "yes" : "no"); if (s->username[0]) m_printf(tx, " user=%s", s->username); } } if (tx->rcptcount == 1) { m_printf(tx, "\n\tfor <%s@%s>", tx->evp.rcpt.user, tx->evp.rcpt.domain); } m_printf(tx, ";\n\t%s\n", time_to_text(time(&tx->time))); smtp_enter_state(s, STATE_BODY); } static void smtp_message_end(struct smtp_tx *tx) { struct smtp_session *s; s = tx->session; log_debug("debug: %p: end of message, error=%d", s, tx->error); fclose(tx->ofile); tx->ofile = NULL; switch(tx->error) { case TX_OK: smtp_tx_commit(tx); return; case TX_ERROR_SIZE: smtp_reply(s, "554 %s %s: Transaction failed, message too big", esc_code(ESC_STATUS_PERMFAIL, ESC_MESSAGE_TOO_BIG_FOR_SYSTEM), esc_description(ESC_MESSAGE_TOO_BIG_FOR_SYSTEM)); break; case TX_ERROR_LOOP: smtp_reply(s, "500 %s %s: Loop detected", esc_code(ESC_STATUS_PERMFAIL, ESC_ROUTING_LOOP_DETECTED), esc_description(ESC_ROUTING_LOOP_DETECTED)); break; case TX_ERROR_MALFORMED: smtp_reply(s, "550 %s %s: Message is not RFC 2822 compliant", esc_code(ESC_STATUS_PERMFAIL, ESC_DELIVERY_NOT_AUTHORIZED_MESSAGE_REFUSED), esc_description(ESC_DELIVERY_NOT_AUTHORIZED_MESSAGE_REFUSED)); break; case TX_ERROR_IO: case TX_ERROR_RESOURCES: smtp_reply(s, "421 %s Temporary Error", esc_code(ESC_STATUS_TEMPFAIL, ESC_OTHER_MAIL_SYSTEM_STATUS)); break; default: /* fatal? */ smtp_reply(s, "421 Internal server error"); } smtp_tx_rollback(tx); smtp_tx_free(tx); smtp_enter_state(s, STATE_HELO); } static int smtp_filter_printf(struct smtp_tx *tx, const char *fmt, ...) { va_list ap; int len; if (tx->error) return -1; va_start(ap, fmt); len = io_vprintf(tx->filter, fmt, ap); va_end(ap); if (len < 0) { log_warn("smtp-in: session %016"PRIx64": vfprintf", tx->session->id); tx->error = TX_ERROR_IO; } else tx->odatalen += len; return len; } static int smtp_message_printf(struct smtp_tx *tx, const char *fmt, ...) { va_list ap; int len; if (tx->error) return -1; va_start(ap, fmt); len = vfprintf(tx->ofile, fmt, ap); va_end(ap); if (len == -1) { log_warn("smtp-in: session %016"PRIx64": vfprintf", tx->session->id); tx->error = TX_ERROR_IO; } else tx->odatalen += len; return len; } #define CASE(x) case x : return #x const char * smtp_strstate(int state) { static char buf[32]; switch (state) { CASE(STATE_NEW); CASE(STATE_CONNECTED); CASE(STATE_TLS); CASE(STATE_HELO); CASE(STATE_AUTH_INIT); CASE(STATE_AUTH_USERNAME); CASE(STATE_AUTH_PASSWORD); CASE(STATE_AUTH_FINALIZE); CASE(STATE_BODY); CASE(STATE_QUIT); default: (void)snprintf(buf, sizeof(buf), "STATE_??? (%d)", state); return (buf); } } static void smtp_report_link_connect(struct smtp_session *s, const char *rdns, int fcrdns, const struct sockaddr_storage *ss_src, const struct sockaddr_storage *ss_dest) { if (! SESSION_FILTERED(s)) return; report_smtp_link_connect("smtp-in", s->id, rdns, fcrdns, ss_src, ss_dest); } static void smtp_report_link_greeting(struct smtp_session *s, const char *domain) { if (! SESSION_FILTERED(s)) return; report_smtp_link_greeting("smtp-in", s->id, domain); } static void smtp_report_link_identify(struct smtp_session *s, const char *method, const char *identity) { if (! SESSION_FILTERED(s)) return; report_smtp_link_identify("smtp-in", s->id, method, identity); } static void smtp_report_link_tls(struct smtp_session *s, const char *ssl) { if (! SESSION_FILTERED(s)) return; report_smtp_link_tls("smtp-in", s->id, ssl); } static void smtp_report_link_disconnect(struct smtp_session *s) { if (! SESSION_FILTERED(s)) return; report_smtp_link_disconnect("smtp-in", s->id); } static void smtp_report_link_auth(struct smtp_session *s, const char *user, const char *result) { if (! SESSION_FILTERED(s)) return; report_smtp_link_auth("smtp-in", s->id, user, result); } static void smtp_report_tx_reset(struct smtp_session *s, uint32_t msgid) { if (! SESSION_FILTERED(s)) return; report_smtp_tx_reset("smtp-in", s->id, msgid); } static void smtp_report_tx_begin(struct smtp_session *s, uint32_t msgid) { if (! SESSION_FILTERED(s)) return; report_smtp_tx_begin("smtp-in", s->id, msgid); } static void smtp_report_tx_mail(struct smtp_session *s, uint32_t msgid, const char *address, int ok) { char mailaddr[SMTPD_MAXMAILADDRSIZE]; char *p; if (! SESSION_FILTERED(s)) return; if ((p = strchr(address, '<')) == NULL) return; (void)strlcpy(mailaddr, p + 1, sizeof mailaddr); if ((p = strchr(mailaddr, '>')) == NULL) return; *p = '\0'; report_smtp_tx_mail("smtp-in", s->id, msgid, mailaddr, ok); } static void smtp_report_tx_rcpt(struct smtp_session *s, uint32_t msgid, const char *address, int ok) { char mailaddr[SMTPD_MAXMAILADDRSIZE]; char *p; if (! SESSION_FILTERED(s)) return; if ((p = strchr(address, '<')) == NULL) return; (void)strlcpy(mailaddr, p + 1, sizeof mailaddr); if ((p = strchr(mailaddr, '>')) == NULL) return; *p = '\0'; report_smtp_tx_rcpt("smtp-in", s->id, msgid, mailaddr, ok); } static void smtp_report_tx_envelope(struct smtp_session *s, uint32_t msgid, uint64_t evpid) { if (! SESSION_FILTERED(s)) return; report_smtp_tx_envelope("smtp-in", s->id, msgid, evpid); } static void smtp_report_tx_data(struct smtp_session *s, uint32_t msgid, int ok) { if (! SESSION_FILTERED(s)) return; report_smtp_tx_data("smtp-in", s->id, msgid, ok); } static void smtp_report_tx_commit(struct smtp_session *s, uint32_t msgid, size_t msgsz) { if (! SESSION_FILTERED(s)) return; report_smtp_tx_commit("smtp-in", s->id, msgid, msgsz); } static void smtp_report_tx_rollback(struct smtp_session *s, uint32_t msgid) { if (! SESSION_FILTERED(s)) return; report_smtp_tx_rollback("smtp-in", s->id, msgid); } static void smtp_report_protocol_client(struct smtp_session *s, const char *command) { if (! SESSION_FILTERED(s)) return; report_smtp_protocol_client("smtp-in", s->id, command); } static void smtp_report_protocol_server(struct smtp_session *s, const char *response) { if (! SESSION_FILTERED(s)) return; report_smtp_protocol_server("smtp-in", s->id, response); } static void smtp_report_filter_response(struct smtp_session *s, int phase, int response, const char *param) { if (! SESSION_FILTERED(s)) return; report_smtp_filter_response("smtp-in", s->id, phase, response, param); } static void smtp_report_timeout(struct smtp_session *s) { if (! SESSION_FILTERED(s)) return; report_smtp_timeout("smtp-in", s->id); }
./CrossVul/dataset_final_sorted/CWE-252/c/good_4604_0
crossvul-cpp_data_bad_4268_0
/*********************************************************************** Copyright (c) 2006-2012, Skype Limited. All rights reserved. Redistribution and use in source and binary forms, with or without modification, (subject to the limitations in the disclaimer below) 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. - Neither the name of Skype Limited, nor the names of specific contributors, may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. 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. ***********************************************************************/ /*****************************/ /* Silk decoder test program */ /*****************************/ #ifdef _WIN32 #define _CRT_SECURE_NO_DEPRECATE 1 #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include "SKP_Silk_SDK_API.h" #include "SKP_Silk_SigProc_FIX.h" /* Define codec specific settings should be moved to h file */ #define MAX_BYTES_PER_FRAME 1024 #define MAX_INPUT_FRAMES 5 #define MAX_FRAME_LENGTH 480 #define FRAME_LENGTH_MS 20 #define MAX_API_FS_KHZ 48 #define MAX_LBRR_DELAY 2 #ifdef _SYSTEM_IS_BIG_ENDIAN /* Function to convert a little endian int16 to a */ /* big endian int16 or vica verca */ void swap_endian( SKP_int16 vec[], SKP_int len ) { SKP_int i; SKP_int16 tmp; SKP_uint8 *p1, *p2; for( i = 0; i < len; i++ ){ tmp = vec[ i ]; p1 = (SKP_uint8 *)&vec[ i ]; p2 = (SKP_uint8 *)&tmp; p1[ 0 ] = p2[ 1 ]; p1[ 1 ] = p2[ 0 ]; } } #endif #if (defined(_WIN32) || defined(_WINCE)) #include <windows.h> /* timer */ #else // Linux or Mac #include <sys/time.h> #endif #ifdef _WIN32 unsigned long GetHighResolutionTime() /* O: time in usec*/ { /* Returns a time counter in microsec */ /* the resolution is platform dependent */ /* but is typically 1.62 us resolution */ LARGE_INTEGER lpPerformanceCount; LARGE_INTEGER lpFrequency; QueryPerformanceCounter(&lpPerformanceCount); QueryPerformanceFrequency(&lpFrequency); return (unsigned long)((1000000*(lpPerformanceCount.QuadPart)) / lpFrequency.QuadPart); } #else // Linux or Mac unsigned long GetHighResolutionTime() /* O: time in usec*/ { struct timeval tv; gettimeofday(&tv, 0); return((tv.tv_sec*1000000)+(tv.tv_usec)); } #endif // _WIN32 /* Seed for the random number generator, which is used for simulating packet loss */ static SKP_int32 rand_seed = 1; static void print_usage(char* argv[]) { printf( "\nVersion:20160922 Build By kn007 (kn007.net)"); printf( "\nGithub: https://github.com/kn007/silk-v3-decoder\n"); printf( "\nusage: %s in.bit out.pcm [settings]\n", argv[ 0 ] ); printf( "\nin.bit : Bitstream input to decoder" ); printf( "\nout.pcm : Speech output from decoder" ); printf( "\n settings:" ); printf( "\n-Fs_API <Hz> : Sampling rate of output signal in Hz; default: 24000" ); printf( "\n-loss <perc> : Simulated packet loss percentage (0-100); default: 0" ); printf( "\n-quiet : Print out just some basic values" ); printf( "\n" ); } int main( int argc, char* argv[] ) { unsigned long tottime, starttime; double filetime; size_t counter; SKP_int32 args, totPackets, i, k; SKP_int16 ret, len, tot_len; SKP_int16 nBytes; SKP_uint8 payload[ MAX_BYTES_PER_FRAME * MAX_INPUT_FRAMES * ( MAX_LBRR_DELAY + 1 ) ]; SKP_uint8 *payloadEnd = NULL, *payloadToDec = NULL; SKP_uint8 FECpayload[ MAX_BYTES_PER_FRAME * MAX_INPUT_FRAMES ], *payloadPtr; SKP_int16 nBytesFEC; SKP_int16 nBytesPerPacket[ MAX_LBRR_DELAY + 1 ], totBytes; SKP_int16 out[ ( ( FRAME_LENGTH_MS * MAX_API_FS_KHZ ) << 1 ) * MAX_INPUT_FRAMES ], *outPtr; char speechOutFileName[ 150 ], bitInFileName[ 150 ]; FILE *bitInFile, *speechOutFile; SKP_int32 packetSize_ms=0, API_Fs_Hz = 0; SKP_int32 decSizeBytes; void *psDec; SKP_float loss_prob; SKP_int32 frames, lost, quiet; SKP_SILK_SDK_DecControlStruct DecControl; if( argc < 3 ) { print_usage( argv ); exit( 0 ); } /* default settings */ quiet = 0; loss_prob = 0.0f; /* get arguments */ args = 1; strcpy( bitInFileName, argv[ args ] ); args++; strcpy( speechOutFileName, argv[ args ] ); args++; while( args < argc ) { if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-loss" ) == 0 ) { sscanf( argv[ args + 1 ], "%f", &loss_prob ); args += 2; } else if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-Fs_API" ) == 0 ) { sscanf( argv[ args + 1 ], "%d", &API_Fs_Hz ); args += 2; } else if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-quiet" ) == 0 ) { quiet = 1; args++; } else { printf( "Error: unrecognized setting: %s\n\n", argv[ args ] ); print_usage( argv ); exit( 0 ); } } if( !quiet ) { printf("********** Silk Decoder (Fixed Point) v %s ********************\n", SKP_Silk_SDK_get_version()); printf("********** Compiled for %d bit cpu *******************************\n", (int)sizeof(void*) * 8 ); printf( "Input: %s\n", bitInFileName ); printf( "Output: %s\n", speechOutFileName ); } /* Open files */ bitInFile = fopen( bitInFileName, "rb" ); if( bitInFile == NULL ) { printf( "Error: could not open input file %s\n", bitInFileName ); exit( 0 ); } /* Check Silk header */ { char header_buf[ 50 ]; fread(header_buf, sizeof(char), 1, bitInFile); header_buf[ strlen( "" ) ] = '\0'; /* Terminate with a null character */ if( strcmp( header_buf, "" ) != 0 ) { counter = fread( header_buf, sizeof( char ), strlen( "!SILK_V3" ), bitInFile ); header_buf[ strlen( "!SILK_V3" ) ] = '\0'; /* Terminate with a null character */ if( strcmp( header_buf, "!SILK_V3" ) != 0 ) { /* Non-equal strings */ printf( "Error: Wrong Header %s\n", header_buf ); exit( 0 ); } } else { counter = fread( header_buf, sizeof( char ), strlen( "#!SILK_V3" ), bitInFile ); header_buf[ strlen( "#!SILK_V3" ) ] = '\0'; /* Terminate with a null character */ if( strcmp( header_buf, "#!SILK_V3" ) != 0 ) { /* Non-equal strings */ printf( "Error: Wrong Header %s\n", header_buf ); exit( 0 ); } } } speechOutFile = fopen( speechOutFileName, "wb" ); if( speechOutFile == NULL ) { printf( "Error: could not open output file %s\n", speechOutFileName ); exit( 0 ); } /* Set the samplingrate that is requested for the output */ if( API_Fs_Hz == 0 ) { DecControl.API_sampleRate = 24000; } else { DecControl.API_sampleRate = API_Fs_Hz; } /* Initialize to one frame per packet, for proper concealment before first packet arrives */ DecControl.framesPerPacket = 1; /* Create decoder */ ret = SKP_Silk_SDK_Get_Decoder_Size( &decSizeBytes ); if( ret ) { printf( "\nSKP_Silk_SDK_Get_Decoder_Size returned %d", ret ); } psDec = malloc( decSizeBytes ); /* Reset decoder */ ret = SKP_Silk_SDK_InitDecoder( psDec ); if( ret ) { printf( "\nSKP_Silk_InitDecoder returned %d", ret ); } totPackets = 0; tottime = 0; payloadEnd = payload; /* Simulate the jitter buffer holding MAX_FEC_DELAY packets */ for( i = 0; i < MAX_LBRR_DELAY; i++ ) { /* Read payload size */ counter = fread( &nBytes, sizeof( SKP_int16 ), 1, bitInFile ); #ifdef _SYSTEM_IS_BIG_ENDIAN swap_endian( &nBytes, 1 ); #endif /* Read payload */ counter = fread( payloadEnd, sizeof( SKP_uint8 ), nBytes, bitInFile ); if( ( SKP_int16 )counter < nBytes ) { break; } nBytesPerPacket[ i ] = nBytes; payloadEnd += nBytes; totPackets++; } while( 1 ) { /* Read payload size */ counter = fread( &nBytes, sizeof( SKP_int16 ), 1, bitInFile ); #ifdef _SYSTEM_IS_BIG_ENDIAN swap_endian( &nBytes, 1 ); #endif if( nBytes < 0 || counter < 1 ) { break; } /* Read payload */ counter = fread( payloadEnd, sizeof( SKP_uint8 ), nBytes, bitInFile ); if( ( SKP_int16 )counter < nBytes ) { break; } /* Simulate losses */ rand_seed = SKP_RAND( rand_seed ); if( ( ( ( float )( ( rand_seed >> 16 ) + ( 1 << 15 ) ) ) / 65535.0f >= ( loss_prob / 100.0f ) ) && ( counter > 0 ) ) { nBytesPerPacket[ MAX_LBRR_DELAY ] = nBytes; payloadEnd += nBytes; } else { nBytesPerPacket[ MAX_LBRR_DELAY ] = 0; } if( nBytesPerPacket[ 0 ] == 0 ) { /* Indicate lost packet */ lost = 1; /* Packet loss. Search after FEC in next packets. Should be done in the jitter buffer */ payloadPtr = payload; for( i = 0; i < MAX_LBRR_DELAY; i++ ) { if( nBytesPerPacket[ i + 1 ] > 0 ) { starttime = GetHighResolutionTime(); SKP_Silk_SDK_search_for_LBRR( payloadPtr, nBytesPerPacket[ i + 1 ], ( i + 1 ), FECpayload, &nBytesFEC ); tottime += GetHighResolutionTime() - starttime; if( nBytesFEC > 0 ) { payloadToDec = FECpayload; nBytes = nBytesFEC; lost = 0; break; } } payloadPtr += nBytesPerPacket[ i + 1 ]; } } else { lost = 0; nBytes = nBytesPerPacket[ 0 ]; payloadToDec = payload; } /* Silk decoder */ outPtr = out; tot_len = 0; starttime = GetHighResolutionTime(); if( lost == 0 ) { /* No Loss: Decode all frames in the packet */ frames = 0; do { /* Decode 20 ms */ ret = SKP_Silk_SDK_Decode( psDec, &DecControl, 0, payloadToDec, nBytes, outPtr, &len ); if( ret ) { printf( "\nSKP_Silk_SDK_Decode returned %d", ret ); } frames++; outPtr += len; tot_len += len; if( frames > MAX_INPUT_FRAMES ) { /* Hack for corrupt stream that could generate too many frames */ outPtr = out; tot_len = 0; frames = 0; } /* Until last 20 ms frame of packet has been decoded */ } while( DecControl.moreInternalDecoderFrames ); } else { /* Loss: Decode enough frames to cover one packet duration */ for( i = 0; i < DecControl.framesPerPacket; i++ ) { /* Generate 20 ms */ ret = SKP_Silk_SDK_Decode( psDec, &DecControl, 1, payloadToDec, nBytes, outPtr, &len ); if( ret ) { printf( "\nSKP_Silk_Decode returned %d", ret ); } outPtr += len; tot_len += len; } } packetSize_ms = tot_len / ( DecControl.API_sampleRate / 1000 ); tottime += GetHighResolutionTime() - starttime; totPackets++; /* Write output to file */ #ifdef _SYSTEM_IS_BIG_ENDIAN swap_endian( out, tot_len ); #endif fwrite( out, sizeof( SKP_int16 ), tot_len, speechOutFile ); /* Update buffer */ totBytes = 0; for( i = 0; i < MAX_LBRR_DELAY; i++ ) { totBytes += nBytesPerPacket[ i + 1 ]; } SKP_memmove( payload, &payload[ nBytesPerPacket[ 0 ] ], totBytes * sizeof( SKP_uint8 ) ); payloadEnd -= nBytesPerPacket[ 0 ]; SKP_memmove( nBytesPerPacket, &nBytesPerPacket[ 1 ], MAX_LBRR_DELAY * sizeof( SKP_int16 ) ); if( !quiet ) { fprintf( stderr, "\rPackets decoded: %d", totPackets ); } } /* Empty the recieve buffer */ for( k = 0; k < MAX_LBRR_DELAY; k++ ) { if( nBytesPerPacket[ 0 ] == 0 ) { /* Indicate lost packet */ lost = 1; /* Packet loss. Search after FEC in next packets. Should be done in the jitter buffer */ payloadPtr = payload; for( i = 0; i < MAX_LBRR_DELAY; i++ ) { if( nBytesPerPacket[ i + 1 ] > 0 ) { starttime = GetHighResolutionTime(); SKP_Silk_SDK_search_for_LBRR( payloadPtr, nBytesPerPacket[ i + 1 ], ( i + 1 ), FECpayload, &nBytesFEC ); tottime += GetHighResolutionTime() - starttime; if( nBytesFEC > 0 ) { payloadToDec = FECpayload; nBytes = nBytesFEC; lost = 0; break; } } payloadPtr += nBytesPerPacket[ i + 1 ]; } } else { lost = 0; nBytes = nBytesPerPacket[ 0 ]; payloadToDec = payload; } /* Silk decoder */ outPtr = out; tot_len = 0; starttime = GetHighResolutionTime(); if( lost == 0 ) { /* No loss: Decode all frames in the packet */ frames = 0; do { /* Decode 20 ms */ ret = SKP_Silk_SDK_Decode( psDec, &DecControl, 0, payloadToDec, nBytes, outPtr, &len ); if( ret ) { printf( "\nSKP_Silk_SDK_Decode returned %d", ret ); } frames++; outPtr += len; tot_len += len; if( frames > MAX_INPUT_FRAMES ) { /* Hack for corrupt stream that could generate too many frames */ outPtr = out; tot_len = 0; frames = 0; } /* Until last 20 ms frame of packet has been decoded */ } while( DecControl.moreInternalDecoderFrames ); } else { /* Loss: Decode enough frames to cover one packet duration */ /* Generate 20 ms */ for( i = 0; i < DecControl.framesPerPacket; i++ ) { ret = SKP_Silk_SDK_Decode( psDec, &DecControl, 1, payloadToDec, nBytes, outPtr, &len ); if( ret ) { printf( "\nSKP_Silk_Decode returned %d", ret ); } outPtr += len; tot_len += len; } } packetSize_ms = tot_len / ( DecControl.API_sampleRate / 1000 ); tottime += GetHighResolutionTime() - starttime; totPackets++; /* Write output to file */ #ifdef _SYSTEM_IS_BIG_ENDIAN swap_endian( out, tot_len ); #endif fwrite( out, sizeof( SKP_int16 ), tot_len, speechOutFile ); /* Update Buffer */ totBytes = 0; for( i = 0; i < MAX_LBRR_DELAY; i++ ) { totBytes += nBytesPerPacket[ i + 1 ]; } SKP_memmove( payload, &payload[ nBytesPerPacket[ 0 ] ], totBytes * sizeof( SKP_uint8 ) ); payloadEnd -= nBytesPerPacket[ 0 ]; SKP_memmove( nBytesPerPacket, &nBytesPerPacket[ 1 ], MAX_LBRR_DELAY * sizeof( SKP_int16 ) ); if( !quiet ) { fprintf( stderr, "\rPackets decoded: %d", totPackets ); } } if( !quiet ) { printf( "\nDecoding Finished \n" ); } /* Free decoder */ free( psDec ); /* Close files */ fclose( speechOutFile ); fclose( bitInFile ); filetime = totPackets * 1e-3 * packetSize_ms; if( !quiet ) { printf("\nFile length: %.3f s", filetime); printf("\nTime for decoding: %.3f s (%.3f%% of realtime)", 1e-6 * tottime, 1e-4 * tottime / filetime); printf("\n\n"); } else { /* print time and % of realtime */ printf( "%.3f %.3f %d\n", 1e-6 * tottime, 1e-4 * tottime / filetime, totPackets ); } return 0; }
./CrossVul/dataset_final_sorted/CWE-252/c/bad_4268_0
crossvul-cpp_data_good_4268_0
/*********************************************************************** Copyright (c) 2006-2012, Skype Limited. All rights reserved. Redistribution and use in source and binary forms, with or without modification, (subject to the limitations in the disclaimer below) 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. - Neither the name of Skype Limited, nor the names of specific contributors, may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. 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. ***********************************************************************/ /*****************************/ /* Silk decoder test program */ /*****************************/ #ifdef _WIN32 #define _CRT_SECURE_NO_DEPRECATE 1 #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include "SKP_Silk_SDK_API.h" #include "SKP_Silk_SigProc_FIX.h" /* Define codec specific settings should be moved to h file */ #define MAX_BYTES_PER_FRAME 1024 #define MAX_INPUT_FRAMES 5 #define MAX_FRAME_LENGTH 480 #define FRAME_LENGTH_MS 20 #define MAX_API_FS_KHZ 48 #define MAX_LBRR_DELAY 2 #ifdef _SYSTEM_IS_BIG_ENDIAN /* Function to convert a little endian int16 to a */ /* big endian int16 or vica verca */ void swap_endian( SKP_int16 vec[], SKP_int len ) { SKP_int i; SKP_int16 tmp; SKP_uint8 *p1, *p2; for( i = 0; i < len; i++ ){ tmp = vec[ i ]; p1 = (SKP_uint8 *)&vec[ i ]; p2 = (SKP_uint8 *)&tmp; p1[ 0 ] = p2[ 1 ]; p1[ 1 ] = p2[ 0 ]; } } #endif #if (defined(_WIN32) || defined(_WINCE)) #include <windows.h> /* timer */ #else // Linux or Mac #include <sys/time.h> #endif #ifdef _WIN32 unsigned long GetHighResolutionTime() /* O: time in usec*/ { /* Returns a time counter in microsec */ /* the resolution is platform dependent */ /* but is typically 1.62 us resolution */ LARGE_INTEGER lpPerformanceCount; LARGE_INTEGER lpFrequency; QueryPerformanceCounter(&lpPerformanceCount); QueryPerformanceFrequency(&lpFrequency); return (unsigned long)((1000000*(lpPerformanceCount.QuadPart)) / lpFrequency.QuadPart); } #else // Linux or Mac unsigned long GetHighResolutionTime() /* O: time in usec*/ { struct timeval tv; gettimeofday(&tv, 0); return((tv.tv_sec*1000000)+(tv.tv_usec)); } #endif // _WIN32 /* Seed for the random number generator, which is used for simulating packet loss */ static SKP_int32 rand_seed = 1; static void print_usage(char* argv[]) { printf( "\nVersion:20160922 Build By kn007 (kn007.net)"); printf( "\nGithub: https://github.com/kn007/silk-v3-decoder\n"); printf( "\nusage: %s in.bit out.pcm [settings]\n", argv[ 0 ] ); printf( "\nin.bit : Bitstream input to decoder" ); printf( "\nout.pcm : Speech output from decoder" ); printf( "\n settings:" ); printf( "\n-Fs_API <Hz> : Sampling rate of output signal in Hz; default: 24000" ); printf( "\n-loss <perc> : Simulated packet loss percentage (0-100); default: 0" ); printf( "\n-quiet : Print out just some basic values" ); printf( "\n" ); } int main( int argc, char* argv[] ) { unsigned long tottime, starttime; double filetime; size_t counter; SKP_int32 args, totPackets, i, k; SKP_int16 ret, len, tot_len; SKP_int16 nBytes; SKP_uint8 payload[ MAX_BYTES_PER_FRAME * MAX_INPUT_FRAMES * ( MAX_LBRR_DELAY + 1 ) ]; SKP_uint8 *payloadEnd = NULL, *payloadToDec = NULL; SKP_uint8 FECpayload[ MAX_BYTES_PER_FRAME * MAX_INPUT_FRAMES ], *payloadPtr; SKP_int16 nBytesFEC; SKP_int16 nBytesPerPacket[ MAX_LBRR_DELAY + 1 ], totBytes; SKP_int16 out[ ( ( FRAME_LENGTH_MS * MAX_API_FS_KHZ ) << 1 ) * MAX_INPUT_FRAMES ], *outPtr; char speechOutFileName[ 150 ], bitInFileName[ 150 ]; FILE *bitInFile, *speechOutFile; SKP_int32 packetSize_ms=0, API_Fs_Hz = 0; SKP_int32 decSizeBytes; void *psDec; SKP_float loss_prob; SKP_int32 frames, lost, quiet; SKP_SILK_SDK_DecControlStruct DecControl; if( argc < 3 ) { print_usage( argv ); exit( 0 ); } /* default settings */ quiet = 0; loss_prob = 0.0f; /* get arguments */ args = 1; strcpy( bitInFileName, argv[ args ] ); args++; strcpy( speechOutFileName, argv[ args ] ); args++; while( args < argc ) { if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-loss" ) == 0 ) { sscanf( argv[ args + 1 ], "%f", &loss_prob ); args += 2; } else if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-Fs_API" ) == 0 ) { sscanf( argv[ args + 1 ], "%d", &API_Fs_Hz ); args += 2; } else if( SKP_STR_CASEINSENSITIVE_COMPARE( argv[ args ], "-quiet" ) == 0 ) { quiet = 1; args++; } else { printf( "Error: unrecognized setting: %s\n\n", argv[ args ] ); print_usage( argv ); exit( 0 ); } } if( !quiet ) { printf("********** Silk Decoder (Fixed Point) v %s ********************\n", SKP_Silk_SDK_get_version()); printf("********** Compiled for %d bit cpu *******************************\n", (int)sizeof(void*) * 8 ); printf( "Input: %s\n", bitInFileName ); printf( "Output: %s\n", speechOutFileName ); } /* Open files */ bitInFile = fopen( bitInFileName, "rb" ); if( bitInFile == NULL ) { printf( "Error: could not open input file %s\n", bitInFileName ); exit( 0 ); } /* Check Silk header */ { char header_buf[ 50 ]; fread(header_buf, sizeof(char), 1, bitInFile); header_buf[ strlen( "" ) ] = '\0'; /* Terminate with a null character */ if( strcmp( header_buf, "" ) != 0 ) { counter = fread( header_buf, sizeof( char ), strlen( "!SILK_V3" ), bitInFile ); header_buf[ strlen( "!SILK_V3" ) ] = '\0'; /* Terminate with a null character */ if( strcmp( header_buf, "!SILK_V3" ) != 0 ) { /* Non-equal strings */ printf( "Error: Wrong Header %s\n", header_buf ); exit( 0 ); } } else { counter = fread( header_buf, sizeof( char ), strlen( "#!SILK_V3" ), bitInFile ); header_buf[ strlen( "#!SILK_V3" ) ] = '\0'; /* Terminate with a null character */ if( strcmp( header_buf, "#!SILK_V3" ) != 0 ) { /* Non-equal strings */ printf( "Error: Wrong Header %s\n", header_buf ); exit( 0 ); } } } speechOutFile = fopen( speechOutFileName, "wb" ); if( speechOutFile == NULL ) { printf( "Error: could not open output file %s\n", speechOutFileName ); exit( 0 ); } /* Set the samplingrate that is requested for the output */ if( API_Fs_Hz == 0 ) { DecControl.API_sampleRate = 24000; } else { DecControl.API_sampleRate = API_Fs_Hz; } /* Initialize to one frame per packet, for proper concealment before first packet arrives */ DecControl.framesPerPacket = 1; /* Create decoder */ ret = SKP_Silk_SDK_Get_Decoder_Size( &decSizeBytes ); if( ret ) { printf( "\nSKP_Silk_SDK_Get_Decoder_Size returned %d", ret ); } psDec = malloc( decSizeBytes ); /* Reset decoder */ ret = SKP_Silk_SDK_InitDecoder( psDec ); if( ret ) { printf( "\nSKP_Silk_InitDecoder returned %d", ret ); } totPackets = 0; tottime = 0; payloadEnd = payload; /* Simulate the jitter buffer holding MAX_FEC_DELAY packets */ for( i = 0; i < MAX_LBRR_DELAY; i++ ) { /* Read payload size */ counter = fread( &nBytes, sizeof( SKP_int16 ), 1, bitInFile ); #ifdef _SYSTEM_IS_BIG_ENDIAN swap_endian( &nBytes, 1 ); #endif /* Read payload */ counter = fread( payloadEnd, sizeof( SKP_uint8 ), nBytes, bitInFile ); if( ( SKP_int16 )counter < nBytes ) { break; } nBytesPerPacket[ i ] = nBytes; payloadEnd += nBytes; totPackets++; } while( 1 ) { /* Read payload size */ counter = fread( &nBytes, sizeof( SKP_int16 ), 1, bitInFile ); #ifdef _SYSTEM_IS_BIG_ENDIAN swap_endian( &nBytes, 1 ); #endif if( nBytes < 0 || counter < 1 ) { break; } /* Read payload */ counter = fread( payloadEnd, sizeof( SKP_uint8 ), nBytes, bitInFile ); if( ( SKP_int16 )counter < nBytes ) { break; } /* Simulate losses */ rand_seed = SKP_RAND( rand_seed ); if( ( ( ( float )( ( rand_seed >> 16 ) + ( 1 << 15 ) ) ) / 65535.0f >= ( loss_prob / 100.0f ) ) && ( counter > 0 ) ) { nBytesPerPacket[ MAX_LBRR_DELAY ] = nBytes; payloadEnd += nBytes; } else { nBytesPerPacket[ MAX_LBRR_DELAY ] = 0; } if( nBytesPerPacket[ 0 ] == 0 ) { /* Indicate lost packet */ lost = 1; /* Packet loss. Search after FEC in next packets. Should be done in the jitter buffer */ payloadPtr = payload; for( i = 0; i < MAX_LBRR_DELAY; i++ ) { if( nBytesPerPacket[ i + 1 ] > 0 ) { starttime = GetHighResolutionTime(); SKP_Silk_SDK_search_for_LBRR( payloadPtr, nBytesPerPacket[ i + 1 ], ( i + 1 ), FECpayload, &nBytesFEC ); tottime += GetHighResolutionTime() - starttime; if( nBytesFEC > 0 ) { payloadToDec = FECpayload; nBytes = nBytesFEC; lost = 0; break; } } payloadPtr += nBytesPerPacket[ i + 1 ]; } } else { lost = 0; nBytes = nBytesPerPacket[ 0 ]; payloadToDec = payload; } /* Silk decoder */ outPtr = out; tot_len = 0; starttime = GetHighResolutionTime(); if( lost == 0 ) { /* No Loss: Decode all frames in the packet */ frames = 0; do { /* Decode 20 ms */ ret = SKP_Silk_SDK_Decode( psDec, &DecControl, 0, payloadToDec, nBytes, outPtr, &len ); if( ret ) { printf( "\nSKP_Silk_SDK_Decode returned %d", ret ); } frames++; outPtr += len; tot_len += len; if( frames > MAX_INPUT_FRAMES ) { /* Hack for corrupt stream that could generate too many frames */ outPtr = out; tot_len = 0; frames = 0; } /* Until last 20 ms frame of packet has been decoded */ } while( DecControl.moreInternalDecoderFrames ); } else { /* Loss: Decode enough frames to cover one packet duration */ for( i = 0; i < DecControl.framesPerPacket; i++ ) { /* Generate 20 ms */ ret = SKP_Silk_SDK_Decode( psDec, &DecControl, 1, payloadToDec, nBytes, outPtr, &len ); if( ret ) { printf( "\nSKP_Silk_Decode returned %d", ret ); } outPtr += len; tot_len += len; } } packetSize_ms = tot_len / ( DecControl.API_sampleRate / 1000 ); tottime += GetHighResolutionTime() - starttime; totPackets++; /* Write output to file */ #ifdef _SYSTEM_IS_BIG_ENDIAN swap_endian( out, tot_len ); #endif fwrite( out, sizeof( SKP_int16 ), tot_len, speechOutFile ); /* Update buffer */ totBytes = 0; for( i = 0; i < MAX_LBRR_DELAY; i++ ) { totBytes += nBytesPerPacket[ i + 1 ]; } /* Check if the received totBytes is valid */ if (totBytes < 0 || totBytes > sizeof(payload)) { fprintf( stderr, "\rPackets decoded: %d", totPackets ); return -1; } SKP_memmove( payload, &payload[ nBytesPerPacket[ 0 ] ], totBytes * sizeof( SKP_uint8 ) ); payloadEnd -= nBytesPerPacket[ 0 ]; SKP_memmove( nBytesPerPacket, &nBytesPerPacket[ 1 ], MAX_LBRR_DELAY * sizeof( SKP_int16 ) ); if( !quiet ) { fprintf( stderr, "\rPackets decoded: %d", totPackets ); } } /* Empty the recieve buffer */ for( k = 0; k < MAX_LBRR_DELAY; k++ ) { if( nBytesPerPacket[ 0 ] == 0 ) { /* Indicate lost packet */ lost = 1; /* Packet loss. Search after FEC in next packets. Should be done in the jitter buffer */ payloadPtr = payload; for( i = 0; i < MAX_LBRR_DELAY; i++ ) { if( nBytesPerPacket[ i + 1 ] > 0 ) { starttime = GetHighResolutionTime(); SKP_Silk_SDK_search_for_LBRR( payloadPtr, nBytesPerPacket[ i + 1 ], ( i + 1 ), FECpayload, &nBytesFEC ); tottime += GetHighResolutionTime() - starttime; if( nBytesFEC > 0 ) { payloadToDec = FECpayload; nBytes = nBytesFEC; lost = 0; break; } } payloadPtr += nBytesPerPacket[ i + 1 ]; } } else { lost = 0; nBytes = nBytesPerPacket[ 0 ]; payloadToDec = payload; } /* Silk decoder */ outPtr = out; tot_len = 0; starttime = GetHighResolutionTime(); if( lost == 0 ) { /* No loss: Decode all frames in the packet */ frames = 0; do { /* Decode 20 ms */ ret = SKP_Silk_SDK_Decode( psDec, &DecControl, 0, payloadToDec, nBytes, outPtr, &len ); if( ret ) { printf( "\nSKP_Silk_SDK_Decode returned %d", ret ); } frames++; outPtr += len; tot_len += len; if( frames > MAX_INPUT_FRAMES ) { /* Hack for corrupt stream that could generate too many frames */ outPtr = out; tot_len = 0; frames = 0; } /* Until last 20 ms frame of packet has been decoded */ } while( DecControl.moreInternalDecoderFrames ); } else { /* Loss: Decode enough frames to cover one packet duration */ /* Generate 20 ms */ for( i = 0; i < DecControl.framesPerPacket; i++ ) { ret = SKP_Silk_SDK_Decode( psDec, &DecControl, 1, payloadToDec, nBytes, outPtr, &len ); if( ret ) { printf( "\nSKP_Silk_Decode returned %d", ret ); } outPtr += len; tot_len += len; } } packetSize_ms = tot_len / ( DecControl.API_sampleRate / 1000 ); tottime += GetHighResolutionTime() - starttime; totPackets++; /* Write output to file */ #ifdef _SYSTEM_IS_BIG_ENDIAN swap_endian( out, tot_len ); #endif fwrite( out, sizeof( SKP_int16 ), tot_len, speechOutFile ); /* Update Buffer */ totBytes = 0; for( i = 0; i < MAX_LBRR_DELAY; i++ ) { totBytes += nBytesPerPacket[ i + 1 ]; } /* Check if the received totBytes is valid */ if (totBytes < 0 || totBytes > sizeof(payload)) { fprintf( stderr, "\rPackets decoded: %d", totPackets ); return -1; } SKP_memmove( payload, &payload[ nBytesPerPacket[ 0 ] ], totBytes * sizeof( SKP_uint8 ) ); payloadEnd -= nBytesPerPacket[ 0 ]; SKP_memmove( nBytesPerPacket, &nBytesPerPacket[ 1 ], MAX_LBRR_DELAY * sizeof( SKP_int16 ) ); if( !quiet ) { fprintf( stderr, "\rPackets decoded: %d", totPackets ); } } if( !quiet ) { printf( "\nDecoding Finished \n" ); } /* Free decoder */ free( psDec ); /* Close files */ fclose( speechOutFile ); fclose( bitInFile ); filetime = totPackets * 1e-3 * packetSize_ms; if( !quiet ) { printf("\nFile length: %.3f s", filetime); printf("\nTime for decoding: %.3f s (%.3f%% of realtime)", 1e-6 * tottime, 1e-4 * tottime / filetime); printf("\n\n"); } else { /* print time and % of realtime */ printf( "%.3f %.3f %d\n", 1e-6 * tottime, 1e-4 * tottime / filetime, totPackets ); } return 0; }
./CrossVul/dataset_final_sorted/CWE-252/c/good_4268_0
crossvul-cpp_data_bad_4604_0
/* $OpenBSD: smtp_session.c,v 1.421 2020/01/08 00:05:38 gilles Exp $ */ /* * Copyright (c) 2008 Gilles Chehade <gilles@poolp.org> * Copyright (c) 2008 Pierre-Yves Ritschard <pyr@openbsd.org> * Copyright (c) 2008-2009 Jacek Masiulaniec <jacekm@dobremiasto.net> * Copyright (c) 2012 Eric Faurot <eric@openbsd.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, 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 <sys/types.h> #include <sys/queue.h> #include <sys/tree.h> #include <sys/socket.h> #include <sys/uio.h> #include <netinet/in.h> #include <ctype.h> #include <errno.h> #include <event.h> #include <imsg.h> #include <limits.h> #include <inttypes.h> #include <openssl/ssl.h> #include <resolv.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <vis.h> #include "smtpd.h" #include "log.h" #include "ssl.h" #include "rfc5322.h" #define SMTP_LINE_MAX 65535 #define DATA_HIWAT 65535 #define APPEND_DOMAIN_BUFFER_SIZE SMTP_LINE_MAX enum smtp_state { STATE_NEW = 0, STATE_CONNECTED, STATE_TLS, STATE_HELO, STATE_AUTH_INIT, STATE_AUTH_USERNAME, STATE_AUTH_PASSWORD, STATE_AUTH_FINALIZE, STATE_BODY, STATE_QUIT, }; enum session_flags { SF_EHLO = 0x0001, SF_8BITMIME = 0x0002, SF_SECURE = 0x0004, SF_AUTHENTICATED = 0x0008, SF_BOUNCE = 0x0010, SF_VERIFIED = 0x0020, SF_BADINPUT = 0x0080, }; enum { TX_OK = 0, TX_ERROR_ENVELOPE, TX_ERROR_SIZE, TX_ERROR_IO, TX_ERROR_LOOP, TX_ERROR_MALFORMED, TX_ERROR_RESOURCES, TX_ERROR_INTERNAL, }; enum smtp_command { CMD_HELO = 0, CMD_EHLO, CMD_STARTTLS, CMD_AUTH, CMD_MAIL_FROM, CMD_RCPT_TO, CMD_DATA, CMD_RSET, CMD_QUIT, CMD_HELP, CMD_WIZ, CMD_NOOP, CMD_COMMIT, }; struct smtp_rcpt { TAILQ_ENTRY(smtp_rcpt) entry; uint64_t evpid; struct mailaddr maddr; size_t destcount; }; struct smtp_tx { struct smtp_session *session; uint32_t msgid; struct envelope evp; size_t rcptcount; size_t destcount; TAILQ_HEAD(, smtp_rcpt) rcpts; time_t time; int error; size_t datain; size_t odatalen; FILE *ofile; struct io *filter; struct rfc5322_parser *parser; int rcvcount; int has_date; int has_message_id; uint8_t junk; }; struct smtp_session { uint64_t id; struct io *io; struct listener *listener; void *ssl_ctx; struct sockaddr_storage ss; char rdns[HOST_NAME_MAX+1]; char smtpname[HOST_NAME_MAX+1]; int fcrdns; int flags; enum smtp_state state; uint8_t banner_sent; char helo[LINE_MAX]; char cmd[LINE_MAX]; char username[SMTPD_MAXMAILADDRSIZE]; size_t mailcount; struct event pause; struct smtp_tx *tx; enum smtp_command last_cmd; enum filter_phase filter_phase; const char *filter_param; uint8_t junk; }; #define ADVERTISE_TLS(s) \ ((s)->listener->flags & F_STARTTLS && !((s)->flags & SF_SECURE)) #define ADVERTISE_AUTH(s) \ ((s)->listener->flags & F_AUTH && (s)->flags & SF_SECURE && \ !((s)->flags & SF_AUTHENTICATED)) #define ADVERTISE_EXT_DSN(s) \ ((s)->listener->flags & F_EXT_DSN) #define SESSION_FILTERED(s) \ ((s)->listener->flags & F_FILTERED) #define SESSION_DATA_FILTERED(s) \ ((s)->listener->flags & F_FILTERED) static int smtp_mailaddr(struct mailaddr *, char *, int, char **, const char *); static void smtp_session_init(void); static void smtp_lookup_servername(struct smtp_session *); static void smtp_getnameinfo_cb(void *, int, const char *, const char *); static void smtp_getaddrinfo_cb(void *, int, struct addrinfo *); static void smtp_connected(struct smtp_session *); static void smtp_send_banner(struct smtp_session *); static void smtp_tls_verified(struct smtp_session *); static void smtp_io(struct io *, int, void *); static void smtp_enter_state(struct smtp_session *, int); static void smtp_reply(struct smtp_session *, char *, ...); static void smtp_command(struct smtp_session *, char *); static void smtp_rfc4954_auth_plain(struct smtp_session *, char *); static void smtp_rfc4954_auth_login(struct smtp_session *, char *); static void smtp_free(struct smtp_session *, const char *); static const char *smtp_strstate(int); static void smtp_cert_init(struct smtp_session *); static void smtp_cert_init_cb(void *, int, const char *, const void *, size_t); static void smtp_cert_verify(struct smtp_session *); static void smtp_cert_verify_cb(void *, int); static void smtp_auth_failure_pause(struct smtp_session *); static void smtp_auth_failure_resume(int, short, void *); static int smtp_tx(struct smtp_session *); static void smtp_tx_free(struct smtp_tx *); static void smtp_tx_create_message(struct smtp_tx *); static void smtp_tx_mail_from(struct smtp_tx *, const char *); static void smtp_tx_rcpt_to(struct smtp_tx *, const char *); static void smtp_tx_open_message(struct smtp_tx *); static void smtp_tx_commit(struct smtp_tx *); static void smtp_tx_rollback(struct smtp_tx *); static int smtp_tx_dataline(struct smtp_tx *, const char *); static int smtp_tx_filtered_dataline(struct smtp_tx *, const char *); static void smtp_tx_eom(struct smtp_tx *); static void smtp_filter_fd(struct smtp_tx *, int); static int smtp_message_fd(struct smtp_tx *, int); static void smtp_message_begin(struct smtp_tx *); static void smtp_message_end(struct smtp_tx *); static int smtp_filter_printf(struct smtp_tx *, const char *, ...) __attribute__((__format__ (printf, 2, 3))); static int smtp_message_printf(struct smtp_tx *, const char *, ...) __attribute__((__format__ (printf, 2, 3))); static int smtp_check_rset(struct smtp_session *, const char *); static int smtp_check_helo(struct smtp_session *, const char *); static int smtp_check_ehlo(struct smtp_session *, const char *); static int smtp_check_auth(struct smtp_session *s, const char *); static int smtp_check_starttls(struct smtp_session *, const char *); static int smtp_check_mail_from(struct smtp_session *, const char *); static int smtp_check_rcpt_to(struct smtp_session *, const char *); static int smtp_check_data(struct smtp_session *, const char *); static int smtp_check_noparam(struct smtp_session *, const char *); static void smtp_filter_phase(enum filter_phase, struct smtp_session *, const char *); static void smtp_proceed_connected(struct smtp_session *); static void smtp_proceed_rset(struct smtp_session *, const char *); static void smtp_proceed_helo(struct smtp_session *, const char *); static void smtp_proceed_ehlo(struct smtp_session *, const char *); static void smtp_proceed_auth(struct smtp_session *, const char *); static void smtp_proceed_starttls(struct smtp_session *, const char *); static void smtp_proceed_mail_from(struct smtp_session *, const char *); static void smtp_proceed_rcpt_to(struct smtp_session *, const char *); static void smtp_proceed_data(struct smtp_session *, const char *); static void smtp_proceed_noop(struct smtp_session *, const char *); static void smtp_proceed_help(struct smtp_session *, const char *); static void smtp_proceed_wiz(struct smtp_session *, const char *); static void smtp_proceed_quit(struct smtp_session *, const char *); static void smtp_proceed_commit(struct smtp_session *, const char *); static void smtp_proceed_rollback(struct smtp_session *, const char *); static void smtp_filter_begin(struct smtp_session *); static void smtp_filter_end(struct smtp_session *); static void smtp_filter_data_begin(struct smtp_session *); static void smtp_filter_data_end(struct smtp_session *); static void smtp_report_link_connect(struct smtp_session *, const char *, int, const struct sockaddr_storage *, const struct sockaddr_storage *); static void smtp_report_link_greeting(struct smtp_session *, const char *); static void smtp_report_link_identify(struct smtp_session *, const char *, const char *); static void smtp_report_link_tls(struct smtp_session *, const char *); static void smtp_report_link_disconnect(struct smtp_session *); static void smtp_report_link_auth(struct smtp_session *, const char *, const char *); static void smtp_report_tx_reset(struct smtp_session *, uint32_t); static void smtp_report_tx_begin(struct smtp_session *, uint32_t); static void smtp_report_tx_mail(struct smtp_session *, uint32_t, const char *, int); static void smtp_report_tx_rcpt(struct smtp_session *, uint32_t, const char *, int); static void smtp_report_tx_envelope(struct smtp_session *, uint32_t, uint64_t); static void smtp_report_tx_data(struct smtp_session *, uint32_t, int); static void smtp_report_tx_commit(struct smtp_session *, uint32_t, size_t); static void smtp_report_tx_rollback(struct smtp_session *, uint32_t); static void smtp_report_protocol_client(struct smtp_session *, const char *); static void smtp_report_protocol_server(struct smtp_session *, const char *); static void smtp_report_filter_response(struct smtp_session *, int, int, const char *); static void smtp_report_timeout(struct smtp_session *); static struct { int code; enum filter_phase filter_phase; const char *cmd; int (*check)(struct smtp_session *, const char *); void (*proceed)(struct smtp_session *, const char *); } commands[] = { { CMD_HELO, FILTER_HELO, "HELO", smtp_check_helo, smtp_proceed_helo }, { CMD_EHLO, FILTER_EHLO, "EHLO", smtp_check_ehlo, smtp_proceed_ehlo }, { CMD_STARTTLS, FILTER_STARTTLS, "STARTTLS", smtp_check_starttls, smtp_proceed_starttls }, { CMD_AUTH, FILTER_AUTH, "AUTH", smtp_check_auth, smtp_proceed_auth }, { CMD_MAIL_FROM, FILTER_MAIL_FROM, "MAIL FROM", smtp_check_mail_from, smtp_proceed_mail_from }, { CMD_RCPT_TO, FILTER_RCPT_TO, "RCPT TO", smtp_check_rcpt_to, smtp_proceed_rcpt_to }, { CMD_DATA, FILTER_DATA, "DATA", smtp_check_data, smtp_proceed_data }, { CMD_RSET, FILTER_RSET, "RSET", smtp_check_rset, smtp_proceed_rset }, { CMD_QUIT, FILTER_QUIT, "QUIT", smtp_check_noparam, smtp_proceed_quit }, { CMD_NOOP, FILTER_NOOP, "NOOP", smtp_check_noparam, smtp_proceed_noop }, { CMD_HELP, FILTER_HELP, "HELP", smtp_check_noparam, smtp_proceed_help }, { CMD_WIZ, FILTER_WIZ, "WIZ", smtp_check_noparam, smtp_proceed_wiz }, { CMD_COMMIT, FILTER_COMMIT, ".", smtp_check_noparam, smtp_proceed_commit }, { -1, 0, NULL, NULL }, }; static struct tree wait_lka_helo; static struct tree wait_lka_mail; static struct tree wait_lka_rcpt; static struct tree wait_parent_auth; static struct tree wait_queue_msg; static struct tree wait_queue_fd; static struct tree wait_queue_commit; static struct tree wait_ssl_init; static struct tree wait_ssl_verify; static struct tree wait_filters; static struct tree wait_filter_fd; static void header_append_domain_buffer(char *buffer, char *domain, size_t len) { size_t i; int escape, quote, comment, bracket; int has_domain, has_bracket, has_group; int pos_bracket, pos_component, pos_insert; char copy[APPEND_DOMAIN_BUFFER_SIZE]; escape = quote = comment = bracket = 0; has_domain = has_bracket = has_group = 0; pos_bracket = pos_insert = pos_component = 0; for (i = 0; buffer[i]; ++i) { if (buffer[i] == '(' && !escape && !quote) comment++; if (buffer[i] == '"' && !escape && !comment) quote = !quote; if (buffer[i] == ')' && !escape && !quote && comment) comment--; if (buffer[i] == '\\' && !escape && !comment && !quote) escape = 1; else escape = 0; if (buffer[i] == '<' && !escape && !comment && !quote && !bracket) { bracket++; has_bracket = 1; } if (buffer[i] == '>' && !escape && !comment && !quote && bracket) { bracket--; pos_bracket = i; } if (buffer[i] == '@' && !escape && !comment && !quote) has_domain = 1; if (buffer[i] == ':' && !escape && !comment && !quote) has_group = 1; /* update insert point if not in comment and not on a whitespace */ if (!comment && buffer[i] != ')' && !isspace((unsigned char)buffer[i])) pos_component = i; } /* parse error, do not attempt to modify */ if (escape || quote || comment || bracket) return; /* domain already present, no need to modify */ if (has_domain) return; /* address is group, skip */ if (has_group) return; /* there's an address between brackets, just append domain */ if (has_bracket) { pos_bracket--; while (isspace((unsigned char)buffer[pos_bracket])) pos_bracket--; if (buffer[pos_bracket] == '<') return; pos_insert = pos_bracket + 1; } else { /* otherwise append address to last component */ pos_insert = pos_component + 1; /* empty address */ if (buffer[pos_component] == '\0' || isspace((unsigned char)buffer[pos_component])) return; } if (snprintf(copy, sizeof copy, "%.*s@%s%s", (int)pos_insert, buffer, domain, buffer+pos_insert) >= (int)sizeof copy) return; memcpy(buffer, copy, len); } static void header_address_rewrite_buffer(char *buffer, const char *address, size_t len) { size_t i; int address_len; int escape, quote, comment, bracket; int has_bracket, has_group; int pos_bracket_beg, pos_bracket_end, pos_component_beg, pos_component_end; int insert_beg, insert_end; char copy[APPEND_DOMAIN_BUFFER_SIZE]; escape = quote = comment = bracket = 0; has_bracket = has_group = 0; pos_bracket_beg = pos_bracket_end = pos_component_beg = pos_component_end = 0; for (i = 0; buffer[i]; ++i) { if (buffer[i] == '(' && !escape && !quote) comment++; if (buffer[i] == '"' && !escape && !comment) quote = !quote; if (buffer[i] == ')' && !escape && !quote && comment) comment--; if (buffer[i] == '\\' && !escape && !comment && !quote) escape = 1; else escape = 0; if (buffer[i] == '<' && !escape && !comment && !quote && !bracket) { bracket++; has_bracket = 1; pos_bracket_beg = i+1; } if (buffer[i] == '>' && !escape && !comment && !quote && bracket) { bracket--; pos_bracket_end = i; } if (buffer[i] == ':' && !escape && !comment && !quote) has_group = 1; /* update insert point if not in comment and not on a whitespace */ if (!comment && buffer[i] != ')' && !isspace((unsigned char)buffer[i])) pos_component_end = i; } /* parse error, do not attempt to modify */ if (escape || quote || comment || bracket) return; /* address is group, skip */ if (has_group) return; /* there's an address between brackets, just replace everything brackets */ if (has_bracket) { insert_beg = pos_bracket_beg; insert_end = pos_bracket_end; } else { if (pos_component_end == 0) pos_component_beg = 0; else { for (pos_component_beg = pos_component_end; pos_component_beg >= 0; --pos_component_beg) if (buffer[pos_component_beg] == ')' || isspace(buffer[pos_component_beg])) break; pos_component_beg += 1; pos_component_end += 1; } insert_beg = pos_component_beg; insert_end = pos_component_end; } /* check that masquerade won' t overflow */ address_len = strlen(address); if (strlen(buffer) - (insert_end - insert_beg) + address_len >= len) return; (void)strlcpy(copy, buffer, sizeof copy); (void)strlcpy(copy+insert_beg, address, sizeof (copy) - insert_beg); (void)strlcat(copy, buffer+insert_end, sizeof (copy)); memcpy(buffer, copy, len); } static void header_domain_append_callback(struct smtp_tx *tx, const char *hdr, const char *val) { size_t i, j, linelen; int escape, quote, comment, skip; char buffer[APPEND_DOMAIN_BUFFER_SIZE]; const char *line, *end; if (smtp_message_printf(tx, "%s:", hdr) == -1) return; j = 0; escape = quote = comment = skip = 0; memset(buffer, 0, sizeof buffer); for (line = val; line; line = end) { end = strchr(line, '\n'); if (end) { linelen = end - line; end++; } else linelen = strlen(line); for (i = 0; i < linelen; ++i) { if (line[i] == '(' && !escape && !quote) comment++; if (line[i] == '"' && !escape && !comment) quote = !quote; if (line[i] == ')' && !escape && !quote && comment) comment--; if (line[i] == '\\' && !escape && !comment && !quote) escape = 1; else escape = 0; /* found a separator, buffer contains a full address */ if (line[i] == ',' && !escape && !quote && !comment) { if (!skip && j + strlen(tx->session->listener->hostname) + 1 < sizeof buffer) { header_append_domain_buffer(buffer, tx->session->listener->hostname, sizeof buffer); if (tx->session->flags & SF_AUTHENTICATED && tx->session->listener->sendertable[0] && tx->session->listener->flags & F_MASQUERADE && !(strcasecmp(hdr, "From"))) header_address_rewrite_buffer(buffer, mailaddr_to_text(&tx->evp.sender), sizeof buffer); } if (smtp_message_printf(tx, "%s,", buffer) == -1) return; j = 0; skip = 0; memset(buffer, 0, sizeof buffer); } else { if (skip) { if (smtp_message_printf(tx, "%c", line[i]) == -1) return; } else { buffer[j++] = line[i]; if (j == sizeof (buffer) - 1) { if (smtp_message_printf(tx, "%s", buffer) == -1) return; skip = 1; j = 0; memset(buffer, 0, sizeof buffer); } } } } if (skip) { if (smtp_message_printf(tx, "\n") == -1) return; } else { buffer[j++] = '\n'; if (j == sizeof (buffer) - 1) { if (smtp_message_printf(tx, "%s", buffer) == -1) return; skip = 1; j = 0; memset(buffer, 0, sizeof buffer); } } } /* end of header, if buffer is not empty we'll process it */ if (buffer[0]) { if (j + strlen(tx->session->listener->hostname) + 1 < sizeof buffer) { header_append_domain_buffer(buffer, tx->session->listener->hostname, sizeof buffer); if (tx->session->flags & SF_AUTHENTICATED && tx->session->listener->sendertable[0] && tx->session->listener->flags & F_MASQUERADE && !(strcasecmp(hdr, "From"))) header_address_rewrite_buffer(buffer, mailaddr_to_text(&tx->evp.sender), sizeof buffer); } smtp_message_printf(tx, "%s", buffer); } } static void smtp_session_init(void) { static int init = 0; if (!init) { tree_init(&wait_lka_helo); tree_init(&wait_lka_mail); tree_init(&wait_lka_rcpt); tree_init(&wait_parent_auth); tree_init(&wait_queue_msg); tree_init(&wait_queue_fd); tree_init(&wait_queue_commit); tree_init(&wait_ssl_init); tree_init(&wait_ssl_verify); tree_init(&wait_filters); tree_init(&wait_filter_fd); init = 1; } } int smtp_session(struct listener *listener, int sock, const struct sockaddr_storage *ss, const char *hostname, struct io *io) { struct smtp_session *s; smtp_session_init(); if ((s = calloc(1, sizeof(*s))) == NULL) return (-1); s->id = generate_uid(); s->listener = listener; memmove(&s->ss, ss, sizeof(*ss)); if (io != NULL) s->io = io; else s->io = io_new(); io_set_callback(s->io, smtp_io, s); io_set_fd(s->io, sock); io_set_timeout(s->io, SMTPD_SESSION_TIMEOUT * 1000); io_set_write(s->io); s->state = STATE_NEW; (void)strlcpy(s->smtpname, listener->hostname, sizeof(s->smtpname)); log_trace(TRACE_SMTP, "smtp: %p: connected to listener %p " "[hostname=%s, port=%d, tag=%s]", s, listener, listener->hostname, ntohs(listener->port), listener->tag); /* For local enqueueing, the hostname is already set */ if (hostname) { s->flags |= SF_AUTHENTICATED; /* A bit of a hack */ if (!strcmp(hostname, "localhost")) s->flags |= SF_BOUNCE; (void)strlcpy(s->rdns, hostname, sizeof(s->rdns)); s->fcrdns = 1; smtp_lookup_servername(s); } else { resolver_getnameinfo((struct sockaddr *)&s->ss, NI_NAMEREQD, smtp_getnameinfo_cb, s); } /* session may have been freed by now */ return (0); } static void smtp_getnameinfo_cb(void *arg, int gaierrno, const char *host, const char *serv) { struct smtp_session *s = arg; struct addrinfo hints; if (gaierrno) { (void)strlcpy(s->rdns, "<unknown>", sizeof(s->rdns)); if (gaierrno == EAI_NODATA || gaierrno == EAI_NONAME) s->fcrdns = 0; else { log_warnx("getnameinfo: %s: %s", ss_to_text(&s->ss), gai_strerror(gaierrno)); s->fcrdns = -1; } smtp_lookup_servername(s); return; } (void)strlcpy(s->rdns, host, sizeof(s->rdns)); memset(&hints, 0, sizeof(hints)); hints.ai_family = s->ss.ss_family; hints.ai_socktype = SOCK_STREAM; resolver_getaddrinfo(s->rdns, NULL, &hints, smtp_getaddrinfo_cb, s); } static void smtp_getaddrinfo_cb(void *arg, int gaierrno, struct addrinfo *ai0) { struct smtp_session *s = arg; struct addrinfo *ai; char fwd[64], rev[64]; if (gaierrno) { if (gaierrno == EAI_NODATA || gaierrno == EAI_NONAME) s->fcrdns = 0; else { log_warnx("getaddrinfo: %s: %s", s->rdns, gai_strerror(gaierrno)); s->fcrdns = -1; } } else { strlcpy(rev, ss_to_text(&s->ss), sizeof(rev)); for (ai = ai0; ai; ai = ai->ai_next) { strlcpy(fwd, sa_to_text(ai->ai_addr), sizeof(fwd)); if (!strcmp(fwd, rev)) { s->fcrdns = 1; break; } } freeaddrinfo(ai0); } smtp_lookup_servername(s); } void smtp_session_imsg(struct mproc *p, struct imsg *imsg) { struct smtp_session *s; struct smtp_rcpt *rcpt; char user[SMTPD_MAXMAILADDRSIZE]; char tmp[SMTP_LINE_MAX]; struct msg m; const char *line, *helo; uint64_t reqid, evpid; uint32_t msgid; int status, success; int filter_response; const char *filter_param; uint8_t i; switch (imsg->hdr.type) { case IMSG_SMTP_CHECK_SENDER: m_msg(&m, imsg); m_get_id(&m, &reqid); m_get_int(&m, &status); m_end(&m); s = tree_xpop(&wait_lka_mail, reqid); switch (status) { case LKA_OK: smtp_tx_create_message(s->tx); break; case LKA_PERMFAIL: smtp_tx_free(s->tx); smtp_reply(s, "%d %s", 530, "Sender rejected"); break; case LKA_TEMPFAIL: smtp_tx_free(s->tx); smtp_reply(s, "421 %s Temporary Error", esc_code(ESC_STATUS_TEMPFAIL, ESC_OTHER_MAIL_SYSTEM_STATUS)); break; } return; case IMSG_SMTP_EXPAND_RCPT: m_msg(&m, imsg); m_get_id(&m, &reqid); m_get_int(&m, &status); m_get_string(&m, &line); m_end(&m); s = tree_xpop(&wait_lka_rcpt, reqid); tmp[0] = '\0'; if (s->tx->evp.rcpt.user[0]) { (void)strlcpy(tmp, s->tx->evp.rcpt.user, sizeof tmp); if (s->tx->evp.rcpt.domain[0]) { (void)strlcat(tmp, "@", sizeof tmp); (void)strlcat(tmp, s->tx->evp.rcpt.domain, sizeof tmp); } } switch (status) { case LKA_OK: fatalx("unexpected ok"); case LKA_PERMFAIL: smtp_reply(s, "%s: <%s>", line, tmp); break; case LKA_TEMPFAIL: smtp_reply(s, "%s: <%s>", line, tmp); break; } return; case IMSG_SMTP_LOOKUP_HELO: m_msg(&m, imsg); m_get_id(&m, &reqid); s = tree_xpop(&wait_lka_helo, reqid); m_get_int(&m, &status); if (status == LKA_OK) { m_get_string(&m, &helo); (void)strlcpy(s->smtpname, helo, sizeof(s->smtpname)); } m_end(&m); smtp_connected(s); return; case IMSG_SMTP_MESSAGE_CREATE: m_msg(&m, imsg); m_get_id(&m, &reqid); m_get_int(&m, &success); s = tree_xpop(&wait_queue_msg, reqid); if (success) { m_get_msgid(&m, &msgid); s->tx->msgid = msgid; s->tx->evp.id = msgid_to_evpid(msgid); s->tx->rcptcount = 0; smtp_reply(s, "250 %s Ok", esc_code(ESC_STATUS_OK, ESC_OTHER_STATUS)); } else { smtp_reply(s, "421 %s Temporary Error", esc_code(ESC_STATUS_TEMPFAIL, ESC_OTHER_MAIL_SYSTEM_STATUS)); smtp_tx_free(s->tx); smtp_enter_state(s, STATE_QUIT); } m_end(&m); return; case IMSG_SMTP_MESSAGE_OPEN: m_msg(&m, imsg); m_get_id(&m, &reqid); m_get_int(&m, &success); m_end(&m); s = tree_xpop(&wait_queue_fd, reqid); if (!success || imsg->fd == -1) { if (imsg->fd != -1) close(imsg->fd); smtp_reply(s, "421 %s Temporary Error", esc_code(ESC_STATUS_TEMPFAIL, ESC_OTHER_MAIL_SYSTEM_STATUS)); smtp_enter_state(s, STATE_QUIT); return; } log_debug("smtp: %p: fd %d from queue", s, imsg->fd); if (smtp_message_fd(s->tx, imsg->fd)) { if (!SESSION_DATA_FILTERED(s)) smtp_message_begin(s->tx); else smtp_filter_data_begin(s); } return; case IMSG_FILTER_SMTP_DATA_BEGIN: m_msg(&m, imsg); m_get_id(&m, &reqid); m_get_int(&m, &success); m_end(&m); s = tree_xpop(&wait_filter_fd, reqid); if (!success || imsg->fd == -1) { if (imsg->fd != -1) close(imsg->fd); smtp_reply(s, "421 %s Temporary Error", esc_code(ESC_STATUS_TEMPFAIL, ESC_OTHER_MAIL_SYSTEM_STATUS)); smtp_enter_state(s, STATE_QUIT); return; } log_debug("smtp: %p: fd %d from lka", s, imsg->fd); smtp_filter_fd(s->tx, imsg->fd); smtp_message_begin(s->tx); return; case IMSG_QUEUE_ENVELOPE_SUBMIT: m_msg(&m, imsg); m_get_id(&m, &reqid); m_get_int(&m, &success); s = tree_xget(&wait_lka_rcpt, reqid); if (success) { m_get_evpid(&m, &evpid); s->tx->evp.id = evpid; s->tx->destcount++; smtp_report_tx_envelope(s, s->tx->msgid, evpid); } else s->tx->error = TX_ERROR_ENVELOPE; m_end(&m); return; case IMSG_QUEUE_ENVELOPE_COMMIT: m_msg(&m, imsg); m_get_id(&m, &reqid); m_get_int(&m, &success); m_end(&m); if (!success) fatalx("commit evp failed: not supposed to happen"); s = tree_xpop(&wait_lka_rcpt, reqid); if (s->tx->error) { /* * If an envelope failed, we can't cancel the last * RCPT only so we must cancel the whole transaction * and close the connection. */ smtp_reply(s, "421 %s Temporary failure", esc_code(ESC_STATUS_TEMPFAIL, ESC_OTHER_MAIL_SYSTEM_STATUS)); smtp_enter_state(s, STATE_QUIT); } else { rcpt = xcalloc(1, sizeof(*rcpt)); rcpt->evpid = s->tx->evp.id; rcpt->destcount = s->tx->destcount; rcpt->maddr = s->tx->evp.rcpt; TAILQ_INSERT_TAIL(&s->tx->rcpts, rcpt, entry); s->tx->destcount = 0; s->tx->rcptcount++; smtp_reply(s, "250 %s %s: Recipient ok", esc_code(ESC_STATUS_OK, ESC_DESTINATION_ADDRESS_VALID), esc_description(ESC_DESTINATION_ADDRESS_VALID)); } return; case IMSG_SMTP_MESSAGE_COMMIT: m_msg(&m, imsg); m_get_id(&m, &reqid); m_get_int(&m, &success); m_end(&m); s = tree_xpop(&wait_queue_commit, reqid); if (!success) { smtp_reply(s, "421 %s Temporary failure", esc_code(ESC_STATUS_TEMPFAIL, ESC_OTHER_MAIL_SYSTEM_STATUS)); smtp_tx_free(s->tx); smtp_enter_state(s, STATE_QUIT); return; } smtp_reply(s, "250 %s %08x Message accepted for delivery", esc_code(ESC_STATUS_OK, ESC_OTHER_STATUS), s->tx->msgid); smtp_report_tx_commit(s, s->tx->msgid, s->tx->odatalen); smtp_report_tx_reset(s, s->tx->msgid); log_info("%016"PRIx64" smtp message " "msgid=%08x size=%zu nrcpt=%zu proto=%s", s->id, s->tx->msgid, s->tx->odatalen, s->tx->rcptcount, s->flags & SF_EHLO ? "ESMTP" : "SMTP"); TAILQ_FOREACH(rcpt, &s->tx->rcpts, entry) { log_info("%016"PRIx64" smtp envelope " "evpid=%016"PRIx64" from=<%s%s%s> to=<%s%s%s>", s->id, rcpt->evpid, s->tx->evp.sender.user, s->tx->evp.sender.user[0] == '\0' ? "" : "@", s->tx->evp.sender.domain, rcpt->maddr.user, rcpt->maddr.user[0] == '\0' ? "" : "@", rcpt->maddr.domain); } smtp_tx_free(s->tx); s->mailcount++; smtp_enter_state(s, STATE_HELO); return; case IMSG_SMTP_AUTHENTICATE: m_msg(&m, imsg); m_get_id(&m, &reqid); m_get_int(&m, &success); m_end(&m); s = tree_xpop(&wait_parent_auth, reqid); strnvis(user, s->username, sizeof user, VIS_WHITE | VIS_SAFE); if (success == LKA_OK) { log_info("%016"PRIx64" smtp " "authentication user=%s " "result=ok", s->id, user); s->flags |= SF_AUTHENTICATED; smtp_report_link_auth(s, user, "pass"); smtp_reply(s, "235 %s Authentication succeeded", esc_code(ESC_STATUS_OK, ESC_OTHER_STATUS)); } else if (success == LKA_PERMFAIL) { log_info("%016"PRIx64" smtp " "authentication user=%s " "result=permfail", s->id, user); smtp_report_link_auth(s, user, "fail"); smtp_auth_failure_pause(s); return; } else if (success == LKA_TEMPFAIL) { log_info("%016"PRIx64" smtp " "authentication user=%s " "result=tempfail", s->id, user); smtp_report_link_auth(s, user, "error"); smtp_reply(s, "421 %s Temporary failure", esc_code(ESC_STATUS_TEMPFAIL, ESC_OTHER_MAIL_SYSTEM_STATUS)); } else fatalx("bad lka response"); smtp_enter_state(s, STATE_HELO); return; case IMSG_FILTER_SMTP_PROTOCOL: m_msg(&m, imsg); m_get_id(&m, &reqid); m_get_int(&m, &filter_response); if (filter_response != FILTER_PROCEED && filter_response != FILTER_JUNK) m_get_string(&m, &filter_param); else filter_param = NULL; m_end(&m); s = tree_xpop(&wait_filters, reqid); switch (filter_response) { case FILTER_REJECT: case FILTER_DISCONNECT: if (!valid_smtp_response(filter_param) || (filter_param[0] != '4' && filter_param[0] != '5')) filter_param = "421 Internal server error"; if (!strncmp(filter_param, "421", 3)) filter_response = FILTER_DISCONNECT; smtp_report_filter_response(s, s->filter_phase, filter_response, filter_param); smtp_reply(s, "%s", filter_param); if (filter_response == FILTER_DISCONNECT) smtp_enter_state(s, STATE_QUIT); else if (s->filter_phase == FILTER_COMMIT) smtp_proceed_rollback(s, NULL); break; case FILTER_JUNK: if (s->tx) s->tx->junk = 1; else s->junk = 1; /* fallthrough */ case FILTER_PROCEED: filter_param = s->filter_param; /* fallthrough */ case FILTER_REWRITE: smtp_report_filter_response(s, s->filter_phase, filter_response, filter_param == s->filter_param ? NULL : filter_param); if (s->filter_phase == FILTER_CONNECT) { smtp_proceed_connected(s); return; } for (i = 0; i < nitems(commands); ++i) if (commands[i].filter_phase == s->filter_phase) { if (filter_response == FILTER_REWRITE) if (!commands[i].check(s, filter_param)) break; commands[i].proceed(s, filter_param); break; } break; } return; } log_warnx("smtp_session_imsg: unexpected %s imsg", imsg_to_str(imsg->hdr.type)); fatalx(NULL); } static void smtp_tls_verified(struct smtp_session *s) { X509 *x; x = SSL_get_peer_certificate(io_tls(s->io)); if (x) { log_info("%016"PRIx64" smtp " "client-cert-check result=\"%s\"", s->id, (s->flags & SF_VERIFIED) ? "success" : "failure"); X509_free(x); } if (s->listener->flags & F_SMTPS) { stat_increment("smtp.smtps", 1); io_set_write(s->io); smtp_send_banner(s); } else { stat_increment("smtp.tls", 1); smtp_enter_state(s, STATE_HELO); } } static void smtp_io(struct io *io, int evt, void *arg) { struct smtp_session *s = arg; char *line; size_t len; int eom; log_trace(TRACE_IO, "smtp: %p: %s %s", s, io_strevent(evt), io_strio(io)); switch (evt) { case IO_TLSREADY: log_info("%016"PRIx64" smtp tls ciphers=%s", s->id, ssl_to_text(io_tls(s->io))); smtp_report_link_tls(s, ssl_to_text(io_tls(s->io))); s->flags |= SF_SECURE; s->helo[0] = '\0'; smtp_cert_verify(s); break; case IO_DATAIN: nextline: line = io_getline(s->io, &len); if ((line == NULL && io_datalen(s->io) >= SMTP_LINE_MAX) || (line && len >= SMTP_LINE_MAX)) { s->flags |= SF_BADINPUT; smtp_reply(s, "500 %s Line too long", esc_code(ESC_STATUS_PERMFAIL, ESC_OTHER_STATUS)); smtp_enter_state(s, STATE_QUIT); io_set_write(io); return; } /* No complete line received */ if (line == NULL) return; /* Message body */ eom = 0; if (s->state == STATE_BODY) { if (strcmp(line, ".")) { s->tx->datain += strlen(line) + 1; if (s->tx->datain > env->sc_maxsize) s->tx->error = TX_ERROR_SIZE; } eom = (s->tx->filter == NULL) ? smtp_tx_dataline(s->tx, line) : smtp_tx_filtered_dataline(s->tx, line); if (eom == 0) goto nextline; } /* Pipelining not supported */ if (io_datalen(s->io)) { s->flags |= SF_BADINPUT; smtp_reply(s, "500 %s %s: Pipelining not supported", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); smtp_enter_state(s, STATE_QUIT); io_set_write(io); return; } if (eom) { io_set_write(io); if (s->tx->filter == NULL) smtp_tx_eom(s->tx); return; } /* Must be a command */ if (strlcpy(s->cmd, line, sizeof(s->cmd)) >= sizeof(s->cmd)) { s->flags |= SF_BADINPUT; smtp_reply(s, "500 %s Command line too long", esc_code(ESC_STATUS_PERMFAIL, ESC_OTHER_STATUS)); smtp_enter_state(s, STATE_QUIT); io_set_write(io); return; } io_set_write(io); smtp_command(s, line); break; case IO_LOWAT: if (s->state == STATE_QUIT) { log_info("%016"PRIx64" smtp disconnected " "reason=quit", s->id); smtp_free(s, "done"); break; } /* Wait for the client to start tls */ if (s->state == STATE_TLS) { smtp_cert_init(s); break; } io_set_read(io); break; case IO_TIMEOUT: log_info("%016"PRIx64" smtp disconnected " "reason=timeout", s->id); smtp_report_timeout(s); smtp_free(s, "timeout"); break; case IO_DISCONNECTED: log_info("%016"PRIx64" smtp disconnected " "reason=disconnect", s->id); smtp_free(s, "disconnected"); break; case IO_ERROR: log_info("%016"PRIx64" smtp disconnected " "reason=\"io-error: %s\"", s->id, io_error(io)); smtp_free(s, "IO error"); break; default: fatalx("smtp_io()"); } } static void smtp_command(struct smtp_session *s, char *line) { char *args; int cmd, i; log_trace(TRACE_SMTP, "smtp: %p: <<< %s", s, line); /* * These states are special. */ if (s->state == STATE_AUTH_INIT) { smtp_report_protocol_client(s, "********"); smtp_rfc4954_auth_plain(s, line); return; } if (s->state == STATE_AUTH_USERNAME || s->state == STATE_AUTH_PASSWORD) { smtp_report_protocol_client(s, "********"); smtp_rfc4954_auth_login(s, line); return; } if (s->state == STATE_HELO && strncasecmp(line, "AUTH PLAIN ", 11) == 0) smtp_report_protocol_client(s, "AUTH PLAIN ********"); else smtp_report_protocol_client(s, line); /* * Unlike other commands, "mail from" and "rcpt to" contain a * space in the command name. */ if (strncasecmp("mail from:", line, 10) == 0 || strncasecmp("rcpt to:", line, 8) == 0) args = strchr(line, ':'); else args = strchr(line, ' '); if (args) { *args++ = '\0'; while (isspace((unsigned char)*args)) args++; } cmd = -1; for (i = 0; commands[i].code != -1; i++) if (!strcasecmp(line, commands[i].cmd)) { cmd = commands[i].code; break; } s->last_cmd = cmd; switch (cmd) { /* * INIT */ case CMD_HELO: if (!smtp_check_helo(s, args)) break; smtp_filter_phase(FILTER_HELO, s, args); break; case CMD_EHLO: if (!smtp_check_ehlo(s, args)) break; smtp_filter_phase(FILTER_EHLO, s, args); break; /* * SETUP */ case CMD_STARTTLS: if (!smtp_check_starttls(s, args)) break; smtp_filter_phase(FILTER_STARTTLS, s, NULL); break; case CMD_AUTH: if (!smtp_check_auth(s, args)) break; smtp_filter_phase(FILTER_AUTH, s, args); break; case CMD_MAIL_FROM: if (!smtp_check_mail_from(s, args)) break; smtp_filter_phase(FILTER_MAIL_FROM, s, args); break; /* * TRANSACTION */ case CMD_RCPT_TO: if (!smtp_check_rcpt_to(s, args)) break; smtp_filter_phase(FILTER_RCPT_TO, s, args); break; case CMD_RSET: if (!smtp_check_rset(s, args)) break; smtp_filter_phase(FILTER_RSET, s, NULL); break; case CMD_DATA: if (!smtp_check_data(s, args)) break; smtp_filter_phase(FILTER_DATA, s, NULL); break; /* * ANY */ case CMD_QUIT: if (!smtp_check_noparam(s, args)) break; smtp_filter_phase(FILTER_QUIT, s, NULL); break; case CMD_NOOP: if (!smtp_check_noparam(s, args)) break; smtp_filter_phase(FILTER_NOOP, s, NULL); break; case CMD_HELP: if (!smtp_check_noparam(s, args)) break; smtp_proceed_help(s, NULL); break; case CMD_WIZ: if (!smtp_check_noparam(s, args)) break; smtp_proceed_wiz(s, NULL); break; default: smtp_reply(s, "500 %s %s: Command unrecognized", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); break; } } static int smtp_check_rset(struct smtp_session *s, const char *args) { if (!smtp_check_noparam(s, args)) return 0; if (s->helo[0] == '\0') { smtp_reply(s, "503 %s %s: Command not allowed at this point.", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } return 1; } static int smtp_check_helo(struct smtp_session *s, const char *args) { if (!s->banner_sent) { smtp_reply(s, "503 %s %s: Command not allowed at this point.", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (s->helo[0]) { smtp_reply(s, "503 %s %s: Already identified", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (args == NULL) { smtp_reply(s, "501 %s %s: HELO requires domain name", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (!valid_domainpart(args)) { smtp_reply(s, "501 %s %s: Invalid domain name", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND_ARGUMENTS), esc_description(ESC_INVALID_COMMAND_ARGUMENTS)); return 0; } return 1; } static int smtp_check_ehlo(struct smtp_session *s, const char *args) { if (!s->banner_sent) { smtp_reply(s, "503 %s %s: Command not allowed at this point.", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (s->helo[0]) { smtp_reply(s, "503 %s %s: Already identified", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (args == NULL) { smtp_reply(s, "501 %s %s: EHLO requires domain name", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (!valid_domainpart(args)) { smtp_reply(s, "501 %s %s: Invalid domain name", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND_ARGUMENTS), esc_description(ESC_INVALID_COMMAND_ARGUMENTS)); return 0; } return 1; } static int smtp_check_auth(struct smtp_session *s, const char *args) { if (s->helo[0] == '\0' || s->tx) { smtp_reply(s, "503 %s %s: Command not allowed at this point.", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (s->flags & SF_AUTHENTICATED) { smtp_reply(s, "503 %s %s: Already authenticated", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (!ADVERTISE_AUTH(s)) { smtp_reply(s, "503 %s %s: Command not supported", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (args == NULL) { smtp_reply(s, "501 %s %s: No parameters given", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND_ARGUMENTS), esc_description(ESC_INVALID_COMMAND_ARGUMENTS)); return 0; } return 1; } static int smtp_check_starttls(struct smtp_session *s, const char *args) { if (s->helo[0] == '\0' || s->tx) { smtp_reply(s, "503 %s %s: Command not allowed at this point.", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (!(s->listener->flags & F_STARTTLS)) { smtp_reply(s, "503 %s %s: Command not supported", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (s->flags & SF_SECURE) { smtp_reply(s, "503 %s %s: Channel already secured", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (args != NULL) { smtp_reply(s, "501 %s %s: No parameters allowed", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND_ARGUMENTS), esc_description(ESC_INVALID_COMMAND_ARGUMENTS)); return 0; } return 1; } static int smtp_check_mail_from(struct smtp_session *s, const char *args) { char *copy; char tmp[SMTP_LINE_MAX]; struct mailaddr sender; (void)strlcpy(tmp, args, sizeof tmp); copy = tmp; if (s->helo[0] == '\0' || s->tx) { smtp_reply(s, "503 %s %s: Command not allowed at this point.", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (s->listener->flags & F_STARTTLS_REQUIRE && !(s->flags & SF_SECURE)) { smtp_reply(s, "530 %s %s: Must issue a STARTTLS command first", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (s->listener->flags & F_AUTH_REQUIRE && !(s->flags & SF_AUTHENTICATED)) { smtp_reply(s, "530 %s %s: Must issue an AUTH command first", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (s->mailcount >= env->sc_session_max_mails) { /* we can pretend we had too many recipients */ smtp_reply(s, "452 %s %s: Too many messages sent", esc_code(ESC_STATUS_TEMPFAIL, ESC_TOO_MANY_RECIPIENTS), esc_description(ESC_TOO_MANY_RECIPIENTS)); return 0; } if (smtp_mailaddr(&sender, copy, 1, &copy, s->smtpname) == 0) { smtp_reply(s, "553 %s Sender address syntax error", esc_code(ESC_STATUS_PERMFAIL, ESC_OTHER_ADDRESS_STATUS)); return 0; } return 1; } static int smtp_check_rcpt_to(struct smtp_session *s, const char *args) { char *copy; char tmp[SMTP_LINE_MAX]; (void)strlcpy(tmp, args, sizeof tmp); copy = tmp; if (s->tx == NULL) { smtp_reply(s, "503 %s %s: Command not allowed at this point.", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (s->tx->rcptcount >= env->sc_session_max_rcpt) { smtp_reply(s->tx->session, "451 %s %s: Too many recipients", esc_code(ESC_STATUS_TEMPFAIL, ESC_TOO_MANY_RECIPIENTS), esc_description(ESC_TOO_MANY_RECIPIENTS)); return 0; } if (smtp_mailaddr(&s->tx->evp.rcpt, copy, 0, &copy, s->tx->session->smtpname) == 0) { smtp_reply(s->tx->session, "501 %s Recipient address syntax error", esc_code(ESC_STATUS_PERMFAIL, ESC_BAD_DESTINATION_MAILBOX_ADDRESS_SYNTAX)); return 0; } return 1; } static int smtp_check_data(struct smtp_session *s, const char *args) { if (!smtp_check_noparam(s, args)) return 0; if (s->tx == NULL) { smtp_reply(s, "503 %s %s: Command not allowed at this point.", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); return 0; } if (s->tx->rcptcount == 0) { smtp_reply(s, "503 %s %s: No recipient specified", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND_ARGUMENTS), esc_description(ESC_INVALID_COMMAND_ARGUMENTS)); return 0; } return 1; } static int smtp_check_noparam(struct smtp_session *s, const char *args) { if (args != NULL) { smtp_reply(s, "500 %s %s: command does not accept arguments.", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND_ARGUMENTS), esc_description(ESC_INVALID_COMMAND_ARGUMENTS)); return 0; } return 1; } static void smtp_query_filters(enum filter_phase phase, struct smtp_session *s, const char *args) { m_create(p_lka, IMSG_FILTER_SMTP_PROTOCOL, 0, 0, -1); m_add_id(p_lka, s->id); m_add_int(p_lka, phase); m_add_string(p_lka, args); m_close(p_lka); tree_xset(&wait_filters, s->id, s); } static void smtp_filter_begin(struct smtp_session *s) { if (!SESSION_FILTERED(s)) return; m_create(p_lka, IMSG_FILTER_SMTP_BEGIN, 0, 0, -1); m_add_id(p_lka, s->id); m_add_string(p_lka, s->listener->filter_name); m_close(p_lka); } static void smtp_filter_end(struct smtp_session *s) { if (!SESSION_FILTERED(s)) return; m_create(p_lka, IMSG_FILTER_SMTP_END, 0, 0, -1); m_add_id(p_lka, s->id); m_close(p_lka); } static void smtp_filter_data_begin(struct smtp_session *s) { if (!SESSION_FILTERED(s)) return; m_create(p_lka, IMSG_FILTER_SMTP_DATA_BEGIN, 0, 0, -1); m_add_id(p_lka, s->id); m_close(p_lka); tree_xset(&wait_filter_fd, s->id, s); } static void smtp_filter_data_end(struct smtp_session *s) { if (!SESSION_FILTERED(s)) return; if (s->tx->filter == NULL) return; io_free(s->tx->filter); s->tx->filter = NULL; m_create(p_lka, IMSG_FILTER_SMTP_DATA_END, 0, 0, -1); m_add_id(p_lka, s->id); m_close(p_lka); } static void smtp_filter_phase(enum filter_phase phase, struct smtp_session *s, const char *param) { uint8_t i; s->filter_phase = phase; s->filter_param = param; if (SESSION_FILTERED(s)) { smtp_query_filters(phase, s, param ? param : ""); return; } if (s->filter_phase == FILTER_CONNECT) { smtp_proceed_connected(s); return; } for (i = 0; i < nitems(commands); ++i) if (commands[i].filter_phase == s->filter_phase) { commands[i].proceed(s, param); break; } } static void smtp_proceed_rset(struct smtp_session *s, const char *args) { smtp_reply(s, "250 %s Reset state", esc_code(ESC_STATUS_OK, ESC_OTHER_STATUS)); if (s->tx) { if (s->tx->msgid) smtp_tx_rollback(s->tx); smtp_tx_free(s->tx); } } static void smtp_proceed_helo(struct smtp_session *s, const char *args) { (void)strlcpy(s->helo, args, sizeof(s->helo)); s->flags &= SF_SECURE | SF_AUTHENTICATED | SF_VERIFIED; smtp_report_link_identify(s, "HELO", s->helo); smtp_enter_state(s, STATE_HELO); smtp_reply(s, "250 %s Hello %s %s%s%s, pleased to meet you", s->smtpname, s->helo, s->ss.ss_family == AF_INET6 ? "" : "[", ss_to_text(&s->ss), s->ss.ss_family == AF_INET6 ? "" : "]"); } static void smtp_proceed_ehlo(struct smtp_session *s, const char *args) { (void)strlcpy(s->helo, args, sizeof(s->helo)); s->flags &= SF_SECURE | SF_AUTHENTICATED | SF_VERIFIED; s->flags |= SF_EHLO; s->flags |= SF_8BITMIME; smtp_report_link_identify(s, "EHLO", s->helo); smtp_enter_state(s, STATE_HELO); smtp_reply(s, "250-%s Hello %s %s%s%s, pleased to meet you", s->smtpname, s->helo, s->ss.ss_family == AF_INET6 ? "" : "[", ss_to_text(&s->ss), s->ss.ss_family == AF_INET6 ? "" : "]"); smtp_reply(s, "250-8BITMIME"); smtp_reply(s, "250-ENHANCEDSTATUSCODES"); smtp_reply(s, "250-SIZE %zu", env->sc_maxsize); if (ADVERTISE_EXT_DSN(s)) smtp_reply(s, "250-DSN"); if (ADVERTISE_TLS(s)) smtp_reply(s, "250-STARTTLS"); if (ADVERTISE_AUTH(s)) smtp_reply(s, "250-AUTH PLAIN LOGIN"); smtp_reply(s, "250 HELP"); } static void smtp_proceed_auth(struct smtp_session *s, const char *args) { char tmp[SMTP_LINE_MAX]; char *eom, *method; (void)strlcpy(tmp, args, sizeof tmp); method = tmp; eom = strchr(tmp, ' '); if (eom == NULL) eom = strchr(tmp, '\t'); if (eom != NULL) *eom++ = '\0'; if (strcasecmp(method, "PLAIN") == 0) smtp_rfc4954_auth_plain(s, eom); else if (strcasecmp(method, "LOGIN") == 0) smtp_rfc4954_auth_login(s, eom); else smtp_reply(s, "504 %s %s: AUTH method \"%s\" not supported", esc_code(ESC_STATUS_PERMFAIL, ESC_SECURITY_FEATURES_NOT_SUPPORTED), esc_description(ESC_SECURITY_FEATURES_NOT_SUPPORTED), method); } static void smtp_proceed_starttls(struct smtp_session *s, const char *args) { smtp_reply(s, "220 %s Ready to start TLS", esc_code(ESC_STATUS_OK, ESC_OTHER_STATUS)); smtp_enter_state(s, STATE_TLS); } static void smtp_proceed_mail_from(struct smtp_session *s, const char *args) { char *copy; char tmp[SMTP_LINE_MAX]; (void)strlcpy(tmp, args, sizeof tmp); copy = tmp; if (!smtp_tx(s)) { smtp_reply(s, "421 %s Temporary Error", esc_code(ESC_STATUS_TEMPFAIL, ESC_OTHER_MAIL_SYSTEM_STATUS)); smtp_enter_state(s, STATE_QUIT); return; } if (smtp_mailaddr(&s->tx->evp.sender, copy, 1, &copy, s->smtpname) == 0) { smtp_reply(s, "553 %s Sender address syntax error", esc_code(ESC_STATUS_PERMFAIL, ESC_OTHER_ADDRESS_STATUS)); smtp_tx_free(s->tx); return; } smtp_tx_mail_from(s->tx, args); } static void smtp_proceed_rcpt_to(struct smtp_session *s, const char *args) { smtp_tx_rcpt_to(s->tx, args); } static void smtp_proceed_data(struct smtp_session *s, const char *args) { smtp_tx_open_message(s->tx); } static void smtp_proceed_quit(struct smtp_session *s, const char *args) { smtp_reply(s, "221 %s Bye", esc_code(ESC_STATUS_OK, ESC_OTHER_STATUS)); smtp_enter_state(s, STATE_QUIT); } static void smtp_proceed_noop(struct smtp_session *s, const char *args) { smtp_reply(s, "250 %s Ok", esc_code(ESC_STATUS_OK, ESC_OTHER_STATUS)); } static void smtp_proceed_help(struct smtp_session *s, const char *args) { const char *code = esc_code(ESC_STATUS_OK, ESC_OTHER_STATUS); smtp_reply(s, "214-%s This is " SMTPD_NAME, code); smtp_reply(s, "214-%s To report bugs in the implementation, " "please contact bugs@openbsd.org", code); smtp_reply(s, "214-%s with full details", code); smtp_reply(s, "214 %s End of HELP info", code); } static void smtp_proceed_wiz(struct smtp_session *s, const char *args) { smtp_reply(s, "500 %s %s: this feature is not supported yet ;-)", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND), esc_description(ESC_INVALID_COMMAND)); } static void smtp_proceed_commit(struct smtp_session *s, const char *args) { smtp_message_end(s->tx); } static void smtp_proceed_rollback(struct smtp_session *s, const char *args) { struct smtp_tx *tx; tx = s->tx; fclose(tx->ofile); tx->ofile = NULL; smtp_tx_rollback(tx); smtp_tx_free(tx); smtp_enter_state(s, STATE_HELO); } static void smtp_rfc4954_auth_plain(struct smtp_session *s, char *arg) { char buf[1024], *user, *pass; int len; switch (s->state) { case STATE_HELO: if (arg == NULL) { smtp_enter_state(s, STATE_AUTH_INIT); smtp_reply(s, "334 "); return; } smtp_enter_state(s, STATE_AUTH_INIT); /* FALLTHROUGH */ case STATE_AUTH_INIT: /* String is not NUL terminated, leave room. */ if ((len = base64_decode(arg, (unsigned char *)buf, sizeof(buf) - 1)) == -1) goto abort; /* buf is a byte string, NUL terminate. */ buf[len] = '\0'; /* * Skip "foo" in "foo\0user\0pass", if present. */ user = memchr(buf, '\0', len); if (user == NULL || user >= buf + len - 2) goto abort; user++; /* skip NUL */ if (strlcpy(s->username, user, sizeof(s->username)) >= sizeof(s->username)) goto abort; pass = memchr(user, '\0', len - (user - buf)); if (pass == NULL || pass >= buf + len - 2) goto abort; pass++; /* skip NUL */ m_create(p_lka, IMSG_SMTP_AUTHENTICATE, 0, 0, -1); m_add_id(p_lka, s->id); m_add_string(p_lka, s->listener->authtable); m_add_string(p_lka, user); m_add_string(p_lka, pass); m_close(p_lka); tree_xset(&wait_parent_auth, s->id, s); return; default: fatal("smtp_rfc4954_auth_plain: unknown state"); } abort: smtp_reply(s, "501 %s %s: Syntax error", esc_code(ESC_STATUS_PERMFAIL, ESC_SYNTAX_ERROR), esc_description(ESC_SYNTAX_ERROR)); smtp_enter_state(s, STATE_HELO); } static void smtp_rfc4954_auth_login(struct smtp_session *s, char *arg) { char buf[LINE_MAX]; switch (s->state) { case STATE_HELO: smtp_enter_state(s, STATE_AUTH_USERNAME); if (arg != NULL && *arg != '\0') { smtp_rfc4954_auth_login(s, arg); return; } smtp_reply(s, "334 VXNlcm5hbWU6"); return; case STATE_AUTH_USERNAME: memset(s->username, 0, sizeof(s->username)); if (base64_decode(arg, (unsigned char *)s->username, sizeof(s->username) - 1) == -1) goto abort; smtp_enter_state(s, STATE_AUTH_PASSWORD); smtp_reply(s, "334 UGFzc3dvcmQ6"); return; case STATE_AUTH_PASSWORD: memset(buf, 0, sizeof(buf)); if (base64_decode(arg, (unsigned char *)buf, sizeof(buf)-1) == -1) goto abort; m_create(p_lka, IMSG_SMTP_AUTHENTICATE, 0, 0, -1); m_add_id(p_lka, s->id); m_add_string(p_lka, s->listener->authtable); m_add_string(p_lka, s->username); m_add_string(p_lka, buf); m_close(p_lka); tree_xset(&wait_parent_auth, s->id, s); return; default: fatal("smtp_rfc4954_auth_login: unknown state"); } abort: smtp_reply(s, "501 %s %s: Syntax error", esc_code(ESC_STATUS_PERMFAIL, ESC_SYNTAX_ERROR), esc_description(ESC_SYNTAX_ERROR)); smtp_enter_state(s, STATE_HELO); } static void smtp_lookup_servername(struct smtp_session *s) { if (s->listener->hostnametable[0]) { m_create(p_lka, IMSG_SMTP_LOOKUP_HELO, 0, 0, -1); m_add_id(p_lka, s->id); m_add_string(p_lka, s->listener->hostnametable); m_add_sockaddr(p_lka, (struct sockaddr*)&s->listener->ss); m_close(p_lka); tree_xset(&wait_lka_helo, s->id, s); return; } smtp_connected(s); } static void smtp_connected(struct smtp_session *s) { smtp_enter_state(s, STATE_CONNECTED); log_info("%016"PRIx64" smtp connected address=%s host=%s", s->id, ss_to_text(&s->ss), s->rdns); smtp_filter_begin(s); smtp_report_link_connect(s, s->rdns, s->fcrdns, &s->ss, &s->listener->ss); smtp_filter_phase(FILTER_CONNECT, s, ss_to_text(&s->ss)); } static void smtp_proceed_connected(struct smtp_session *s) { if (s->listener->flags & F_SMTPS) smtp_cert_init(s); else smtp_send_banner(s); } static void smtp_send_banner(struct smtp_session *s) { smtp_reply(s, "220 %s ESMTP %s", s->smtpname, SMTPD_NAME); s->banner_sent = 1; smtp_report_link_greeting(s, s->smtpname); } void smtp_enter_state(struct smtp_session *s, int newstate) { log_trace(TRACE_SMTP, "smtp: %p: %s -> %s", s, smtp_strstate(s->state), smtp_strstate(newstate)); s->state = newstate; } static void smtp_reply(struct smtp_session *s, char *fmt, ...) { va_list ap; int n; char buf[LINE_MAX*2], tmp[LINE_MAX*2]; va_start(ap, fmt); n = vsnprintf(buf, sizeof buf, fmt, ap); va_end(ap); if (n < 0) fatalx("smtp_reply: response format error"); if (n < 4) fatalx("smtp_reply: response too short"); if (n >= (int)sizeof buf) { /* only first three bytes are used by SMTP logic, * so if _our_ reply does not fit entirely in the * buffer, it's ok to truncate. */ } log_trace(TRACE_SMTP, "smtp: %p: >>> %s", s, buf); smtp_report_protocol_server(s, buf); switch (buf[0]) { case '2': if (s->tx) { if (s->last_cmd == CMD_MAIL_FROM) { smtp_report_tx_begin(s, s->tx->msgid); smtp_report_tx_mail(s, s->tx->msgid, s->cmd + 10, 1); } else if (s->last_cmd == CMD_RCPT_TO) smtp_report_tx_rcpt(s, s->tx->msgid, s->cmd + 8, 1); } break; case '3': if (s->tx) { if (s->last_cmd == CMD_DATA) smtp_report_tx_data(s, s->tx->msgid, 1); } break; case '5': case '4': /* do not report smtp_tx_mail/smtp_tx_rcpt errors * if they happened outside of a transaction. */ if (s->tx) { if (s->last_cmd == CMD_MAIL_FROM) smtp_report_tx_mail(s, s->tx->msgid, s->cmd + 10, buf[0] == '4' ? -1 : 0); else if (s->last_cmd == CMD_RCPT_TO) smtp_report_tx_rcpt(s, s->tx->msgid, s->cmd + 8, buf[0] == '4' ? -1 : 0); else if (s->last_cmd == CMD_DATA && s->tx->rcptcount) smtp_report_tx_data(s, s->tx->msgid, buf[0] == '4' ? -1 : 0); } if (s->flags & SF_BADINPUT) { log_info("%016"PRIx64" smtp " "bad-input result=\"%.*s\"", s->id, n, buf); } else if (s->state == STATE_AUTH_INIT) { log_info("%016"PRIx64" smtp " "failed-command " "command=\"AUTH PLAIN (...)\" result=\"%.*s\"", s->id, n, buf); } else if (s->state == STATE_AUTH_USERNAME) { log_info("%016"PRIx64" smtp " "failed-command " "command=\"AUTH LOGIN (username)\" result=\"%.*s\"", s->id, n, buf); } else if (s->state == STATE_AUTH_PASSWORD) { log_info("%016"PRIx64" smtp " "failed-command " "command=\"AUTH LOGIN (password)\" result=\"%.*s\"", s->id, n, buf); } else { strnvis(tmp, s->cmd, sizeof tmp, VIS_SAFE | VIS_CSTYLE); log_info("%016"PRIx64" smtp " "failed-command command=\"%s\" " "result=\"%.*s\"", s->id, tmp, n, buf); } break; } io_xprintf(s->io, "%s\r\n", buf); } static void smtp_free(struct smtp_session *s, const char * reason) { if (s->tx) { if (s->tx->msgid) smtp_tx_rollback(s->tx); smtp_tx_free(s->tx); } smtp_report_link_disconnect(s); smtp_filter_end(s); if (s->flags & SF_SECURE && s->listener->flags & F_SMTPS) stat_decrement("smtp.smtps", 1); if (s->flags & SF_SECURE && s->listener->flags & F_STARTTLS) stat_decrement("smtp.tls", 1); io_free(s->io); free(s); smtp_collect(); } static int smtp_mailaddr(struct mailaddr *maddr, char *line, int mailfrom, char **args, const char *domain) { char *p, *e; if (line == NULL) return (0); if (*line != '<') return (0); e = strchr(line, '>'); if (e == NULL) return (0); *e++ = '\0'; while (*e == ' ') e++; *args = e; if (!text_to_mailaddr(maddr, line + 1)) return (0); p = strchr(maddr->user, ':'); if (p != NULL) { p++; memmove(maddr->user, p, strlen(p) + 1); } if (!valid_localpart(maddr->user) || !valid_domainpart(maddr->domain)) { /* accept empty return-path in MAIL FROM, required for bounces */ if (mailfrom && maddr->user[0] == '\0' && maddr->domain[0] == '\0') return (1); /* no user-part, reject */ if (maddr->user[0] == '\0') return (0); /* no domain, local user */ if (maddr->domain[0] == '\0') { (void)strlcpy(maddr->domain, domain, sizeof(maddr->domain)); return (1); } return (0); } return (1); } static void smtp_cert_init(struct smtp_session *s) { const char *name; int fallback; if (s->listener->pki_name[0]) { name = s->listener->pki_name; fallback = 0; } else { name = s->smtpname; fallback = 1; } if (cert_init(name, fallback, smtp_cert_init_cb, s)) tree_xset(&wait_ssl_init, s->id, s); } static void smtp_cert_init_cb(void *arg, int status, const char *name, const void *cert, size_t cert_len) { struct smtp_session *s = arg; void *ssl, *ssl_ctx; tree_pop(&wait_ssl_init, s->id); if (status == CA_FAIL) { log_info("%016"PRIx64" smtp disconnected " "reason=ca-failure", s->id); smtp_free(s, "CA failure"); return; } ssl_ctx = dict_get(env->sc_ssl_dict, name); ssl = ssl_smtp_init(ssl_ctx, s->listener->flags & F_TLS_VERIFY); io_set_read(s->io); io_start_tls(s->io, ssl); } static void smtp_cert_verify(struct smtp_session *s) { const char *name; int fallback; if (s->listener->ca_name[0]) { name = s->listener->ca_name; fallback = 0; } else { name = s->smtpname; fallback = 1; } if (cert_verify(io_tls(s->io), name, fallback, smtp_cert_verify_cb, s)) { tree_xset(&wait_ssl_verify, s->id, s); io_pause(s->io, IO_IN); } } static void smtp_cert_verify_cb(void *arg, int status) { struct smtp_session *s = arg; const char *reason = NULL; int resume; resume = tree_pop(&wait_ssl_verify, s->id) != NULL; switch (status) { case CERT_OK: reason = "cert-ok"; s->flags |= SF_VERIFIED; break; case CERT_NOCA: reason = "no-ca"; break; case CERT_NOCERT: reason = "no-client-cert"; break; case CERT_INVALID: reason = "cert-invalid"; break; default: reason = "cert-check-failed"; break; } log_debug("smtp: %p: smtp_cert_verify_cb: %s", s, reason); if (!(s->flags & SF_VERIFIED) && (s->listener->flags & F_TLS_VERIFY)) { log_info("%016"PRIx64" smtp disconnected " " reason=%s", s->id, reason); smtp_free(s, "SSL certificate check failed"); return; } smtp_tls_verified(s); if (resume) io_resume(s->io, IO_IN); } static void smtp_auth_failure_resume(int fd, short event, void *p) { struct smtp_session *s = p; smtp_reply(s, "535 Authentication failed"); smtp_enter_state(s, STATE_HELO); } static void smtp_auth_failure_pause(struct smtp_session *s) { struct timeval tv; tv.tv_sec = 0; tv.tv_usec = arc4random_uniform(1000000); log_trace(TRACE_SMTP, "smtp: timing-attack protection triggered, " "will defer answer for %lu microseconds", tv.tv_usec); evtimer_set(&s->pause, smtp_auth_failure_resume, s); evtimer_add(&s->pause, &tv); } static int smtp_tx(struct smtp_session *s) { struct smtp_tx *tx; tx = calloc(1, sizeof(*tx)); if (tx == NULL) return 0; TAILQ_INIT(&tx->rcpts); s->tx = tx; tx->session = s; /* setup the envelope */ tx->evp.ss = s->ss; (void)strlcpy(tx->evp.tag, s->listener->tag, sizeof(tx->evp.tag)); (void)strlcpy(tx->evp.smtpname, s->smtpname, sizeof(tx->evp.smtpname)); (void)strlcpy(tx->evp.hostname, s->rdns, sizeof tx->evp.hostname); (void)strlcpy(tx->evp.helo, s->helo, sizeof(tx->evp.helo)); (void)strlcpy(tx->evp.username, s->username, sizeof(tx->evp.username)); if (s->flags & SF_BOUNCE) tx->evp.flags |= EF_BOUNCE; if (s->flags & SF_AUTHENTICATED) tx->evp.flags |= EF_AUTHENTICATED; if ((tx->parser = rfc5322_parser_new()) == NULL) { free(tx); return 0; } return 1; } static void smtp_tx_free(struct smtp_tx *tx) { struct smtp_rcpt *rcpt; rfc5322_free(tx->parser); while ((rcpt = TAILQ_FIRST(&tx->rcpts))) { TAILQ_REMOVE(&tx->rcpts, rcpt, entry); free(rcpt); } if (tx->ofile) fclose(tx->ofile); tx->session->tx = NULL; free(tx); } static void smtp_tx_mail_from(struct smtp_tx *tx, const char *line) { char *opt; char *copy; char tmp[SMTP_LINE_MAX]; (void)strlcpy(tmp, line, sizeof tmp); copy = tmp; if (smtp_mailaddr(&tx->evp.sender, copy, 1, &copy, tx->session->smtpname) == 0) { smtp_reply(tx->session, "553 %s Sender address syntax error", esc_code(ESC_STATUS_PERMFAIL, ESC_OTHER_ADDRESS_STATUS)); smtp_tx_free(tx); return; } while ((opt = strsep(&copy, " "))) { if (*opt == '\0') continue; if (strncasecmp(opt, "AUTH=", 5) == 0) log_debug("debug: smtp: AUTH in MAIL FROM command"); else if (strncasecmp(opt, "SIZE=", 5) == 0) log_debug("debug: smtp: SIZE in MAIL FROM command"); else if (strcasecmp(opt, "BODY=7BIT") == 0) /* XXX only for this transaction */ tx->session->flags &= ~SF_8BITMIME; else if (strcasecmp(opt, "BODY=8BITMIME") == 0) ; else if (ADVERTISE_EXT_DSN(tx->session) && strncasecmp(opt, "RET=", 4) == 0) { opt += 4; if (strcasecmp(opt, "HDRS") == 0) tx->evp.dsn_ret = DSN_RETHDRS; else if (strcasecmp(opt, "FULL") == 0) tx->evp.dsn_ret = DSN_RETFULL; } else if (ADVERTISE_EXT_DSN(tx->session) && strncasecmp(opt, "ENVID=", 6) == 0) { opt += 6; if (strlcpy(tx->evp.dsn_envid, opt, sizeof(tx->evp.dsn_envid)) >= sizeof(tx->evp.dsn_envid)) { smtp_reply(tx->session, "503 %s %s: option too large, truncated: %s", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND_ARGUMENTS), esc_description(ESC_INVALID_COMMAND_ARGUMENTS), opt); smtp_tx_free(tx); return; } } else { smtp_reply(tx->session, "503 %s %s: Unsupported option %s", esc_code(ESC_STATUS_PERMFAIL, ESC_INVALID_COMMAND_ARGUMENTS), esc_description(ESC_INVALID_COMMAND_ARGUMENTS), opt); smtp_tx_free(tx); return; } } /* only check sendertable if defined and user has authenticated */ if (tx->session->flags & SF_AUTHENTICATED && tx->session->listener->sendertable[0]) { m_create(p_lka, IMSG_SMTP_CHECK_SENDER, 0, 0, -1); m_add_id(p_lka, tx->session->id); m_add_string(p_lka, tx->session->listener->sendertable); m_add_string(p_lka, tx->session->username); m_add_mailaddr(p_lka, &tx->evp.sender); m_close(p_lka); tree_xset(&wait_lka_mail, tx->session->id, tx->session); } else smtp_tx_create_message(tx); } static void smtp_tx_create_message(struct smtp_tx *tx) { m_create(p_queue, IMSG_SMTP_MESSAGE_CREATE, 0, 0, -1); m_add_id(p_queue, tx->session->id); m_close(p_queue); tree_xset(&wait_queue_msg, tx->session->id, tx->session); } static void smtp_tx_rcpt_to(struct smtp_tx *tx, const char *line) { char *opt, *p; char *copy; char tmp[SMTP_LINE_MAX]; (void)strlcpy(tmp, line, sizeof tmp); copy = tmp; if (tx->rcptcount >= env->sc_session_max_rcpt) { smtp_reply(tx->session, "451 %s %s: Too many recipients", esc_code(ESC_STATUS_TEMPFAIL, ESC_TOO_MANY_RECIPIENTS), esc_description(ESC_TOO_MANY_RECIPIENTS)); return; } if (smtp_mailaddr(&tx->evp.rcpt, copy, 0, &copy, tx->session->smtpname) == 0) { smtp_reply(tx->session, "501 %s Recipient address syntax error", esc_code(ESC_STATUS_PERMFAIL, ESC_BAD_DESTINATION_MAILBOX_ADDRESS_SYNTAX)); return; } while ((opt = strsep(&copy, " "))) { if (*opt == '\0') continue; if (ADVERTISE_EXT_DSN(tx->session) && strncasecmp(opt, "NOTIFY=", 7) == 0) { opt += 7; while ((p = strsep(&opt, ","))) { if (strcasecmp(p, "SUCCESS") == 0) tx->evp.dsn_notify |= DSN_SUCCESS; else if (strcasecmp(p, "FAILURE") == 0) tx->evp.dsn_notify |= DSN_FAILURE; else if (strcasecmp(p, "DELAY") == 0) tx->evp.dsn_notify |= DSN_DELAY; else if (strcasecmp(p, "NEVER") == 0) tx->evp.dsn_notify |= DSN_NEVER; } if (tx->evp.dsn_notify & DSN_NEVER && tx->evp.dsn_notify & (DSN_SUCCESS | DSN_FAILURE | DSN_DELAY)) { smtp_reply(tx->session, "553 NOTIFY option NEVER cannot be" " combined with other options"); return; } } else if (ADVERTISE_EXT_DSN(tx->session) && strncasecmp(opt, "ORCPT=", 6) == 0) { opt += 6; if (!text_to_mailaddr(&tx->evp.dsn_orcpt, opt)) { smtp_reply(tx->session, "553 ORCPT address syntax error"); return; } } else { smtp_reply(tx->session, "503 Unsupported option %s", opt); return; } } m_create(p_lka, IMSG_SMTP_EXPAND_RCPT, 0, 0, -1); m_add_id(p_lka, tx->session->id); m_add_envelope(p_lka, &tx->evp); m_close(p_lka); tree_xset(&wait_lka_rcpt, tx->session->id, tx->session); } static void smtp_tx_open_message(struct smtp_tx *tx) { m_create(p_queue, IMSG_SMTP_MESSAGE_OPEN, 0, 0, -1); m_add_id(p_queue, tx->session->id); m_add_msgid(p_queue, tx->msgid); m_close(p_queue); tree_xset(&wait_queue_fd, tx->session->id, tx->session); } static void smtp_tx_commit(struct smtp_tx *tx) { m_create(p_queue, IMSG_SMTP_MESSAGE_COMMIT, 0, 0, -1); m_add_id(p_queue, tx->session->id); m_add_msgid(p_queue, tx->msgid); m_close(p_queue); tree_xset(&wait_queue_commit, tx->session->id, tx->session); smtp_filter_data_end(tx->session); } static void smtp_tx_rollback(struct smtp_tx *tx) { m_create(p_queue, IMSG_SMTP_MESSAGE_ROLLBACK, 0, 0, -1); m_add_msgid(p_queue, tx->msgid); m_close(p_queue); smtp_report_tx_rollback(tx->session, tx->msgid); smtp_report_tx_reset(tx->session, tx->msgid); smtp_filter_data_end(tx->session); } static int smtp_tx_dataline(struct smtp_tx *tx, const char *line) { struct rfc5322_result res; int r; log_trace(TRACE_SMTP, "<<< [MSG] %s", line); if (!strcmp(line, ".")) { smtp_report_protocol_client(tx->session, "."); log_trace(TRACE_SMTP, "<<< [EOM]"); if (tx->error) return 1; line = NULL; } else { /* ignore data line if an error is set */ if (tx->error) return 0; /* escape lines starting with a '.' */ if (line[0] == '.') line += 1; } if (rfc5322_push(tx->parser, line) == -1) { log_warnx("failed to push dataline"); tx->error = TX_ERROR_INTERNAL; return 0; } for(;;) { r = rfc5322_next(tx->parser, &res); switch (r) { case -1: if (errno == ENOMEM) tx->error = TX_ERROR_INTERNAL; else tx->error = TX_ERROR_MALFORMED; return 0; case RFC5322_NONE: /* Need more data */ return 0; case RFC5322_HEADER_START: /* ignore bcc */ if (!strcasecmp("Bcc", res.hdr)) continue; if (!strcasecmp("To", res.hdr) || !strcasecmp("Cc", res.hdr) || !strcasecmp("From", res.hdr)) { rfc5322_unfold_header(tx->parser); continue; } if (!strcasecmp("Received", res.hdr)) { if (++tx->rcvcount >= MAX_HOPS_COUNT) { log_warnx("warn: loop detected"); tx->error = TX_ERROR_LOOP; return 0; } } else if (!tx->has_date && !strcasecmp("Date", res.hdr)) tx->has_date = 1; else if (!tx->has_message_id && !strcasecmp("Message-Id", res.hdr)) tx->has_message_id = 1; smtp_message_printf(tx, "%s:%s\n", res.hdr, res.value); break; case RFC5322_HEADER_CONT: if (!strcasecmp("Bcc", res.hdr) || !strcasecmp("To", res.hdr) || !strcasecmp("Cc", res.hdr) || !strcasecmp("From", res.hdr)) continue; smtp_message_printf(tx, "%s\n", res.value); break; case RFC5322_HEADER_END: if (!strcasecmp("To", res.hdr) || !strcasecmp("Cc", res.hdr) || !strcasecmp("From", res.hdr)) header_domain_append_callback(tx, res.hdr, res.value); break; case RFC5322_END_OF_HEADERS: if (tx->session->listener->local || tx->session->listener->port == 587) { if (!tx->has_date) { log_debug("debug: %p: adding Date", tx); smtp_message_printf(tx, "Date: %s\n", time_to_text(tx->time)); } if (!tx->has_message_id) { log_debug("debug: %p: adding Message-ID", tx); smtp_message_printf(tx, "Message-ID: <%016"PRIx64"@%s>\n", generate_uid(), tx->session->listener->hostname); } } break; case RFC5322_BODY_START: case RFC5322_BODY: smtp_message_printf(tx, "%s\n", res.value); break; case RFC5322_END_OF_MESSAGE: return 1; default: fatalx("%s", __func__); } } } static int smtp_tx_filtered_dataline(struct smtp_tx *tx, const char *line) { if (!strcmp(line, ".")) line = NULL; else { /* ignore data line if an error is set */ if (tx->error) return 0; } io_printf(tx->filter, "%s\n", line ? line : "."); return line ? 0 : 1; } static void smtp_tx_eom(struct smtp_tx *tx) { smtp_filter_phase(FILTER_COMMIT, tx->session, NULL); } static int smtp_message_fd(struct smtp_tx *tx, int fd) { struct smtp_session *s; s = tx->session; log_debug("smtp: %p: message fd %d", s, fd); if ((tx->ofile = fdopen(fd, "w")) == NULL) { close(fd); smtp_reply(s, "421 %s Temporary Error", esc_code(ESC_STATUS_TEMPFAIL, ESC_OTHER_MAIL_SYSTEM_STATUS)); smtp_enter_state(s, STATE_QUIT); return 0; } return 1; } static void filter_session_io(struct io *io, int evt, void *arg) { struct smtp_tx*tx = arg; char*line = NULL; ssize_t len; log_trace(TRACE_IO, "filter session io (smtp): %p: %s %s", tx, io_strevent(evt), io_strio(io)); switch (evt) { case IO_DATAIN: nextline: line = io_getline(tx->filter, &len); /* No complete line received */ if (line == NULL) return; if (smtp_tx_dataline(tx, line)) { smtp_tx_eom(tx); return; } goto nextline; } } static void smtp_filter_fd(struct smtp_tx *tx, int fd) { struct smtp_session *s; s = tx->session; log_debug("smtp: %p: filter fd %d", s, fd); tx->filter = io_new(); io_set_fd(tx->filter, fd); io_set_callback(tx->filter, filter_session_io, tx); } static void smtp_message_begin(struct smtp_tx *tx) { struct smtp_session *s; X509 *x; int (*m_printf)(struct smtp_tx *, const char *, ...); m_printf = smtp_message_printf; if (tx->filter) m_printf = smtp_filter_printf; s = tx->session; log_debug("smtp: %p: message begin", s); smtp_reply(s, "354 Enter mail, end with \".\"" " on a line by itself"); if (s->junk || (s->tx && s->tx->junk)) m_printf(tx, "X-Spam: Yes\n"); m_printf(tx, "Received: "); if (!(s->listener->flags & F_MASK_SOURCE)) { m_printf(tx, "from %s (%s %s%s%s)", s->helo, s->rdns, s->ss.ss_family == AF_INET6 ? "" : "[", ss_to_text(&s->ss), s->ss.ss_family == AF_INET6 ? "" : "]"); } m_printf(tx, "\n\tby %s (%s) with %sSMTP%s%s id %08x", s->smtpname, SMTPD_NAME, s->flags & SF_EHLO ? "E" : "", s->flags & SF_SECURE ? "S" : "", s->flags & SF_AUTHENTICATED ? "A" : "", tx->msgid); if (s->flags & SF_SECURE) { x = SSL_get_peer_certificate(io_tls(s->io)); m_printf(tx, " (%s:%s:%d:%s)", SSL_get_version(io_tls(s->io)), SSL_get_cipher_name(io_tls(s->io)), SSL_get_cipher_bits(io_tls(s->io), NULL), (s->flags & SF_VERIFIED) ? "YES" : (x ? "FAIL" : "NO")); X509_free(x); if (s->listener->flags & F_RECEIVEDAUTH) { m_printf(tx, " auth=%s", s->username[0] ? "yes" : "no"); if (s->username[0]) m_printf(tx, " user=%s", s->username); } } if (tx->rcptcount == 1) { m_printf(tx, "\n\tfor <%s@%s>", tx->evp.rcpt.user, tx->evp.rcpt.domain); } m_printf(tx, ";\n\t%s\n", time_to_text(time(&tx->time))); smtp_enter_state(s, STATE_BODY); } static void smtp_message_end(struct smtp_tx *tx) { struct smtp_session *s; s = tx->session; log_debug("debug: %p: end of message, error=%d", s, tx->error); fclose(tx->ofile); tx->ofile = NULL; switch(tx->error) { case TX_OK: smtp_tx_commit(tx); return; case TX_ERROR_SIZE: smtp_reply(s, "554 %s %s: Transaction failed, message too big", esc_code(ESC_STATUS_PERMFAIL, ESC_MESSAGE_TOO_BIG_FOR_SYSTEM), esc_description(ESC_MESSAGE_TOO_BIG_FOR_SYSTEM)); break; case TX_ERROR_LOOP: smtp_reply(s, "500 %s %s: Loop detected", esc_code(ESC_STATUS_PERMFAIL, ESC_ROUTING_LOOP_DETECTED), esc_description(ESC_ROUTING_LOOP_DETECTED)); break; case TX_ERROR_MALFORMED: smtp_reply(s, "550 %s %s: Message is not RFC 2822 compliant", esc_code(ESC_STATUS_PERMFAIL, ESC_DELIVERY_NOT_AUTHORIZED_MESSAGE_REFUSED), esc_description(ESC_DELIVERY_NOT_AUTHORIZED_MESSAGE_REFUSED)); break; case TX_ERROR_IO: case TX_ERROR_RESOURCES: smtp_reply(s, "421 %s Temporary Error", esc_code(ESC_STATUS_TEMPFAIL, ESC_OTHER_MAIL_SYSTEM_STATUS)); break; default: /* fatal? */ smtp_reply(s, "421 Internal server error"); } smtp_tx_rollback(tx); smtp_tx_free(tx); smtp_enter_state(s, STATE_HELO); } static int smtp_filter_printf(struct smtp_tx *tx, const char *fmt, ...) { va_list ap; int len; if (tx->error) return -1; va_start(ap, fmt); len = io_vprintf(tx->filter, fmt, ap); va_end(ap); if (len < 0) { log_warn("smtp-in: session %016"PRIx64": vfprintf", tx->session->id); tx->error = TX_ERROR_IO; } else tx->odatalen += len; return len; } static int smtp_message_printf(struct smtp_tx *tx, const char *fmt, ...) { va_list ap; int len; if (tx->error) return -1; va_start(ap, fmt); len = vfprintf(tx->ofile, fmt, ap); va_end(ap); if (len == -1) { log_warn("smtp-in: session %016"PRIx64": vfprintf", tx->session->id); tx->error = TX_ERROR_IO; } else tx->odatalen += len; return len; } #define CASE(x) case x : return #x const char * smtp_strstate(int state) { static char buf[32]; switch (state) { CASE(STATE_NEW); CASE(STATE_CONNECTED); CASE(STATE_TLS); CASE(STATE_HELO); CASE(STATE_AUTH_INIT); CASE(STATE_AUTH_USERNAME); CASE(STATE_AUTH_PASSWORD); CASE(STATE_AUTH_FINALIZE); CASE(STATE_BODY); CASE(STATE_QUIT); default: (void)snprintf(buf, sizeof(buf), "STATE_??? (%d)", state); return (buf); } } static void smtp_report_link_connect(struct smtp_session *s, const char *rdns, int fcrdns, const struct sockaddr_storage *ss_src, const struct sockaddr_storage *ss_dest) { if (! SESSION_FILTERED(s)) return; report_smtp_link_connect("smtp-in", s->id, rdns, fcrdns, ss_src, ss_dest); } static void smtp_report_link_greeting(struct smtp_session *s, const char *domain) { if (! SESSION_FILTERED(s)) return; report_smtp_link_greeting("smtp-in", s->id, domain); } static void smtp_report_link_identify(struct smtp_session *s, const char *method, const char *identity) { if (! SESSION_FILTERED(s)) return; report_smtp_link_identify("smtp-in", s->id, method, identity); } static void smtp_report_link_tls(struct smtp_session *s, const char *ssl) { if (! SESSION_FILTERED(s)) return; report_smtp_link_tls("smtp-in", s->id, ssl); } static void smtp_report_link_disconnect(struct smtp_session *s) { if (! SESSION_FILTERED(s)) return; report_smtp_link_disconnect("smtp-in", s->id); } static void smtp_report_link_auth(struct smtp_session *s, const char *user, const char *result) { if (! SESSION_FILTERED(s)) return; report_smtp_link_auth("smtp-in", s->id, user, result); } static void smtp_report_tx_reset(struct smtp_session *s, uint32_t msgid) { if (! SESSION_FILTERED(s)) return; report_smtp_tx_reset("smtp-in", s->id, msgid); } static void smtp_report_tx_begin(struct smtp_session *s, uint32_t msgid) { if (! SESSION_FILTERED(s)) return; report_smtp_tx_begin("smtp-in", s->id, msgid); } static void smtp_report_tx_mail(struct smtp_session *s, uint32_t msgid, const char *address, int ok) { char mailaddr[SMTPD_MAXMAILADDRSIZE]; char *p; if (! SESSION_FILTERED(s)) return; if ((p = strchr(address, '<')) == NULL) return; (void)strlcpy(mailaddr, p + 1, sizeof mailaddr); if ((p = strchr(mailaddr, '>')) == NULL) return; *p = '\0'; report_smtp_tx_mail("smtp-in", s->id, msgid, mailaddr, ok); } static void smtp_report_tx_rcpt(struct smtp_session *s, uint32_t msgid, const char *address, int ok) { char mailaddr[SMTPD_MAXMAILADDRSIZE]; char *p; if (! SESSION_FILTERED(s)) return; if ((p = strchr(address, '<')) == NULL) return; (void)strlcpy(mailaddr, p + 1, sizeof mailaddr); if ((p = strchr(mailaddr, '>')) == NULL) return; *p = '\0'; report_smtp_tx_rcpt("smtp-in", s->id, msgid, mailaddr, ok); } static void smtp_report_tx_envelope(struct smtp_session *s, uint32_t msgid, uint64_t evpid) { if (! SESSION_FILTERED(s)) return; report_smtp_tx_envelope("smtp-in", s->id, msgid, evpid); } static void smtp_report_tx_data(struct smtp_session *s, uint32_t msgid, int ok) { if (! SESSION_FILTERED(s)) return; report_smtp_tx_data("smtp-in", s->id, msgid, ok); } static void smtp_report_tx_commit(struct smtp_session *s, uint32_t msgid, size_t msgsz) { if (! SESSION_FILTERED(s)) return; report_smtp_tx_commit("smtp-in", s->id, msgid, msgsz); } static void smtp_report_tx_rollback(struct smtp_session *s, uint32_t msgid) { if (! SESSION_FILTERED(s)) return; report_smtp_tx_rollback("smtp-in", s->id, msgid); } static void smtp_report_protocol_client(struct smtp_session *s, const char *command) { if (! SESSION_FILTERED(s)) return; report_smtp_protocol_client("smtp-in", s->id, command); } static void smtp_report_protocol_server(struct smtp_session *s, const char *response) { if (! SESSION_FILTERED(s)) return; report_smtp_protocol_server("smtp-in", s->id, response); } static void smtp_report_filter_response(struct smtp_session *s, int phase, int response, const char *param) { if (! SESSION_FILTERED(s)) return; report_smtp_filter_response("smtp-in", s->id, phase, response, param); } static void smtp_report_timeout(struct smtp_session *s) { if (! SESSION_FILTERED(s)) return; report_smtp_timeout("smtp-in", s->id); }
./CrossVul/dataset_final_sorted/CWE-252/c/bad_4604_0
crossvul-cpp_data_good_2978_0
/* Request a key from userspace * * Copyright (C) 2004-2007 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. * * See Documentation/security/keys/request-key.rst */ #include <linux/module.h> #include <linux/sched.h> #include <linux/kmod.h> #include <linux/err.h> #include <linux/keyctl.h> #include <linux/slab.h> #include "internal.h" #define key_negative_timeout 60 /* default timeout on a negative key's existence */ /** * complete_request_key - Complete the construction of a key. * @cons: The key construction record. * @error: The success or failute of the construction. * * Complete the attempt to construct a key. The key will be negated * if an error is indicated. The authorisation key will be revoked * unconditionally. */ void complete_request_key(struct key_construction *cons, int error) { kenter("{%d,%d},%d", cons->key->serial, cons->authkey->serial, error); if (error < 0) key_negate_and_link(cons->key, key_negative_timeout, NULL, cons->authkey); else key_revoke(cons->authkey); key_put(cons->key); key_put(cons->authkey); kfree(cons); } EXPORT_SYMBOL(complete_request_key); /* * Initialise a usermode helper that is going to have a specific session * keyring. * * This is called in context of freshly forked kthread before kernel_execve(), * so we can simply install the desired session_keyring at this point. */ static int umh_keys_init(struct subprocess_info *info, struct cred *cred) { struct key *keyring = info->data; return install_session_keyring_to_cred(cred, keyring); } /* * Clean up a usermode helper with session keyring. */ static void umh_keys_cleanup(struct subprocess_info *info) { struct key *keyring = info->data; key_put(keyring); } /* * Call a usermode helper with a specific session keyring. */ static int call_usermodehelper_keys(const char *path, char **argv, char **envp, struct key *session_keyring, int wait) { struct subprocess_info *info; info = call_usermodehelper_setup(path, argv, envp, GFP_KERNEL, umh_keys_init, umh_keys_cleanup, session_keyring); if (!info) return -ENOMEM; key_get(session_keyring); return call_usermodehelper_exec(info, wait); } /* * Request userspace finish the construction of a key * - execute "/sbin/request-key <op> <key> <uid> <gid> <keyring> <keyring> <keyring>" */ static int call_sbin_request_key(struct key_construction *cons, const char *op, void *aux) { static char const request_key[] = "/sbin/request-key"; const struct cred *cred = current_cred(); key_serial_t prkey, sskey; struct key *key = cons->key, *authkey = cons->authkey, *keyring, *session; char *argv[9], *envp[3], uid_str[12], gid_str[12]; char key_str[12], keyring_str[3][12]; char desc[20]; int ret, i; kenter("{%d},{%d},%s", key->serial, authkey->serial, op); ret = install_user_keyrings(); if (ret < 0) goto error_alloc; /* allocate a new session keyring */ sprintf(desc, "_req.%u", key->serial); cred = get_current_cred(); keyring = keyring_alloc(desc, cred->fsuid, cred->fsgid, cred, KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ, KEY_ALLOC_QUOTA_OVERRUN, NULL, NULL); put_cred(cred); if (IS_ERR(keyring)) { ret = PTR_ERR(keyring); goto error_alloc; } /* attach the auth key to the session keyring */ ret = key_link(keyring, authkey); if (ret < 0) goto error_link; /* record the UID and GID */ sprintf(uid_str, "%d", from_kuid(&init_user_ns, cred->fsuid)); sprintf(gid_str, "%d", from_kgid(&init_user_ns, cred->fsgid)); /* we say which key is under construction */ sprintf(key_str, "%d", key->serial); /* we specify the process's default keyrings */ sprintf(keyring_str[0], "%d", cred->thread_keyring ? cred->thread_keyring->serial : 0); prkey = 0; if (cred->process_keyring) prkey = cred->process_keyring->serial; sprintf(keyring_str[1], "%d", prkey); rcu_read_lock(); session = rcu_dereference(cred->session_keyring); if (!session) session = cred->user->session_keyring; sskey = session->serial; rcu_read_unlock(); sprintf(keyring_str[2], "%d", sskey); /* set up a minimal environment */ i = 0; envp[i++] = "HOME=/"; envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin"; envp[i] = NULL; /* set up the argument list */ i = 0; argv[i++] = (char *)request_key; argv[i++] = (char *) op; argv[i++] = key_str; argv[i++] = uid_str; argv[i++] = gid_str; argv[i++] = keyring_str[0]; argv[i++] = keyring_str[1]; argv[i++] = keyring_str[2]; argv[i] = NULL; /* do it */ ret = call_usermodehelper_keys(request_key, argv, envp, keyring, UMH_WAIT_PROC); kdebug("usermode -> 0x%x", ret); if (ret >= 0) { /* ret is the exit/wait code */ if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags) || key_validate(key) < 0) ret = -ENOKEY; else /* ignore any errors from userspace if the key was * instantiated */ ret = 0; } error_link: key_put(keyring); error_alloc: complete_request_key(cons, ret); kleave(" = %d", ret); return ret; } /* * Call out to userspace for key construction. * * Program failure is ignored in favour of key status. */ static int construct_key(struct key *key, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring) { struct key_construction *cons; request_key_actor_t actor; struct key *authkey; int ret; kenter("%d,%p,%zu,%p", key->serial, callout_info, callout_len, aux); cons = kmalloc(sizeof(*cons), GFP_KERNEL); if (!cons) return -ENOMEM; /* allocate an authorisation key */ authkey = request_key_auth_new(key, callout_info, callout_len, dest_keyring); if (IS_ERR(authkey)) { kfree(cons); ret = PTR_ERR(authkey); authkey = NULL; } else { cons->authkey = key_get(authkey); cons->key = key_get(key); /* make the call */ actor = call_sbin_request_key; if (key->type->request_key) actor = key->type->request_key; ret = actor(cons, "create", aux); /* check that the actor called complete_request_key() prior to * returning an error */ WARN_ON(ret < 0 && !test_bit(KEY_FLAG_REVOKED, &authkey->flags)); key_put(authkey); } kleave(" = %d", ret); return ret; } /* * Get the appropriate destination keyring for the request. * * The keyring selected is returned with an extra reference upon it which the * caller must release. */ static int construct_get_dest_keyring(struct key **_dest_keyring) { struct request_key_auth *rka; const struct cred *cred = current_cred(); struct key *dest_keyring = *_dest_keyring, *authkey; int ret; kenter("%p", dest_keyring); /* find the appropriate keyring */ if (dest_keyring) { /* the caller supplied one */ key_get(dest_keyring); } else { bool do_perm_check = true; /* use a default keyring; falling through the cases until we * find one that we actually have */ switch (cred->jit_keyring) { case KEY_REQKEY_DEFL_DEFAULT: case KEY_REQKEY_DEFL_REQUESTOR_KEYRING: if (cred->request_key_auth) { authkey = cred->request_key_auth; down_read(&authkey->sem); rka = authkey->payload.data[0]; if (!test_bit(KEY_FLAG_REVOKED, &authkey->flags)) dest_keyring = key_get(rka->dest_keyring); up_read(&authkey->sem); if (dest_keyring) { do_perm_check = false; break; } } case KEY_REQKEY_DEFL_THREAD_KEYRING: dest_keyring = key_get(cred->thread_keyring); if (dest_keyring) break; case KEY_REQKEY_DEFL_PROCESS_KEYRING: dest_keyring = key_get(cred->process_keyring); if (dest_keyring) break; case KEY_REQKEY_DEFL_SESSION_KEYRING: rcu_read_lock(); dest_keyring = key_get( rcu_dereference(cred->session_keyring)); rcu_read_unlock(); if (dest_keyring) break; case KEY_REQKEY_DEFL_USER_SESSION_KEYRING: dest_keyring = key_get(cred->user->session_keyring); break; case KEY_REQKEY_DEFL_USER_KEYRING: dest_keyring = key_get(cred->user->uid_keyring); break; case KEY_REQKEY_DEFL_GROUP_KEYRING: default: BUG(); } /* * Require Write permission on the keyring. This is essential * because the default keyring may be the session keyring, and * joining a keyring only requires Search permission. * * However, this check is skipped for the "requestor keyring" so * that /sbin/request-key can itself use request_key() to add * keys to the original requestor's destination keyring. */ if (dest_keyring && do_perm_check) { ret = key_permission(make_key_ref(dest_keyring, 1), KEY_NEED_WRITE); if (ret) { key_put(dest_keyring); return ret; } } } *_dest_keyring = dest_keyring; kleave(" [dk %d]", key_serial(dest_keyring)); return 0; } /* * Allocate a new key in under-construction state and attempt to link it in to * the requested keyring. * * May return a key that's already under construction instead if there was a * race between two thread calling request_key(). */ static int construct_alloc_key(struct keyring_search_context *ctx, struct key *dest_keyring, unsigned long flags, struct key_user *user, struct key **_key) { struct assoc_array_edit *edit; struct key *key; key_perm_t perm; key_ref_t key_ref; int ret; kenter("%s,%s,,,", ctx->index_key.type->name, ctx->index_key.description); *_key = NULL; mutex_lock(&user->cons_lock); perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR; perm |= KEY_USR_VIEW; if (ctx->index_key.type->read) perm |= KEY_POS_READ; if (ctx->index_key.type == &key_type_keyring || ctx->index_key.type->update) perm |= KEY_POS_WRITE; key = key_alloc(ctx->index_key.type, ctx->index_key.description, ctx->cred->fsuid, ctx->cred->fsgid, ctx->cred, perm, flags, NULL); if (IS_ERR(key)) goto alloc_failed; set_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags); if (dest_keyring) { ret = __key_link_begin(dest_keyring, &ctx->index_key, &edit); if (ret < 0) goto link_prealloc_failed; } /* attach the key to the destination keyring under lock, but we do need * to do another check just in case someone beat us to it whilst we * waited for locks */ mutex_lock(&key_construction_mutex); key_ref = search_process_keyrings(ctx); if (!IS_ERR(key_ref)) goto key_already_present; if (dest_keyring) __key_link(key, &edit); mutex_unlock(&key_construction_mutex); if (dest_keyring) __key_link_end(dest_keyring, &ctx->index_key, edit); mutex_unlock(&user->cons_lock); *_key = key; kleave(" = 0 [%d]", key_serial(key)); return 0; /* the key is now present - we tell the caller that we found it by * returning -EINPROGRESS */ key_already_present: key_put(key); mutex_unlock(&key_construction_mutex); key = key_ref_to_ptr(key_ref); if (dest_keyring) { ret = __key_link_check_live_key(dest_keyring, key); if (ret == 0) __key_link(key, &edit); __key_link_end(dest_keyring, &ctx->index_key, edit); if (ret < 0) goto link_check_failed; } mutex_unlock(&user->cons_lock); *_key = key; kleave(" = -EINPROGRESS [%d]", key_serial(key)); return -EINPROGRESS; link_check_failed: mutex_unlock(&user->cons_lock); key_put(key); kleave(" = %d [linkcheck]", ret); return ret; link_prealloc_failed: mutex_unlock(&user->cons_lock); key_put(key); kleave(" = %d [prelink]", ret); return ret; alloc_failed: mutex_unlock(&user->cons_lock); kleave(" = %ld", PTR_ERR(key)); return PTR_ERR(key); } /* * Commence key construction. */ static struct key *construct_key_and_link(struct keyring_search_context *ctx, const char *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct key_user *user; struct key *key; int ret; kenter(""); if (ctx->index_key.type == &key_type_keyring) return ERR_PTR(-EPERM); ret = construct_get_dest_keyring(&dest_keyring); if (ret) goto error; user = key_user_lookup(current_fsuid()); if (!user) { ret = -ENOMEM; goto error_put_dest_keyring; } ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key); key_user_put(user); if (ret == 0) { ret = construct_key(key, callout_info, callout_len, aux, dest_keyring); if (ret < 0) { kdebug("cons failed"); goto construction_failed; } } else if (ret == -EINPROGRESS) { ret = 0; } else { goto error_put_dest_keyring; } key_put(dest_keyring); kleave(" = key %d", key_serial(key)); return key; construction_failed: key_negate_and_link(key, key_negative_timeout, NULL, NULL); key_put(key); error_put_dest_keyring: key_put(dest_keyring); error: kleave(" = %d", ret); return ERR_PTR(ret); } /** * request_key_and_link - Request a key and cache it in a keyring. * @type: The type of key we want. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * @dest_keyring: Where to cache the key. * @flags: Flags to key_alloc(). * * A key matching the specified criteria is searched for in the process's * keyrings and returned with its usage count incremented if found. Otherwise, * if callout_info is not NULL, a key will be allocated and some service * (probably in userspace) will be asked to instantiate it. * * If successfully found or created, the key will be linked to the destination * keyring if one is provided. * * Returns a pointer to the key if successful; -EACCES, -ENOKEY, -EKEYREVOKED * or -EKEYEXPIRED if an inaccessible, negative, revoked or expired key was * found; -ENOKEY if no key was found and no @callout_info was given; -EDQUOT * if insufficient key quota was available to create a new key; or -ENOMEM if * insufficient memory was available. * * If the returned key was created, then it may still be under construction, * and wait_for_key_construction() should be used to wait for that to complete. */ struct key *request_key_and_link(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = (KEYRING_SEARCH_DO_STATE_CHECK | KEYRING_SEARCH_SKIP_EXPIRED), }; struct key *key; key_ref_t key_ref; int ret; kenter("%s,%s,%p,%zu,%p,%p,%lx", ctx.index_key.type->name, ctx.index_key.description, callout_info, callout_len, aux, dest_keyring, flags); if (type->match_preparse) { ret = type->match_preparse(&ctx.match_data); if (ret < 0) { key = ERR_PTR(ret); goto error; } } /* search all the process keyrings for a key */ key_ref = search_process_keyrings(&ctx); if (!IS_ERR(key_ref)) { key = key_ref_to_ptr(key_ref); if (dest_keyring) { ret = key_link(dest_keyring, key); if (ret < 0) { key_put(key); key = ERR_PTR(ret); goto error_free; } } } else if (PTR_ERR(key_ref) != -EAGAIN) { key = ERR_CAST(key_ref); } else { /* the search failed, but the keyrings were searchable, so we * should consult userspace if we can */ key = ERR_PTR(-ENOKEY); if (!callout_info) goto error_free; key = construct_key_and_link(&ctx, callout_info, callout_len, aux, dest_keyring, flags); } error_free: if (type->match_free) type->match_free(&ctx.match_data); error: kleave(" = %p", key); return key; } /** * wait_for_key_construction - Wait for construction of a key to complete * @key: The key being waited for. * @intr: Whether to wait interruptibly. * * Wait for a key to finish being constructed. * * Returns 0 if successful; -ERESTARTSYS if the wait was interrupted; -ENOKEY * if the key was negated; or -EKEYREVOKED or -EKEYEXPIRED if the key was * revoked or expired. */ int wait_for_key_construction(struct key *key, bool intr) { int ret; ret = wait_on_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT, intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE); if (ret) return -ERESTARTSYS; ret = key_read_state(key); if (ret < 0) return ret; return key_validate(key); } EXPORT_SYMBOL(wait_for_key_construction); /** * request_key - Request a key and wait for construction * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found, new keys are always allocated in the user's quota, * the callout_info must be a NUL-terminated string and no auxiliary data can * be passed. * * Furthermore, it then works as wait_for_key_construction() to wait for the * completion of keys undergoing construction with a non-interruptible wait. */ struct key *request_key(struct key_type *type, const char *description, const char *callout_info) { struct key *key; size_t callout_len = 0; int ret; if (callout_info) callout_len = strlen(callout_info); key = request_key_and_link(type, description, callout_info, callout_len, NULL, NULL, KEY_ALLOC_IN_QUOTA); if (!IS_ERR(key)) { ret = wait_for_key_construction(key, false); if (ret < 0) { key_put(key); return ERR_PTR(ret); } } return key; } EXPORT_SYMBOL(request_key); /** * request_key_with_auxdata - Request a key with auxiliary data for the upcaller * @type: The type of key we want. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found and new keys are always allocated in the user's quota. * * Furthermore, it then works as wait_for_key_construction() to wait for the * completion of keys undergoing construction with a non-interruptible wait. */ struct key *request_key_with_auxdata(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux) { struct key *key; int ret; key = request_key_and_link(type, description, callout_info, callout_len, aux, NULL, KEY_ALLOC_IN_QUOTA); if (!IS_ERR(key)) { ret = wait_for_key_construction(key, false); if (ret < 0) { key_put(key); return ERR_PTR(ret); } } return key; } EXPORT_SYMBOL(request_key_with_auxdata); /* * request_key_async - Request a key (allow async construction) * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found, new keys are always allocated in the user's quota and * no auxiliary data can be passed. * * The caller should call wait_for_key_construction() to wait for the * completion of the returned key if it is still undergoing construction. */ struct key *request_key_async(struct key_type *type, const char *description, const void *callout_info, size_t callout_len) { return request_key_and_link(type, description, callout_info, callout_len, NULL, NULL, KEY_ALLOC_IN_QUOTA); } EXPORT_SYMBOL(request_key_async); /* * request a key with auxiliary data for the upcaller (allow async construction) * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found and new keys are always allocated in the user's quota. * * The caller should call wait_for_key_construction() to wait for the * completion of the returned key if it is still undergoing construction. */ struct key *request_key_async_with_auxdata(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux) { return request_key_and_link(type, description, callout_info, callout_len, aux, NULL, KEY_ALLOC_IN_QUOTA); } EXPORT_SYMBOL(request_key_async_with_auxdata);
./CrossVul/dataset_final_sorted/CWE-862/c/good_2978_0
crossvul-cpp_data_good_4459_0
/* Copyright (C) 2002-2010 Karl J. Runge <runge@karlrunge.com> All rights reserved. This file is part of x11vnc. x11vnc 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. x11vnc 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 x11vnc; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA or see <http://www.gnu.org/licenses/>. In addition, as a special exception, Karl J. Runge gives permission to link the code of its release of x11vnc with the OpenSSL project's "OpenSSL" library (or with modified versions of it that use the same license as the "OpenSSL" library), and distribute the linked executables. You must obey the GNU General Public License in all respects for all of the code used other than "OpenSSL". If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ /* -- scan.c -- */ #include "x11vnc.h" #include "xinerama.h" #include "xwrappers.h" #include "xdamage.h" #include "xrandr.h" #include "win_utils.h" #include "8to24.h" #include "screen.h" #include "pointer.h" #include "cleanup.h" #include "unixpw.h" #include "screen.h" #include "macosx.h" #include "userinput.h" /* * routines for scanning and reading the X11 display for changes, and * for doing all the tile work (shm, etc). */ void initialize_tiles(void); void free_tiles(void); void shm_delete(XShmSegmentInfo *shm); void shm_clean(XShmSegmentInfo *shm, XImage *xim); void initialize_polling_images(void); void scale_rect(double factor_x, double factor_y, int blend, int interpolate, int Bpp, char *src_fb, int src_bytes_per_line, char *dst_fb, int dst_bytes_per_line, int Nx, int Ny, int nx, int ny, int X1, int Y1, int X2, int Y2, int mark); void scale_and_mark_rect(int X1, int Y1, int X2, int Y2, int mark); void mark_rect_as_modified(int x1, int y1, int x2, int y2, int force); int copy_screen(void); int copy_snap(void); void nap_sleep(int ms, int split); void set_offset(void); int scan_for_updates(int count_only); void rotate_curs(char *dst_0, char *src_0, int Dx, int Dy, int Bpp); void rotate_coords(int x, int y, int *xo, int *yo, int dxi, int dyi); void rotate_coords_inverse(int x, int y, int *xo, int *yo, int dxi, int dyi); static void set_fs_factor(int max); static char *flip_ximage_byte_order(XImage *xim); static int shm_create(XShmSegmentInfo *shm, XImage **ximg_ptr, int w, int h, char *name); static void create_tile_hint(int x, int y, int tw, int th, hint_t *hint); static void extend_tile_hint(int x, int y, int tw, int th, hint_t *hint); static void save_hint(hint_t hint, int loc); static void hint_updates(void); static void mark_hint(hint_t hint); static int copy_tiles(int tx, int ty, int nt); static int copy_all_tiles(void); static int copy_all_tile_runs(void); static int copy_tiles_backward_pass(void); static int copy_tiles_additional_pass(void); static int gap_try(int x, int y, int *run, int *saw, int along_x); static int fill_tile_gaps(void); static int island_try(int x, int y, int u, int v, int *run); static int grow_islands(void); static void blackout_regions(void); static void nap_set(int tile_cnt); static void nap_check(int tile_cnt); static void ping_clients(int tile_cnt); static int blackout_line_skip(int n, int x, int y, int rescan, int *tile_count); static int blackout_line_cmpskip(int n, int x, int y, char *dst, char *src, int w, int pixelsize); static int scan_display(int ystart, int rescan); /* array to hold the hints: */ static hint_t *hint_list; /* nap state */ int nap_ok = 0; static int nap_diff_count = 0; static int scan_count = 0; /* indicates which scan pattern we are on */ static int scan_in_progress = 0; typedef struct tile_change_region { /* start and end lines, along y, of the changed area inside a tile. */ unsigned short first_line, last_line; short first_x, last_x; /* info about differences along edges. */ unsigned short left_diff, right_diff; unsigned short top_diff, bot_diff; } region_t; /* array to hold the tiles region_t-s. */ static region_t *tile_region; /* * setup tile numbers and allocate the tile and hint arrays: */ void initialize_tiles(void) { ntiles_x = (dpy_x - 1)/tile_x + 1; ntiles_y = (dpy_y - 1)/tile_y + 1; ntiles = ntiles_x * ntiles_y; tile_has_diff = (unsigned char *) calloc((size_t) (ntiles * sizeof(unsigned char)), 1); tile_has_xdamage_diff = (unsigned char *) calloc((size_t) (ntiles * sizeof(unsigned char)), 1); tile_row_has_xdamage_diff = (unsigned char *) calloc((size_t) (ntiles_y * sizeof(unsigned char)), 1); tile_tried = (unsigned char *) calloc((size_t) (ntiles * sizeof(unsigned char)), 1); tile_copied = (unsigned char *) calloc((size_t) (ntiles * sizeof(unsigned char)), 1); tile_blackout = (tile_blackout_t *) calloc((size_t) (ntiles * sizeof(tile_blackout_t)), 1); tile_region = (region_t *) calloc((size_t) (ntiles * sizeof(region_t)), 1); tile_row = (XImage **) calloc((size_t) ((ntiles_x + 1) * sizeof(XImage *)), 1); tile_row_shm = (XShmSegmentInfo *) calloc((size_t) ((ntiles_x + 1) * sizeof(XShmSegmentInfo)), 1); /* there will never be more hints than tiles: */ hint_list = (hint_t *) calloc((size_t) (ntiles * sizeof(hint_t)), 1); } void free_tiles(void) { if (tile_has_diff) { free(tile_has_diff); tile_has_diff = NULL; } if (tile_has_xdamage_diff) { free(tile_has_xdamage_diff); tile_has_xdamage_diff = NULL; } if (tile_row_has_xdamage_diff) { free(tile_row_has_xdamage_diff); tile_row_has_xdamage_diff = NULL; } if (tile_tried) { free(tile_tried); tile_tried = NULL; } if (tile_copied) { free(tile_copied); tile_copied = NULL; } if (tile_blackout) { free(tile_blackout); tile_blackout = NULL; } if (tile_region) { free(tile_region); tile_region = NULL; } if (tile_row) { free(tile_row); tile_row = NULL; } if (tile_row_shm) { free(tile_row_shm); tile_row_shm = NULL; } if (hint_list) { free(hint_list); hint_list = NULL; } } /* * silly function to factor dpy_y until fullscreen shm is not bigger than max. * should always work unless dpy_y is a large prime or something... under * failure fs_factor remains 0 and no fullscreen updates will be tried. */ static int fs_factor = 0; static void set_fs_factor(int max) { int f, fac = 1, n = dpy_y; fs_factor = 0; if ((bpp/8) * dpy_x * dpy_y <= max) { fs_factor = 1; return; } for (f=2; f <= 101; f++) { while (n % f == 0) { n = n / f; fac = fac * f; if ( (bpp/8) * dpy_x * (dpy_y/fac) <= max ) { fs_factor = fac; return; } } } } static char *flip_ximage_byte_order(XImage *xim) { char *order; if (xim->byte_order == LSBFirst) { order = "MSBFirst"; xim->byte_order = MSBFirst; xim->bitmap_bit_order = MSBFirst; } else { order = "LSBFirst"; xim->byte_order = LSBFirst; xim->bitmap_bit_order = LSBFirst; } return order; } /* * set up an XShm image, or if not using shm just create the XImage. */ static int shm_create(XShmSegmentInfo *shm, XImage **ximg_ptr, int w, int h, char *name) { XImage *xim; static int reported_flip = 0; int db = 0; shm->shmid = -1; shm->shmaddr = (char *) -1; *ximg_ptr = NULL; if (nofb) { return 1; } X_LOCK; if (! using_shm || xform24to32 || raw_fb) { /* we only need the XImage created */ xim = XCreateImage_wr(dpy, default_visual, depth, ZPixmap, 0, NULL, w, h, raw_fb ? 32 : BitmapPad(dpy), 0); X_UNLOCK; if (xim == NULL) { rfbErr("XCreateImage(%s) failed.\n", name); if (quiet) { fprintf(stderr, "XCreateImage(%s) failed.\n", name); } return 0; } if (db) fprintf(stderr, "shm_create simple %d %d\t%p %s\n", w, h, (void *)xim, name); xim->data = (char *) malloc(xim->bytes_per_line * xim->height); if (xim->data == NULL) { rfbErr("XCreateImage(%s) data malloc failed.\n", name); if (quiet) { fprintf(stderr, "XCreateImage(%s) data malloc" " failed.\n", name); } return 0; } if (flip_byte_order) { char *order = flip_ximage_byte_order(xim); if (! reported_flip && ! quiet) { rfbLog("Changing XImage byte order" " to %s\n", order); reported_flip = 1; } } *ximg_ptr = xim; return 1; } if (! dpy) { X_UNLOCK; return 0; } xim = XShmCreateImage_wr(dpy, default_visual, depth, ZPixmap, NULL, shm, w, h); if (xim == NULL) { rfbErr("XShmCreateImage(%s) failed.\n", name); if (quiet) { fprintf(stderr, "XShmCreateImage(%s) failed.\n", name); } X_UNLOCK; return 0; } *ximg_ptr = xim; #if HAVE_XSHM shm->shmid = shmget(IPC_PRIVATE, xim->bytes_per_line * xim->height, IPC_CREAT | 0600); if (shm->shmid == -1) { rfbErr("shmget(%s) failed.\n", name); rfbLogPerror("shmget"); XDestroyImage(xim); *ximg_ptr = NULL; X_UNLOCK; return 0; } shm->shmaddr = xim->data = (char *) shmat(shm->shmid, 0, 0); if (shm->shmaddr == (char *)-1) { rfbErr("shmat(%s) failed.\n", name); rfbLogPerror("shmat"); XDestroyImage(xim); *ximg_ptr = NULL; shmctl(shm->shmid, IPC_RMID, 0); shm->shmid = -1; X_UNLOCK; return 0; } shm->readOnly = False; if (! XShmAttach_wr(dpy, shm)) { rfbErr("XShmAttach(%s) failed.\n", name); XDestroyImage(xim); *ximg_ptr = NULL; shmdt(shm->shmaddr); shm->shmaddr = (char *) -1; shmctl(shm->shmid, IPC_RMID, 0); shm->shmid = -1; X_UNLOCK; return 0; } #endif X_UNLOCK; return 1; } void shm_delete(XShmSegmentInfo *shm) { #if HAVE_XSHM if (getenv("X11VNC_SHM_DEBUG")) fprintf(stderr, "shm_delete: %p\n", (void *) shm); if (shm != NULL && shm->shmaddr != (char *) -1) { shmdt(shm->shmaddr); } if (shm != NULL && shm->shmid != -1) { shmctl(shm->shmid, IPC_RMID, 0); } if (shm != NULL) { shm->shmaddr = (char *) -1; shm->shmid = -1; } #else if (!shm) {} #endif } void shm_clean(XShmSegmentInfo *shm, XImage *xim) { int db = 0; if (db) fprintf(stderr, "shm_clean: called: %p\n", (void *)xim); X_LOCK; #if HAVE_XSHM if (shm != NULL && shm->shmid != -1 && dpy) { if (db) fprintf(stderr, "shm_clean: XShmDetach_wr\n"); XShmDetach_wr(dpy, shm); } #endif if (xim != NULL) { if (! raw_fb_back_to_X) { /* raw_fb hack */ if (xim->bitmap_unit != -1) { if (db) fprintf(stderr, "shm_clean: XDestroyImage %p\n", (void *)xim); XDestroyImage(xim); } else { if (xim->data) { if (db) fprintf(stderr, "shm_clean: free xim->data %p %p\n", (void *)xim, (void *)(xim->data)); free(xim->data); xim->data = NULL; } } } xim = NULL; } X_UNLOCK; shm_delete(shm); } void initialize_polling_images(void) { int i, MB = 1024 * 1024; /* set all shm areas to "none" before trying to create any */ scanline_shm.shmid = -1; scanline_shm.shmaddr = (char *) -1; scanline = NULL; fullscreen_shm.shmid = -1; fullscreen_shm.shmaddr = (char *) -1; fullscreen = NULL; snaprect_shm.shmid = -1; snaprect_shm.shmaddr = (char *) -1; snaprect = NULL; for (i=1; i<=ntiles_x; i++) { tile_row_shm[i].shmid = -1; tile_row_shm[i].shmaddr = (char *) -1; tile_row[i] = NULL; } /* the scanline (e.g. 1280x1) shared memory area image: */ if (! shm_create(&scanline_shm, &scanline, dpy_x, 1, "scanline")) { clean_up_exit(1); } /* * the fullscreen (e.g. 1280x1024/fs_factor) shared memory area image: * (we cut down the size of the shm area to try avoid and shm segment * limits, e.g. the default 1MB on Solaris) */ if (UT.sysname && strstr(UT.sysname, "Linux")) { set_fs_factor(10 * MB); } else { set_fs_factor(1 * MB); } if (fs_frac >= 1.0) { fs_frac = 1.1; fs_factor = 0; } if (! fs_factor) { rfbLog("warning: fullscreen updates are disabled.\n"); } else { if (! shm_create(&fullscreen_shm, &fullscreen, dpy_x, dpy_y/fs_factor, "fullscreen")) { clean_up_exit(1); } } if (use_snapfb) { if (! fs_factor) { rfbLog("warning: disabling -snapfb mode.\n"); use_snapfb = 0; } else if (! shm_create(&snaprect_shm, &snaprect, dpy_x, dpy_y/fs_factor, "snaprect")) { clean_up_exit(1); } } /* * for copy_tiles we need a lot of shared memory areas, one for * each possible run length of changed tiles. 32 for 1024x768 * and 40 for 1280x1024, etc. */ tile_shm_count = 0; for (i=1; i<=ntiles_x; i++) { if (! shm_create(&tile_row_shm[i], &tile_row[i], tile_x * i, tile_y, "tile_row")) { if (i == 1) { clean_up_exit(1); } rfbLog("shm: Error creating shared memory tile-row for" " len=%d,\n", i); rfbLog("shm: reverting to -onetile mode. If this" " problem persists\n"); rfbLog("shm: try using the -onetile or -noshm options" " to limit\n"); rfbLog("shm: shared memory usage, or run ipcrm(1)" " to manually\n"); rfbLog("shm: delete unattached shm segments.\n"); single_copytile_count = i; single_copytile = 1; } tile_shm_count++; if (single_copytile && i >= 1) { /* only need 1x1 tiles */ break; } } if (verbose) { if (using_shm && ! xform24to32) { rfbLog("created %d tile_row shm polling images.\n", tile_shm_count); } else { rfbLog("created %d tile_row polling images.\n", tile_shm_count); } } } /* * A hint is a rectangular region built from 1 or more adjacent tiles * glued together. Ultimately, this information in a single hint is sent * to libvncserver rather than sending each tile separately. */ static void create_tile_hint(int x, int y, int tw, int th, hint_t *hint) { int w = dpy_x - x; int h = dpy_y - y; if (w > tw) { w = tw; } if (h > th) { h = th; } hint->x = x; hint->y = y; hint->w = w; hint->h = h; } static void extend_tile_hint(int x, int y, int tw, int th, hint_t *hint) { int w = dpy_x - x; int h = dpy_y - y; if (w > tw) { w = tw; } if (h > th) { h = th; } if (hint->x > x) { /* extend to the left */ hint->w += hint->x - x; hint->x = x; } if (hint->y > y) { /* extend upward */ hint->h += hint->y - y; hint->y = y; } if (hint->x + hint->w < x + w) { /* extend to the right */ hint->w = x + w - hint->x; } if (hint->y + hint->h < y + h) { /* extend downward */ hint->h = y + h - hint->y; } } static void save_hint(hint_t hint, int loc) { /* simply copy it to the global array for later use. */ hint_list[loc].x = hint.x; hint_list[loc].y = hint.y; hint_list[loc].w = hint.w; hint_list[loc].h = hint.h; } /* * Glue together horizontal "runs" of adjacent changed tiles into one big * rectangle change "hint" to be passed to the vnc machinery. */ static void hint_updates(void) { hint_t hint; int x, y, i, n, ty, th, tx, tw; int hint_count = 0, in_run = 0; hint.x = hint.y = hint.w = hint.h = 0; for (y=0; y < ntiles_y; y++) { for (x=0; x < ntiles_x; x++) { n = x + y * ntiles_x; if (tile_has_diff[n]) { ty = tile_region[n].first_line; th = tile_region[n].last_line - ty + 1; tx = tile_region[n].first_x; tw = tile_region[n].last_x - tx + 1; if (tx < 0) { tx = 0; tw = tile_x; } if (! in_run) { create_tile_hint( x * tile_x + tx, y * tile_y + ty, tw, th, &hint); in_run = 1; } else { extend_tile_hint( x * tile_x + tx, y * tile_y + ty, tw, th, &hint); } } else { if (in_run) { /* end of a row run of altered tiles: */ save_hint(hint, hint_count++); in_run = 0; } } } if (in_run) { /* save the last row run */ save_hint(hint, hint_count++); in_run = 0; } } for (i=0; i < hint_count; i++) { /* pass update info to vnc: */ mark_hint(hint_list[i]); } } /* * kludge, simple ceil+floor for non-negative doubles: */ #define CEIL(x) ( (double) ((int) (x)) == (x) ? \ (double) ((int) (x)) : (double) ((int) (x) + 1) ) #define FLOOR(x) ( (double) ((int) (x)) ) /* * Scaling: * * For shrinking, a destination (scaled) pixel will correspond to more * than one source (i.e. main fb) pixel. Think of an x-y plane made with * graph paper. Each unit square in the graph paper (i.e. collection of * points (x,y) such that N < x < N+1 and M < y < M+1, N and M integers) * corresponds to one pixel in the unscaled fb. There is a solid * color filling the inside of such a square. A scaled pixel has width * 1/scale_fac, e.g. for "-scale 3/4" the width of the scaled pixel * is 1.333. The area of this scaled pixel is 1.333 * 1.333 (so it * obviously overlaps more than one source pixel, each which have area 1). * * We take the weight an unscaled pixel (source) contributes to a * scaled pixel (destination) as simply proportional to the overlap area * between the two pixels. One can then think of the value of the scaled * pixel as an integral over the portion of the graph paper it covers. * The thing being integrated is the color value of the unscaled source. * That color value is constant over a graph paper square (source pixel), * and changes discontinuously from one unit square to the next. * Here is an example for -scale 3/4, the solid lines are the source pixels (graph paper unit squares), while the dotted lines denote the scaled pixels (destination pixels): 0 1 4/3 2 8/3 3 4=12/3 |---------|--.------|------.--|---------|. | | . | . | |. | A | . B | . | |. | | . | . | |. | | . | . | |. 1 |---------|--.------|------.--|---------|. 4/3|.........|.........|.........|.........|. | | . | . | |. | C | . D | . | |. | | . | . | |. 2 |---------|--.------|------.--|---------|. | | . | . | |. | | . | . | |. 8/3|.........|.........|.........|.........|. | | . | . | |. 3 |---------|--.------|------.--|---------|. So we see the first scaled pixel (0 < x < 4/3 and 0 < y < 4/3) mostly overlaps with unscaled source pixel "A". The integration (averaging) weights for this scaled pixel are: A 1 B 1/3 C 1/3 D 1/9 * * The Red, Green, and Blue color values must be averaged over separately * otherwise you can get a complete mess (except in solid regions), * because high order bits are averaged differently from the low order bits. * * So the algorithm is roughly: * * - Given as input a rectangle in the unscaled source fb with changes, * find the rectangle of pixels this affects in the scaled destination fb. * * - For each of the affected scaled (dest) pixels, determine all of the * unscaled (source) pixels it overlaps with. * * - Average those unscaled source values together, weighted by the area * overlap with the destination pixel. Average R, G, B separately. * * - Take this average value and convert to a valid pixel value if * necessary (e.g. rounding, shifting), and then insert it into the * destination framebuffer as the pixel value. * * - On to the next destination pixel... * * ======================================================================== * * For expanding, e.g. -scale 1.1 (which we don't think people will do * very often... or at least so we hope, the framebuffer can become huge) * the situation is reversed and the destination pixel is smaller than a * "graph paper" unit square (source pixel). Some destination pixels * will be completely within a single unscaled source pixel. * * What we do here is a simple 4 point interpolation scheme: * * Let P00 be the source pixel closest to the destination pixel but with * x and y values less than or equal to those of the destination pixel. * (for simplicity, think of the upper left corner of a pixel defining the * x,y location of the pixel, the center would work just as well). So it * is the source pixel immediately to the upper left of the destination * pixel. Let P10 be the source pixel one to the right of P00. Let P01 * be one down from P00. And let P11 be one down and one to the right * of P00. They form a 2x2 square we will interpolate inside of. * * Let V00, V10, V01, and V11 be the color values of those 4 source * pixels. Let dx be the displacement along x the destination pixel is * from P00. Note: 0 <= dx < 1 by definition of P00. Similarly let * dy be the displacement along y. The weighted average for the * interpolation is: * * V_ave = V00 * (1 - dx) * (1 - dy) * + V10 * dx * (1 - dy) * + V01 * (1 - dx) * dy * + V11 * dx * dy * * Note that the weights (1-dx)*(1-dy) + dx*(1-dy) + (1-dx)*dy + dx*dy * automatically add up to 1. It is also nice that all the weights are * positive (unsigned char stays unsigned char). The above formula can * be motivated by doing two 1D interpolations along x: * * VA = V00 * (1 - dx) + V10 * dx * VB = V01 * (1 - dx) + V11 * dx * * and then interpolating VA and VB along y: * * V_ave = VA * (1 - dy) + VB * dy * * VA * v |<-dx->| * -- V00 ------ V10 * dy | | * -- | o...|... "o" denotes the position of the desired * ^ | . | . destination pixel relative to the P00 * | . | . source pixel. * V10 ----.- V11 . * ........ * | * VB * * * Of course R, G, B averages are done separately as in the shrinking * case. This gives reasonable results, and the implementation for * shrinking can simply be used with different choices for weights for * the loop over the 4 pixels. */ void scale_rect(double factor_x, double factor_y, int blend, int interpolate, int Bpp, char *src_fb, int src_bytes_per_line, char *dst_fb, int dst_bytes_per_line, int Nx, int Ny, int nx, int ny, int X1, int Y1, int X2, int Y2, int mark) { /* * Notation: * "i" an x pixel index in the destination (scaled) framebuffer * "j" a y pixel index in the destination (scaled) framebuffer * "I" an x pixel index in the source (un-scaled, i.e. main) framebuffer * "J" a y pixel index in the source (un-scaled, i.e. main) framebuffer * * Similarly for nx, ny, Nx, Ny, etc. Lowercase: dest, Uppercase: source. */ int i, j, i1, i2, j1, j2; /* indices for scaled fb (dest) */ int I, J, I1, I2, J1, J2; /* indices for main fb (source) */ double w, wx, wy, wtot; /* pixel weights */ double x1, y1, x2, y2; /* x-y coords for destination pixels edges */ double dx, dy; /* size of destination pixel */ double ddx=0, ddy=0; /* for interpolation expansion */ char *src, *dest; /* pointers to the two framebuffers */ unsigned short us = 0; unsigned char uc = 0; unsigned int ui = 0; int use_noblend_shortcut = 1; int shrink; /* whether shrinking or expanding */ static int constant_weights = -1, mag_int = -1; static int last_Nx = -1, last_Ny = -1, cnt = 0; static double last_factor = -1.0; int b, k; double pixave[4]; /* for averaging pixel values */ if (factor_x <= 1.0 && factor_y <= 1.0) { shrink = 1; } else { shrink = 0; } /* * N.B. width and height (real numbers) of a scaled pixel. * both are > 1 (e.g. 1.333 for -scale 3/4) * they should also be equal but we don't assume it. * * This new way is probably the best we can do, take the inverse * of the scaling factor to double precision. */ dx = 1.0/factor_x; dy = 1.0/factor_y; /* * There is some speedup if the pixel weights are constant, so * let's special case these. * * If scale = 1/n and n divides Nx and Ny, the pixel weights * are constant (e.g. 1/2 => equal on 2x2 square). */ if (factor_x != last_factor || Nx != last_Nx || Ny != last_Ny) { constant_weights = -1; mag_int = -1; last_Nx = Nx; last_Ny = Ny; last_factor = factor_x; } if (constant_weights < 0 && factor_x != factor_y) { constant_weights = 0; mag_int = 0; } else if (constant_weights < 0) { int n = 0; constant_weights = 0; mag_int = 0; for (i = 2; i<=128; i++) { double test = ((double) 1)/ i; double diff, eps = 1.0e-7; diff = factor_x - test; if (-eps < diff && diff < eps) { n = i; break; } } if (! blend || ! shrink || interpolate) { ; } else if (n != 0) { if (Nx % n == 0 && Ny % n == 0) { static int didmsg = 0; if (mark && ! didmsg) { didmsg = 1; rfbLog("scale_and_mark_rect: using " "constant pixel weight speedup " "for 1/%d\n", n); } constant_weights = 1; } } n = 0; for (i = 2; i<=32; i++) { double test = (double) i; double diff, eps = 1.0e-7; diff = factor_x - test; if (-eps < diff && diff < eps) { n = i; break; } } if (! blend && factor_x > 1.0 && n) { mag_int = n; } } if (mark && factor_x > 1.0 && blend) { /* * kludge: correct for interpolating blurring leaking * up or left 1 destination pixel. */ if (X1 > 0) X1--; if (Y1 > 0) Y1--; } /* * find the extent of the change the input rectangle induces in * the scaled framebuffer. */ /* Left edges: find largest i such that i * dx <= X1 */ i1 = FLOOR(X1/dx); /* Right edges: find smallest i such that (i+1) * dx >= X2+1 */ i2 = CEIL( (X2+1)/dx ) - 1; /* To be safe, correct any overflows: */ i1 = nfix(i1, nx); i2 = nfix(i2, nx) + 1; /* add 1 to make a rectangle upper boundary */ /* Repeat above for y direction: */ j1 = FLOOR(Y1/dy); j2 = CEIL( (Y2+1)/dy ) - 1; j1 = nfix(j1, ny); j2 = nfix(j2, ny) + 1; /* * special case integer magnification with no blending. * vision impaired magnification usage is interested in this case. */ if (mark && ! blend && mag_int && Bpp != 3) { int jmin, jmax, imin, imax; /* outer loop over *source* pixels */ for (J=Y1; J < Y2; J++) { jmin = J * mag_int; jmax = jmin + mag_int; for (I=X1; I < X2; I++) { /* extract value */ src = src_fb + J*src_bytes_per_line + I*Bpp; if (Bpp == 4) { ui = *((unsigned int *)src); } else if (Bpp == 2) { us = *((unsigned short *)src); } else if (Bpp == 1) { uc = *((unsigned char *)src); } imin = I * mag_int; imax = imin + mag_int; /* inner loop over *dest* pixels */ for (j=jmin; j<jmax; j++) { dest = dst_fb + j*dst_bytes_per_line + imin*Bpp; for (i=imin; i<imax; i++) { if (Bpp == 4) { *((unsigned int *)dest) = ui; } else if (Bpp == 2) { *((unsigned short *)dest) = us; } else if (Bpp == 1) { *((unsigned char *)dest) = uc; } dest += Bpp; } } } } goto markit; } /* set these all to 1.0 to begin with */ wx = 1.0; wy = 1.0; w = 1.0; /* * Loop over destination pixels in scaled fb: */ for (j=j1; j<j2; j++) { y1 = j * dy; /* top edge */ if (y1 > Ny - 1) { /* can go over with dy = 1/scale_fac */ y1 = Ny - 1; } y2 = y1 + dy; /* bottom edge */ /* Find main fb indices covered by this dest pixel: */ J1 = (int) FLOOR(y1); J1 = nfix(J1, Ny); if (shrink && ! interpolate) { J2 = (int) CEIL(y2) - 1; J2 = nfix(J2, Ny); } else { J2 = J1 + 1; /* simple interpolation */ ddy = y1 - J1; } /* destination char* pointer: */ dest = dst_fb + j*dst_bytes_per_line + i1*Bpp; for (i=i1; i<i2; i++) { x1 = i * dx; /* left edge */ if (x1 > Nx - 1) { /* can go over with dx = 1/scale_fac */ x1 = Nx - 1; } x2 = x1 + dx; /* right edge */ cnt++; /* Find main fb indices covered by this dest pixel: */ I1 = (int) FLOOR(x1); if (I1 >= Nx) I1 = Nx - 1; if (! blend && use_noblend_shortcut) { /* * The noblend case involves no weights, * and 1 pixel, so just copy the value * directly. */ src = src_fb + J1*src_bytes_per_line + I1*Bpp; if (Bpp == 4) { *((unsigned int *)dest) = *((unsigned int *)src); } else if (Bpp == 2) { *((unsigned short *)dest) = *((unsigned short *)src); } else if (Bpp == 1) { *(dest) = *(src); } else if (Bpp == 3) { /* rare case */ for (k=0; k<=2; k++) { *(dest+k) = *(src+k); } } dest += Bpp; continue; } if (shrink && ! interpolate) { I2 = (int) CEIL(x2) - 1; if (I2 >= Nx) I2 = Nx - 1; } else { I2 = I1 + 1; /* simple interpolation */ ddx = x1 - I1; } /* Zero out accumulators for next pixel average: */ for (b=0; b<4; b++) { pixave[b] = 0.0; /* for RGB weighted sums */ } /* * wtot is for accumulating the total weight. * It should always sum to 1/(scale_fac * scale_fac). */ wtot = 0.0; /* * Loop over source pixels covered by this dest pixel. * * These "extra" loops over "J" and "I" make * the cache/cacheline performance unclear. * For example, will the data brought in from * src for j, i, and J=0 still be in the cache * after the J > 0 data have been accessed and * we are at j, i+1, J=0? The stride in J is * main_bytes_per_line, and so ~4 KB. * * Typical case when shrinking are 2x2 loop, so * just two lines to worry about. */ for (J=J1; J<=J2; J++) { /* see comments for I, x1, x2, etc. below */ if (constant_weights) { ; } else if (! blend) { if (J != J1) { continue; } wy = 1.0; /* interpolation scheme: */ } else if (! shrink || interpolate) { if (J >= Ny) { continue; } else if (J == J1) { wy = 1.0 - ddy; } else if (J != J1) { wy = ddy; } /* integration scheme: */ } else if (J < y1) { wy = J+1 - y1; } else if (J+1 > y2) { wy = y2 - J; } else { wy = 1.0; } src = src_fb + J*src_bytes_per_line + I1*Bpp; for (I=I1; I<=I2; I++) { /* Work out the weight: */ if (constant_weights) { ; } else if (! blend) { /* * Ugh, PseudoColor colormap is * bad news, to avoid random * colors just take the first * pixel. Or user may have * specified :nb to fraction. * The :fb will force blending * for this case. */ if (I != I1) { continue; } wx = 1.0; /* interpolation scheme: */ } else if (! shrink || interpolate) { if (I >= Nx) { continue; /* off edge */ } else if (I == I1) { wx = 1.0 - ddx; } else if (I != I1) { wx = ddx; } /* integration scheme: */ } else if (I < x1) { /* * source left edge (I) to the * left of dest left edge (x1): * fractional weight */ wx = I+1 - x1; } else if (I+1 > x2) { /* * source right edge (I+1) to the * right of dest right edge (x2): * fractional weight */ wx = x2 - I; } else { /* * source edges (I and I+1) completely * inside dest edges (x1 and x2): * full weight */ wx = 1.0; } w = wx * wy; wtot += w; /* * We average the unsigned char value * instead of char value: otherwise * the minimum (char 0) is right next * to the maximum (char -1)! This way * they are spread between 0 and 255. */ if (Bpp == 4) { /* unroll the loops, can give 20% */ pixave[0] += w * ((unsigned char) *(src )); pixave[1] += w * ((unsigned char) *(src+1)); pixave[2] += w * ((unsigned char) *(src+2)); pixave[3] += w * ((unsigned char) *(src+3)); } else if (Bpp == 2) { /* * 16bpp: trickier with green * split over two bytes, so we * use the masks: */ us = *((unsigned short *) src); pixave[0] += w*(us & main_red_mask); pixave[1] += w*(us & main_green_mask); pixave[2] += w*(us & main_blue_mask); } else if (Bpp == 1) { pixave[0] += w * ((unsigned char) *(src)); } else { for (b=0; b<Bpp; b++) { pixave[b] += w * ((unsigned char) *(src+b)); } } src += Bpp; } } if (wtot <= 0.0) { wtot = 1.0; } wtot = 1.0/wtot; /* normalization factor */ /* place weighted average pixel in the scaled fb: */ if (Bpp == 4) { *(dest ) = (char) (wtot * pixave[0]); *(dest+1) = (char) (wtot * pixave[1]); *(dest+2) = (char) (wtot * pixave[2]); *(dest+3) = (char) (wtot * pixave[3]); } else if (Bpp == 2) { /* 16bpp / 565 case: */ pixave[0] *= wtot; pixave[1] *= wtot; pixave[2] *= wtot; us = (main_red_mask & (int) pixave[0]) | (main_green_mask & (int) pixave[1]) | (main_blue_mask & (int) pixave[2]); *( (unsigned short *) dest ) = us; } else if (Bpp == 1) { *(dest) = (char) (wtot * pixave[0]); } else { for (b=0; b<Bpp; b++) { *(dest+b) = (char) (wtot * pixave[b]); } } dest += Bpp; } } markit: if (mark) { mark_rect_as_modified(i1, j1, i2, j2, 1); } } /* Framebuffers data flow: General case: -------- -------- -------- -------- ----- |8to24_fb| |main_fb | |snap_fb | | X | |rfbfb| <== | | <== | | <== | | <== | Server | ----- -------- -------- -------- -------- (to vnc) (optional) (usu = rfbfb) (optional) (read only) 8to24_fb mode will create side fbs: poll24_fb and poll8_fb for bookkeepping the different regions (merged into 8to24_fb). Normal case: -------- -------- |main_fb | | X | |= rfb_fb| <== | Server | -------- -------- Scaling case: -------- -------- ----- |main_fb | | X | |rfbfb| <== | | <== | Server | ----- -------- -------- Webcam/video case: -------- -------- -------- |main_fb | |snap_fb | | Video | | | <== | | <== | device | -------- -------- -------- If we ever do a -rr rotation/reflection tran, it probably should be done after any scaling (need a rr_fb for intermediate results) -rr option: transformation: none x -> x; y -> y; x x -> w - x - 1; y -> y; y x -> x; x -> h - y - 1; xy x -> w - x - 1; y -> h - y - 1; +90 x -> h - y - 1; y -> x; +90x x -> y; y -> x; +90y x -> h - y - 1; y -> w - x - 1; -90 x -> y; y -> w - x - 1; some aliases: xy: yx, +180, -180, 180 +90: 90 +90x: 90x +90y: 90y -90: +270, 270 */ void scale_and_mark_rect(int X1, int Y1, int X2, int Y2, int mark) { char *dst_fb, *src_fb = main_fb; int dst_bpl, Bpp = bpp/8, fac = 1; if (!screen || !rfb_fb || !main_fb) { return; } if (! screen->serverFormat.trueColour) { /* * PseudoColor colormap... blending leads to random colors. * User can override with ":fb" */ if (scaling_blend == 1) { /* :fb option sets it to 2 */ if (default_visual->class == StaticGray) { /* * StaticGray can be blended OK, otherwise * user can disable with :nb */ ; } else { scaling_blend = 0; } } } if (cmap8to24 && cmap8to24_fb) { src_fb = cmap8to24_fb; if (scaling) { if (depth <= 8) { fac = 4; } else if (depth <= 16) { fac = 2; } } } dst_fb = rfb_fb; dst_bpl = rfb_bytes_per_line; scale_rect(scale_fac_x, scale_fac_y, scaling_blend, scaling_interpolate, fac * Bpp, src_fb, fac * main_bytes_per_line, dst_fb, dst_bpl, dpy_x, dpy_y, scaled_x, scaled_y, X1, Y1, X2, Y2, mark); } void rotate_coords(int x, int y, int *xo, int *yo, int dxi, int dyi) { int xi = x, yi = y; int Dx, Dy; if (dxi >= 0) { Dx = dxi; Dy = dyi; } else if (scaling) { Dx = scaled_x; Dy = scaled_y; } else { Dx = dpy_x; Dy = dpy_y; } /* ncache?? */ if (rotating == ROTATE_NONE) { *xo = xi; *yo = yi; } else if (rotating == ROTATE_X) { *xo = Dx - xi - 1; *yo = yi; } else if (rotating == ROTATE_Y) { *xo = xi; *yo = Dy - yi - 1; } else if (rotating == ROTATE_XY) { *xo = Dx - xi - 1; *yo = Dy - yi - 1; } else if (rotating == ROTATE_90) { *xo = Dy - yi - 1; *yo = xi; } else if (rotating == ROTATE_90X) { *xo = yi; *yo = xi; } else if (rotating == ROTATE_90Y) { *xo = Dy - yi - 1; *yo = Dx - xi - 1; } else if (rotating == ROTATE_270) { *xo = yi; *yo = Dx - xi - 1; } } void rotate_coords_inverse(int x, int y, int *xo, int *yo, int dxi, int dyi) { int xi = x, yi = y; int Dx, Dy; if (dxi >= 0) { Dx = dxi; Dy = dyi; } else if (scaling) { Dx = scaled_x; Dy = scaled_y; } else { Dx = dpy_x; Dy = dpy_y; } if (! rotating_same) { int t = Dx; Dx = Dy; Dy = t; } if (rotating == ROTATE_NONE) { *xo = xi; *yo = yi; } else if (rotating == ROTATE_X) { *xo = Dx - xi - 1; *yo = yi; } else if (rotating == ROTATE_Y) { *xo = xi; *yo = Dy - yi - 1; } else if (rotating == ROTATE_XY) { *xo = Dx - xi - 1; *yo = Dy - yi - 1; } else if (rotating == ROTATE_90) { *xo = yi; *yo = Dx - xi - 1; } else if (rotating == ROTATE_90X) { *xo = yi; *yo = xi; } else if (rotating == ROTATE_90Y) { *xo = Dy - yi - 1; *yo = Dx - xi - 1; } else if (rotating == ROTATE_270) { *xo = Dy - yi - 1; *yo = xi; } } /* unroll the Bpp loop to be used in each case: */ #define ROT_COPY \ src = src_0 + fbl*y + Bpp*x; \ dst = dst_0 + rbl*yn + Bpp*xn; \ if (Bpp == 1) { \ *(dst) = *(src); \ } else if (Bpp == 2) { \ *(dst+0) = *(src+0); \ *(dst+1) = *(src+1); \ } else if (Bpp == 3) { \ *(dst+0) = *(src+0); \ *(dst+1) = *(src+1); \ *(dst+2) = *(src+2); \ } else if (Bpp == 4) { \ *(dst+0) = *(src+0); \ *(dst+1) = *(src+1); \ *(dst+2) = *(src+2); \ *(dst+3) = *(src+3); \ } void rotate_fb(int x1, int y1, int x2, int y2) { int x, y, xn, yn, r_x1, r_y1, r_x2, r_y2, Bpp = bpp/8; int fbl = rfb_bytes_per_line; int rbl = rot_bytes_per_line; int Dx, Dy; char *src, *dst; char *src_0 = rfb_fb; char *dst_0 = rot_fb; if (! rotating || ! rot_fb) { return; } if (scaling) { Dx = scaled_x; Dy = scaled_y; } else { Dx = dpy_x; Dy = dpy_y; } rotate_coords(x1, y1, &r_x1, &r_y1, -1, -1); rotate_coords(x2, y2, &r_x2, &r_y2, -1, -1); dst = rot_fb; if (rotating == ROTATE_X) { for (y = y1; y < y2; y++) { for (x = x1; x < x2; x++) { xn = Dx - x - 1; yn = y; ROT_COPY } } } else if (rotating == ROTATE_Y) { for (y = y1; y < y2; y++) { for (x = x1; x < x2; x++) { xn = x; yn = Dy - y - 1; ROT_COPY } } } else if (rotating == ROTATE_XY) { for (y = y1; y < y2; y++) { for (x = x1; x < x2; x++) { xn = Dx - x - 1; yn = Dy - y - 1; ROT_COPY } } } else if (rotating == ROTATE_90) { for (y = y1; y < y2; y++) { for (x = x1; x < x2; x++) { xn = Dy - y - 1; yn = x; ROT_COPY } } } else if (rotating == ROTATE_90X) { for (y = y1; y < y2; y++) { for (x = x1; x < x2; x++) { xn = y; yn = x; ROT_COPY } } } else if (rotating == ROTATE_90Y) { for (y = y1; y < y2; y++) { for (x = x1; x < x2; x++) { xn = Dy - y - 1; yn = Dx - x - 1; ROT_COPY } } } else if (rotating == ROTATE_270) { for (y = y1; y < y2; y++) { for (x = x1; x < x2; x++) { xn = y; yn = Dx - x - 1; ROT_COPY } } } } void rotate_curs(char *dst_0, char *src_0, int Dx, int Dy, int Bpp) { int x, y, xn, yn; char *src, *dst; int fbl, rbl; if (! rotating) { return; } fbl = Dx * Bpp; if (rotating_same) { rbl = Dx * Bpp; } else { rbl = Dy * Bpp; } if (rotating == ROTATE_X) { for (y = 0; y < Dy; y++) { for (x = 0; x < Dx; x++) { xn = Dx - x - 1; yn = y; ROT_COPY if (0) fprintf(stderr, "rcurs: %d %d %d %d\n", x, y, xn, yn); } } } else if (rotating == ROTATE_Y) { for (y = 0; y < Dy; y++) { for (x = 0; x < Dx; x++) { xn = x; yn = Dy - y - 1; ROT_COPY } } } else if (rotating == ROTATE_XY) { for (y = 0; y < Dy; y++) { for (x = 0; x < Dx; x++) { xn = Dx - x - 1; yn = Dy - y - 1; ROT_COPY } } } else if (rotating == ROTATE_90) { for (y = 0; y < Dy; y++) { for (x = 0; x < Dx; x++) { xn = Dy - y - 1; yn = x; ROT_COPY } } } else if (rotating == ROTATE_90X) { for (y = 0; y < Dy; y++) { for (x = 0; x < Dx; x++) { xn = y; yn = x; ROT_COPY } } } else if (rotating == ROTATE_90Y) { for (y = 0; y < Dy; y++) { for (x = 0; x < Dx; x++) { xn = Dy - y - 1; yn = Dx - x - 1; ROT_COPY } } } else if (rotating == ROTATE_270) { for (y = 0; y < Dy; y++) { for (x = 0; x < Dx; x++) { xn = y; yn = Dx - x - 1; ROT_COPY } } } } void mark_wrapper(int x1, int y1, int x2, int y2) { int t, r_x1 = x1, r_y1 = y1, r_x2 = x2, r_y2 = y2; if (rotating) { /* well we hope rot_fb will always be the last one... */ rotate_coords(x1, y1, &r_x1, &r_y1, -1, -1); rotate_coords(x2, y2, &r_x2, &r_y2, -1, -1); rotate_fb(x1, y1, x2, y2); if (r_x1 > r_x2) { t = r_x1; r_x1 = r_x2; r_x2 = t; } if (r_y1 > r_y2) { t = r_y1; r_y1 = r_y2; r_y2 = t; } /* painting errors */ r_x1--; r_x2++; r_y1--; r_y2++; } rfbMarkRectAsModified(screen, r_x1, r_y1, r_x2, r_y2); } void mark_rect_as_modified(int x1, int y1, int x2, int y2, int force) { if (damage_time != 0) { /* * This is not XDAMAGE, rather a hack for testing * where we allow the framebuffer to be corrupted for * damage_delay seconds. */ int debug = 0; if (time(NULL) > damage_time + damage_delay) { if (! quiet) { rfbLog("damaging turned off.\n"); } damage_time = 0; damage_delay = 0; } else { if (debug) { rfbLog("damaging viewer fb by not marking " "rect: %d,%d,%d,%d\n", x1, y1, x2, y2); } return; } } if (rfb_fb == main_fb || force) { mark_wrapper(x1, y1, x2, y2); return; } if (cmap8to24) { bpp8to24(x1, y1, x2, y2); } if (scaling) { scale_and_mark_rect(x1, y1, x2, y2, 1); } else { mark_wrapper(x1, y1, x2, y2); } } /* * Notifies libvncserver of a changed hint rectangle. */ static void mark_hint(hint_t hint) { int x = hint.x; int y = hint.y; int w = hint.w; int h = hint.h; mark_rect_as_modified(x, y, x + w, y + h, 0); } /* * copy_tiles() gives a slight improvement over copy_tile() since * adjacent runs of tiles are done all at once there is some savings * due to contiguous memory access. Not a great speedup, but in some * cases it can be up to 2X. Even more on a SunRay or ShadowFB where * no graphics hardware is involved in the read. Generally, graphics * devices are optimized for write, not read, so we are limited by the * read bandwidth, sometimes only 5 MB/sec on otherwise fast hardware. */ static int *first_line = NULL, *last_line = NULL; static unsigned short *left_diff = NULL, *right_diff = NULL; static int copy_tiles(int tx, int ty, int nt) { int x, y, line; int size_x, size_y, width1, width2; int off, len, n, dw, dx, t; int w1, w2, dx1, dx2; /* tmps for normal and short tiles */ int pixelsize = bpp/8; int first_min, last_max; int first_x = -1, last_x = -1; static int prev_ntiles_x = -1; char *src, *dst, *s_src, *s_dst, *m_src, *m_dst; char *h_src, *h_dst; if (unixpw_in_progress) return 0; if (ntiles_x != prev_ntiles_x && first_line != NULL) { free(first_line); first_line = NULL; free(last_line); last_line = NULL; free(left_diff); left_diff = NULL; free(right_diff); right_diff = NULL; } if (first_line == NULL) { /* allocate arrays first time in. */ int n = ntiles_x + 1; rfbLog("copy_tiles: allocating first_line at size %d\n", n); first_line = (int *) malloc((size_t) (n * sizeof(int))); last_line = (int *) malloc((size_t) (n * sizeof(int))); left_diff = (unsigned short *) malloc((size_t) (n * sizeof(unsigned short))); right_diff = (unsigned short *) malloc((size_t) (n * sizeof(unsigned short))); } prev_ntiles_x = ntiles_x; x = tx * tile_x; y = ty * tile_y; size_x = dpy_x - x; if ( size_x > tile_x * nt ) { size_x = tile_x * nt; width1 = tile_x; width2 = tile_x; } else { /* short tile */ width1 = tile_x; /* internal tile */ width2 = size_x - (nt - 1) * tile_x; /* right hand tile */ } size_y = dpy_y - y; if ( size_y > tile_y ) { size_y = tile_y; } n = tx + ty * ntiles_x; /* number of the first tile */ if (blackouts && tile_blackout[n].cover == 2) { /* * If there are blackouts and this tile is completely covered * no need to poll screen or do anything else.. * n.b. we are in single copy_tile mode: nt=1 */ tile_has_diff[n] = 0; return(0); } X_LOCK; XRANDR_SET_TRAP_RET(-1, "copy_tile-set"); /* read in the whole tile run at once: */ copy_image(tile_row[nt], x, y, size_x, size_y); XRANDR_CHK_TRAP_RET(-1, "copy_tile-chk"); X_UNLOCK; if (blackouts && tile_blackout[n].cover == 1) { /* * If there are blackouts and this tile is partially covered * we should re-black-out the portion. * n.b. we are in single copy_tile mode: nt=1 */ int x1, x2, y1, y2, b; int w, s, fill = 0; for (b=0; b < tile_blackout[n].count; b++) { char *b_dst = tile_row[nt]->data; x1 = tile_blackout[n].bo[b].x1 - x; y1 = tile_blackout[n].bo[b].y1 - y; x2 = tile_blackout[n].bo[b].x2 - x; y2 = tile_blackout[n].bo[b].y2 - y; w = (x2 - x1) * pixelsize; s = x1 * pixelsize; for (line = 0; line < size_y; line++) { if (y1 <= line && line < y2) { memset(b_dst + s, fill, (size_t) w); } b_dst += tile_row[nt]->bytes_per_line; } } } src = tile_row[nt]->data; dst = main_fb + y * main_bytes_per_line + x * pixelsize; s_src = src; s_dst = dst; for (t=1; t <= nt; t++) { first_line[t] = -1; } /* find the first line with difference: */ w1 = width1 * pixelsize; w2 = width2 * pixelsize; /* foreach line: */ for (line = 0; line < size_y; line++) { /* foreach horizontal tile: */ for (t=1; t <= nt; t++) { if (first_line[t] != -1) { continue; } off = (t-1) * w1; if (t == nt) { len = w2; /* possible short tile */ } else { len = w1; } if (memcmp(s_dst + off, s_src + off, len)) { first_line[t] = line; } } s_src += tile_row[nt]->bytes_per_line; s_dst += main_bytes_per_line; } /* see if there were any differences for any tile: */ first_min = -1; for (t=1; t <= nt; t++) { tile_tried[n+(t-1)] = 1; if (first_line[t] != -1) { if (first_min == -1 || first_line[t] < first_min) { first_min = first_line[t]; } } } if (first_min == -1) { /* no tile has a difference, note this and get out: */ for (t=1; t <= nt; t++) { tile_has_diff[n+(t-1)] = 0; } return(0); } else { /* * at least one tile has a difference. make sure info * is recorded (e.g. sometimes we guess tiles and they * came in with tile_has_diff 0) */ for (t=1; t <= nt; t++) { if (first_line[t] == -1) { tile_has_diff[n+(t-1)] = 0; } else { tile_has_diff[n+(t-1)] = 1; } } } m_src = src + (tile_row[nt]->bytes_per_line * size_y); m_dst = dst + (main_bytes_per_line * size_y); for (t=1; t <= nt; t++) { last_line[t] = first_line[t]; } /* find the last line with difference: */ w1 = width1 * pixelsize; w2 = width2 * pixelsize; /* foreach line: */ for (line = size_y - 1; line > first_min; line--) { m_src -= tile_row[nt]->bytes_per_line; m_dst -= main_bytes_per_line; /* foreach tile: */ for (t=1; t <= nt; t++) { if (first_line[t] == -1 || last_line[t] != first_line[t]) { /* tile has no changes or already done */ continue; } off = (t-1) * w1; if (t == nt) { len = w2; /* possible short tile */ } else { len = w1; } if (memcmp(m_dst + off, m_src + off, len)) { last_line[t] = line; } } } /* * determine the farthest down last changed line * will be used below to limit our memcpy() to the framebuffer. */ last_max = -1; for (t=1; t <= nt; t++) { if (first_line[t] == -1) { continue; } if (last_max == -1 || last_line[t] > last_max) { last_max = last_line[t]; } } /* look for differences on left and right hand edges: */ for (t=1; t <= nt; t++) { left_diff[t] = 0; right_diff[t] = 0; } h_src = src; h_dst = dst; w1 = width1 * pixelsize; w2 = width2 * pixelsize; dx1 = (width1 - tile_fuzz) * pixelsize; dx2 = (width2 - tile_fuzz) * pixelsize; dw = tile_fuzz * pixelsize; /* foreach line: */ for (line = 0; line < size_y; line++) { /* foreach tile: */ for (t=1; t <= nt; t++) { if (first_line[t] == -1) { /* tile has no changes at all */ continue; } off = (t-1) * w1; if (t == nt) { dx = dx2; /* possible short tile */ if (dx <= 0) { break; } } else { dx = dx1; } if (! left_diff[t] && memcmp(h_dst + off, h_src + off, dw)) { left_diff[t] = 1; } if (! right_diff[t] && memcmp(h_dst + off + dx, h_src + off + dx, dw) ) { right_diff[t] = 1; } } h_src += tile_row[nt]->bytes_per_line; h_dst += main_bytes_per_line; } /* now finally copy the difference to the rfb framebuffer: */ s_src = src + tile_row[nt]->bytes_per_line * first_min; s_dst = dst + main_bytes_per_line * first_min; for (line = first_min; line <= last_max; line++) { /* for I/O speed we do not do this tile by tile */ memcpy(s_dst, s_src, size_x * pixelsize); if (nt == 1) { /* * optimization for tall skinny lines, e.g. wm * frame. try to find first_x and last_x to limit * the size of the hint. could help for a slow * link. Unfortunately we spent a lot of time * reading in the many tiles. * * BTW, we like to think the above memcpy leaves * the data we use below in the cache... (but * it could be two 128 byte segments at 32bpp) * so this inner loop is not as bad as it seems. */ int k, kx; kx = pixelsize; for (k=0; k<size_x; k++) { if (memcmp(s_dst + k*kx, s_src + k*kx, kx)) { if (first_x == -1 || k < first_x) { first_x = k; } if (last_x == -1 || k > last_x) { last_x = k; } } } } s_src += tile_row[nt]->bytes_per_line; s_dst += main_bytes_per_line; } /* record all the info in the region array for this tile: */ for (t=1; t <= nt; t++) { int s = t - 1; if (first_line[t] == -1) { /* tile unchanged */ continue; } tile_region[n+s].first_line = first_line[t]; tile_region[n+s].last_line = last_line[t]; tile_region[n+s].first_x = first_x; tile_region[n+s].last_x = last_x; tile_region[n+s].top_diff = 0; tile_region[n+s].bot_diff = 0; if ( first_line[t] < tile_fuzz ) { tile_region[n+s].top_diff = 1; } if ( last_line[t] > (size_y - 1) - tile_fuzz ) { tile_region[n+s].bot_diff = 1; } tile_region[n+s].left_diff = left_diff[t]; tile_region[n+s].right_diff = right_diff[t]; tile_copied[n+s] = 1; } return(1); } /* * The copy_tile() call in the loop below copies the changed tile into * the rfb framebuffer. Note that copy_tile() sets the tile_region * struct to have info about the y-range of the changed region and also * whether the tile edges contain diffs (within distance tile_fuzz). * * We use this tile_region info to try to guess if the downward and right * tiles will have diffs. These tiles will be checked later in the loop * (since y+1 > y and x+1 > x). * * See copy_tiles_backward_pass() for analogous checking upward and * left tiles. */ static int copy_all_tiles(void) { int x, y, n, m; int diffs = 0, ct; if (unixpw_in_progress) return 0; for (y=0; y < ntiles_y; y++) { for (x=0; x < ntiles_x; x++) { n = x + y * ntiles_x; if (tile_has_diff[n]) { ct = copy_tiles(x, y, 1); if (ct < 0) return ct; /* fatal */ } if (! tile_has_diff[n]) { /* * n.b. copy_tiles() may have detected * no change and reset tile_has_diff to 0. */ continue; } diffs++; /* neighboring tile downward: */ if ( (y+1) < ntiles_y && tile_region[n].bot_diff) { m = x + (y+1) * ntiles_x; if (! tile_has_diff[m]) { tile_has_diff[m] = 2; } } /* neighboring tile to right: */ if ( (x+1) < ntiles_x && tile_region[n].right_diff) { m = (x+1) + y * ntiles_x; if (! tile_has_diff[m]) { tile_has_diff[m] = 2; } } } } return diffs; } /* * Routine analogous to copy_all_tiles() above, but for horizontal runs * of adjacent changed tiles. */ static int copy_all_tile_runs(void) { int x, y, n, m, i; int diffs = 0, ct; int in_run = 0, run = 0; int ntave = 0, ntcnt = 0; if (unixpw_in_progress) return 0; for (y=0; y < ntiles_y; y++) { for (x=0; x < ntiles_x + 1; x++) { n = x + y * ntiles_x; if (x != ntiles_x && tile_has_diff[n]) { in_run = 1; run++; } else { if (! in_run) { in_run = 0; run = 0; continue; } ct = copy_tiles(x - run, y, run); if (ct < 0) return ct; /* fatal */ ntcnt++; ntave += run; diffs += run; /* neighboring tile downward: */ for (i=1; i <= run; i++) { if ((y+1) < ntiles_y && tile_region[n-i].bot_diff) { m = (x-i) + (y+1) * ntiles_x; if (! tile_has_diff[m]) { tile_has_diff[m] = 2; } } } /* neighboring tile to right: */ if (((x-1)+1) < ntiles_x && tile_region[n-1].right_diff) { m = ((x-1)+1) + y * ntiles_x; if (! tile_has_diff[m]) { tile_has_diff[m] = 2; } /* note that this starts a new run */ in_run = 1; run = 1; } else { in_run = 0; run = 0; } } } /* * Could some activity go here, to emulate threaded * behavior by servicing some libvncserver tasks? */ } return diffs; } /* * Here starts a bunch of heuristics to guess/detect changed tiles. * They are: * copy_tiles_backward_pass, fill_tile_gaps/gap_try, grow_islands/island_try */ /* * Try to predict whether the upward and/or leftward tile has been modified. * copy_all_tiles() has already done downward and rightward tiles. */ static int copy_tiles_backward_pass(void) { int x, y, n, m; int diffs = 0, ct; if (unixpw_in_progress) return 0; for (y = ntiles_y - 1; y >= 0; y--) { for (x = ntiles_x - 1; x >= 0; x--) { n = x + y * ntiles_x; /* number of this tile */ if (! tile_has_diff[n]) { continue; } m = x + (y-1) * ntiles_x; /* neighboring tile upward */ if (y >= 1 && ! tile_has_diff[m] && tile_region[n].top_diff) { if (! tile_tried[m]) { tile_has_diff[m] = 2; ct = copy_tiles(x, y-1, 1); if (ct < 0) return ct; /* fatal */ } } m = (x-1) + y * ntiles_x; /* neighboring tile to left */ if (x >= 1 && ! tile_has_diff[m] && tile_region[n].left_diff) { if (! tile_tried[m]) { tile_has_diff[m] = 2; ct = copy_tiles(x-1, y, 1); if (ct < 0) return ct; /* fatal */ } } } } for (n=0; n < ntiles; n++) { if (tile_has_diff[n]) { diffs++; } } return diffs; } static int copy_tiles_additional_pass(void) { int x, y, n; int diffs = 0, ct; if (unixpw_in_progress) return 0; for (y=0; y < ntiles_y; y++) { for (x=0; x < ntiles_x; x++) { n = x + y * ntiles_x; /* number of this tile */ if (! tile_has_diff[n]) { continue; } if (tile_copied[n]) { continue; } ct = copy_tiles(x, y, 1); if (ct < 0) return ct; /* fatal */ } } for (n=0; n < ntiles; n++) { if (tile_has_diff[n]) { diffs++; } } return diffs; } static int gap_try(int x, int y, int *run, int *saw, int along_x) { int n, m, i, xt, yt, ct; n = x + y * ntiles_x; if (! tile_has_diff[n]) { if (*saw) { (*run)++; /* extend the gap run. */ } return 0; } if (! *saw || *run == 0 || *run > gaps_fill) { *run = 0; /* unacceptable run. */ *saw = 1; return 0; } for (i=1; i <= *run; i++) { /* iterate thru the run. */ if (along_x) { xt = x - i; yt = y; } else { xt = x; yt = y - i; } m = xt + yt * ntiles_x; if (tile_tried[m]) { /* do not repeat tiles */ continue; } ct = copy_tiles(xt, yt, 1); if (ct < 0) return ct; /* fatal */ } *run = 0; *saw = 1; return 1; } /* * Look for small gaps of unchanged tiles that may actually contain changes. * E.g. when paging up and down in a web broswer or terminal there can * be a distracting delayed filling in of such gaps. gaps_fill is the * tweak parameter that sets the width of the gaps that are checked. * * BTW, grow_islands() is actually pretty successful at doing this too... */ static int fill_tile_gaps(void) { int x, y, run, saw; int n, diffs = 0, ct; /* horizontal: */ for (y=0; y < ntiles_y; y++) { run = 0; saw = 0; for (x=0; x < ntiles_x; x++) { ct = gap_try(x, y, &run, &saw, 1); if (ct < 0) return ct; /* fatal */ } } /* vertical: */ for (x=0; x < ntiles_x; x++) { run = 0; saw = 0; for (y=0; y < ntiles_y; y++) { ct = gap_try(x, y, &run, &saw, 0); if (ct < 0) return ct; /* fatal */ } } for (n=0; n < ntiles; n++) { if (tile_has_diff[n]) { diffs++; } } return diffs; } static int island_try(int x, int y, int u, int v, int *run) { int n, m, ct; n = x + y * ntiles_x; m = u + v * ntiles_x; if (tile_has_diff[n]) { (*run)++; } else { *run = 0; } if (tile_has_diff[n] && ! tile_has_diff[m]) { /* found a discontinuity */ if (tile_tried[m]) { return 0; } else if (*run < grow_fill) { return 0; } ct = copy_tiles(u, v, 1); if (ct < 0) return ct; /* fatal */ } return 1; } /* * Scan looking for discontinuities in tile_has_diff[]. Try to extend * the boundary of the discontinuity (i.e. make the island larger). * Vertical scans are skipped since they do not seem to yield much... */ static int grow_islands(void) { int x, y, n, run; int diffs = 0, ct; /* * n.b. the way we scan here should keep an extension going, * and so also fill in gaps effectively... */ /* left to right: */ for (y=0; y < ntiles_y; y++) { run = 0; for (x=0; x <= ntiles_x - 2; x++) { ct = island_try(x, y, x+1, y, &run); if (ct < 0) return ct; /* fatal */ } } /* right to left: */ for (y=0; y < ntiles_y; y++) { run = 0; for (x = ntiles_x - 1; x >= 1; x--) { ct = island_try(x, y, x-1, y, &run); if (ct < 0) return ct; /* fatal */ } } for (n=0; n < ntiles; n++) { if (tile_has_diff[n]) { diffs++; } } return diffs; } /* * Fill the framebuffer with zeros for each blackout region */ static void blackout_regions(void) { int i; for (i=0; i < blackouts; i++) { zero_fb(blackr[i].x1, blackr[i].y1, blackr[i].x2, blackr[i].y2); } } /* * copy the whole X screen to the rfb framebuffer. For a large enough * number of changed tiles, this is faster than tiles scheme at retrieving * the info from the X server. Bandwidth to client and compression time * are other issues... use -fs 1.0 to disable. */ int copy_screen(void) { char *fbp; int i, y, block_size; if (! fs_factor) { return 0; } if (debug_tiles) fprintf(stderr, "copy_screen\n"); if (unixpw_in_progress) return 0; if (! main_fb) { return 0; } block_size = ((dpy_y/fs_factor) * main_bytes_per_line); fbp = main_fb; y = 0; X_LOCK; /* screen may be too big for 1 shm area, so broken into fs_factor */ for (i=0; i < fs_factor; i++) { XRANDR_SET_TRAP_RET(-1, "copy_screen-set"); copy_image(fullscreen, 0, y, 0, 0); XRANDR_CHK_TRAP_RET(-1, "copy_screen-chk"); memcpy(fbp, fullscreen->data, (size_t) block_size); y += dpy_y / fs_factor; fbp += block_size; } X_UNLOCK; if (blackouts) { blackout_regions(); } mark_rect_as_modified(0, 0, dpy_x, dpy_y, 0); return 0; } #include <default8x16.h> /* * Color values from the vcsadump program. * void dumpcss(FILE *fp, char *attribs_used) * char *colormap[] = { * "#000000", "#0000AA", "#00AA00", "#00AAAA", "#AA0000", "#AA00AA", "#AA5500", "#AAAAAA", * "#555555", "#5555AA", "#55FF55", "#55FFFF", "#FF5555", "#FF55FF", "#FFFF00", "#FFFFFF" }; */ static unsigned char console_cmap[16*3]={ /* 0 */ 0x00, 0x00, 0x00, /* 1 */ 0x00, 0x00, 0xAA, /* 2 */ 0x00, 0xAA, 0x00, /* 3 */ 0x00, 0xAA, 0xAA, /* 4 */ 0xAA, 0x00, 0x00, /* 5 */ 0xAA, 0x00, 0xAA, /* 6 */ 0xAA, 0x55, 0x00, /* 7 */ 0xAA, 0xAA, 0xAA, /* 8 */ 0x55, 0x55, 0x55, /* 9 */ 0x55, 0x55, 0xAA, /* 10 */ 0x55, 0xFF, 0x55, /* 11 */ 0x55, 0xFF, 0xFF, /* 12 */ 0xFF, 0x55, 0x55, /* 13 */ 0xFF, 0x55, 0xFF, /* 14 */ 0xFF, 0xFF, 0x00, /* 15 */ 0xFF, 0xFF, 0xFF }; static void snap_vcsa_rawfb(void) { int n; char *dst; char buf[32]; int i, len, del; unsigned char rows, cols, xpos, ypos; static int prev_rows = -1, prev_cols = -1; static unsigned char prev_xpos = -1, prev_ypos = -1; static char *vcsabuf = NULL; static char *vcsabuf0 = NULL; static unsigned int color_tab[16]; static int Cw = 8, Ch = 16; static int db = -1, first = 1; int created = 0; rfbScreenInfo s; rfbScreenInfoPtr fake_screen = &s; int Bpp = raw_fb_native_bpp / 8; if (db < 0) { if (getenv("X11VNC_DEBUG_VCSA")) { db = atoi(getenv("X11VNC_DEBUG_VCSA")); } else { db = 0; } } if (first) { unsigned int rm = raw_fb_native_red_mask; unsigned int gm = raw_fb_native_green_mask; unsigned int bm = raw_fb_native_blue_mask; unsigned int rs = raw_fb_native_red_shift; unsigned int gs = raw_fb_native_green_shift; unsigned int bs = raw_fb_native_blue_shift; unsigned int rx = raw_fb_native_red_max; unsigned int gx = raw_fb_native_green_max; unsigned int bx = raw_fb_native_blue_max; for (i=0; i < 16; i++) { int r = console_cmap[3*i+0]; int g = console_cmap[3*i+1]; int b = console_cmap[3*i+2]; r = rx * r / 255; g = gx * g / 255; b = bx * b / 255; color_tab[i] = (r << rs) | (g << gs) | (b << bs); if (db) fprintf(stderr, "cmap[%02d] 0x%08x %04d %04d %04d\n", i, color_tab[i], r, g, b); if (i != 0 && getenv("RAWFB_VCSA_BW")) { color_tab[i] = rm | gm | bm; } } } first = 0; lseek(raw_fb_fd, 0, SEEK_SET); len = 4; del = 0; memset(buf, 0, sizeof(buf)); while (len > 0) { n = read(raw_fb_fd, buf + del, len); if (n > 0) { del += n; len -= n; } else if (n == 0) { break; } else if (errno != EINTR && errno != EAGAIN) { break; } } rows = (unsigned char) buf[0]; cols = (unsigned char) buf[1]; xpos = (unsigned char) buf[2]; ypos = (unsigned char) buf[3]; if (db) fprintf(stderr, "rows=%d cols=%d xpos=%d ypos=%d Bpp=%d\n", rows, cols, xpos, ypos, Bpp); if (rows == 0 || cols == 0) { usleep(100 * 1000); return; } if (vcsabuf == NULL || prev_rows != rows || prev_cols != cols) { if (vcsabuf) { free(vcsabuf); free(vcsabuf0); } vcsabuf = (char *) calloc(2 * rows * cols, 1); vcsabuf0 = (char *) calloc(2 * rows * cols, 1); created = 1; if (prev_rows != -1 && prev_cols != -1) { do_new_fb(1); } prev_rows = rows; prev_cols = cols; } if (!rfbEndianTest) { unsigned char tc = rows; rows = cols; cols = tc; tc = xpos; xpos = ypos; ypos = tc; } len = 2 * rows * cols; del = 0; memset(vcsabuf, 0, len); while (len > 0) { n = read(raw_fb_fd, vcsabuf + del, len); if (n > 0) { del += n; len -= n; } else if (n == 0) { break; } else if (errno != EINTR && errno != EAGAIN) { break; } } fake_screen->frameBuffer = snap->data; fake_screen->paddedWidthInBytes = snap->bytes_per_line; fake_screen->serverFormat.bitsPerPixel = raw_fb_native_bpp; fake_screen->width = snap->width; fake_screen->height = snap->height; for (i=0; i < rows * cols; i++) { int ix, iy, x, y, w, h; unsigned char chr = 0; unsigned char attr; unsigned int fore, back; unsigned short *usp; unsigned int *uip; chr = (unsigned char) vcsabuf[2*i]; attr = vcsabuf[2*i+1]; iy = i / cols; ix = i - iy * cols; if (ix == prev_xpos && iy == prev_ypos) { ; } else if (ix == xpos && iy == ypos) { ; } else if (!created && chr == vcsabuf0[2*i] && attr == vcsabuf0[2*i+1]) { continue; } if (!rfbEndianTest) { unsigned char tc = chr; chr = attr; attr = tc; } y = iy * Ch; x = ix * Cw; dst = snap->data + y * snap->bytes_per_line + x * Bpp; fore = color_tab[attr & 0xf]; back = color_tab[(attr >> 4) & 0x7]; if (ix == xpos && iy == ypos) { unsigned int ti = fore; fore = back; back = ti; } for (h = 0; h < Ch; h++) { if (Bpp == 1) { memset(dst, back, Cw); } else if (Bpp == 2) { for (w = 0; w < Cw; w++) { usp = (unsigned short *) (dst + w*Bpp); *usp = (unsigned short) back; } } else if (Bpp == 4) { for (w = 0; w < Cw; w++) { uip = (unsigned int *) (dst + w*Bpp); *uip = (unsigned int) back; } } dst += snap->bytes_per_line; } rfbDrawChar(fake_screen, &default8x16Font, x, y + Ch, chr, fore); } memcpy(vcsabuf0, vcsabuf, 2 * rows * cols); prev_xpos = xpos; prev_ypos = ypos; } static void snap_all_rawfb(void) { int pixelsize = bpp/8; int n, sz; char *dst; static char *unclipped_dst = NULL; static int unclipped_len = 0; dst = snap->data; if (xform24to32 && bpp == 32) { pixelsize = 3; } sz = dpy_y * snap->bytes_per_line; if (wdpy_x > dpy_x || wdpy_y > dpy_y) { sz = wdpy_x * wdpy_y * pixelsize; if (sz > unclipped_len || unclipped_dst == NULL) { if (unclipped_dst) { free(unclipped_dst); } unclipped_dst = (char *) malloc(sz+4); unclipped_len = sz; } dst = unclipped_dst; } if (! raw_fb_seek) { memcpy(dst, raw_fb_addr + raw_fb_offset, sz); } else { int len = sz, del = 0; off_t off = (off_t) raw_fb_offset; lseek(raw_fb_fd, off, SEEK_SET); while (len > 0) { n = read(raw_fb_fd, dst + del, len); if (n > 0) { del += n; len -= n; } else if (n == 0) { break; } else if (errno != EINTR && errno != EAGAIN) { break; } } } if (dst == unclipped_dst) { char *src; int h; int x = off_x + coff_x; int y = off_y + coff_y; src = unclipped_dst + y * wdpy_x * pixelsize + x * pixelsize; dst = snap->data; for (h = 0; h < dpy_y; h++) { memcpy(dst, src, dpy_x * pixelsize); src += wdpy_x * pixelsize; dst += snap->bytes_per_line; } } } int copy_snap(void) { int db = 1; char *fbp; int i, y, block_size; double dt; static int first = 1, snapcnt = 0; if (raw_fb_str) { int read_all_at_once = 1; double start = dnow(); if (rawfb_reset < 0) { if (getenv("SNAPFB_RAWFB_RESET")) { rawfb_reset = 1; } else { rawfb_reset = 0; } } if (snap_fb == NULL || snap == NULL) { rfbLog("copy_snap: rawfb mode and null snap fb\n"); clean_up_exit(1); } if (rawfb_reset) { initialize_raw_fb(1); } if (raw_fb_bytes_per_line != snap->bytes_per_line) { read_all_at_once = 0; } if (raw_fb_full_str && strstr(raw_fb_full_str, "/dev/vcsa")) { snap_vcsa_rawfb(); } else if (read_all_at_once) { snap_all_rawfb(); } else { /* this goes line by line, XXX not working for video */ copy_raw_fb(snap, 0, 0, dpy_x, dpy_y); } if (db && snapcnt++ < 5) rfbLog("rawfb copy_snap took: %.5f secs\n", dnow() - start); return 0; } if (! fs_factor) { return 0; } if (! snap_fb || ! snap || ! snaprect) { return 0; } block_size = ((dpy_y/fs_factor) * snap->bytes_per_line); fbp = snap_fb; y = 0; dtime0(&dt); X_LOCK; /* screen may be too big for 1 shm area, so broken into fs_factor */ for (i=0; i < fs_factor; i++) { XRANDR_SET_TRAP_RET(-1, "copy_snap-set"); copy_image(snaprect, 0, y, 0, 0); XRANDR_CHK_TRAP_RET(-1, "copy_snap-chk"); memcpy(fbp, snaprect->data, (size_t) block_size); y += dpy_y / fs_factor; fbp += block_size; } X_UNLOCK; dt = dtime(&dt); if (first) { rfbLog("copy_snap: time for -snapfb snapshot: %.3f sec\n", dt); first = 0; } return 0; } /* STFU: Only for debugging */ #if 0 /* * debugging: print out a picture of the tiles. */ static void print_tiles(void) { /* hack for viewing tile diffs on the screen. */ static char *prev = NULL; int n, x, y, ms = 1500; ms = 1; if (! prev) { prev = (char *) malloc((size_t) ntiles); for (n=0; n < ntiles; n++) { prev[n] = 0; } } fprintf(stderr, " "); for (x=0; x < ntiles_x; x++) { fprintf(stderr, "%1d", x % 10); } fprintf(stderr, "\n"); n = 0; for (y=0; y < ntiles_y; y++) { fprintf(stderr, "%2d ", y); for (x=0; x < ntiles_x; x++) { if (tile_has_diff[n]) { fprintf(stderr, "X"); } else if (prev[n]) { fprintf(stderr, "o"); } else { fprintf(stderr, "."); } n++; } fprintf(stderr, "\n"); } for (n=0; n < ntiles; n++) { prev[n] = tile_has_diff[n]; } usleep(ms * 1000); } #endif /* * Utilities for managing the "naps" to cut down on amount of polling. */ static void nap_set(int tile_cnt) { int nap_in = nap_ok; time_t now = time(NULL); if (scan_count == 0) { /* roll up check for all NSCAN scans */ nap_ok = 0; if (naptile && nap_diff_count < 2 * NSCAN * naptile) { /* "2" is a fudge to permit a bit of bg drawing */ nap_ok = 1; } nap_diff_count = 0; } if (nap_ok && ! nap_in && use_xdamage) { if (XD_skip > 0.8 * XD_tot) { /* X DAMAGE is keeping load low, so skip nap */ nap_ok = 0; } } if (! nap_ok && client_count) { if(now > last_fb_bytes_sent + no_fbu_blank) { if (debug_tiles > 1) { fprintf(stderr, "nap_set: nap_ok=1: now: %d last: %d\n", (int) now, (int) last_fb_bytes_sent); } nap_ok = 1; } } if (show_cursor) { /* kludge for the up to 4 tiles the mouse patch could occupy */ if ( tile_cnt > 4) { last_event = now; } } else if (tile_cnt != 0) { last_event = now; } } /* * split up a long nap to improve the wakeup time */ void nap_sleep(int ms, int split) { int i, input = got_user_input; int gd = got_local_pointer_input; for (i=0; i<split; i++) { usleep(ms * 1000 / split); if (! use_threads && i != split - 1) { rfbPE(-1); } if (input != got_user_input) { break; } if (gd != got_local_pointer_input) { break; } } } static char *get_load(void) { static char tmp[64]; static int count = 0; if (count++ % 5 == 0) { struct stat sb; memset(tmp, 0, sizeof(tmp)); if (stat("/proc/loadavg", &sb) == 0) { int d = open("/proc/loadavg", O_RDONLY); if (d >= 0) { read(d, tmp, 60); close(d); } } if (tmp[0] == '\0') { strcat(tmp, "unknown"); } } return tmp; } /* * see if we should take a nap of some sort between polls */ static void nap_check(int tile_cnt) { time_t now; nap_diff_count += tile_cnt; if (! take_naps) { return; } now = time(NULL); if (screen_blank > 0) { int dt_ev, dt_fbu; static int ms = 0; if (ms == 0) { ms = 2000; if (getenv("X11VNC_SB_FACTOR")) { ms = ms * atof(getenv("X11VNC_SB_FACTOR")); } if (ms <= 0) { ms = 2000; } } /* if no activity, pause here for a second or so. */ dt_ev = (int) (now - last_event); dt_fbu = (int) (now - last_fb_bytes_sent); if (dt_fbu > screen_blank) { /* sleep longer for no fb requests */ if (debug_tiles > 1) { fprintf(stderr, "screen blank sleep1: %d ms / 16, load: %s\n", 2 * ms, get_load()); } nap_sleep(2 * ms, 16); return; } if (dt_ev > screen_blank) { if (debug_tiles > 1) { fprintf(stderr, "screen blank sleep2: %d ms / 8, load: %s\n", ms, get_load()); } nap_sleep(ms, 8); return; } } if (naptile && nap_ok && tile_cnt < naptile) { int ms = napfac * waitms; ms = ms > napmax ? napmax : ms; if (now - last_input <= 3) { nap_ok = 0; } else if (now - last_local_input <= 3) { nap_ok = 0; } else { if (debug_tiles > 1) { fprintf(stderr, "nap_check sleep: %d ms / 1, load: %s\n", ms, get_load()); } nap_sleep(ms, 1); } } } /* * This is called to avoid a ~20 second timeout in libvncserver. * May no longer be needed. */ static void ping_clients(int tile_cnt) { static time_t last_send = 0; time_t now = time(NULL); if (rfbMaxClientWait < 20000) { rfbMaxClientWait = 20000; rfbLog("reset rfbMaxClientWait to %d msec.\n", rfbMaxClientWait); } if (tile_cnt > 0) { last_send = now; } else if (tile_cnt < 0) { /* negative tile_cnt is -ping case */ if (now >= last_send - tile_cnt) { mark_rect_as_modified(0, 0, 1, 1, 1); last_send = now; } } else if (now - last_send > 5) { /* Send small heartbeat to client */ mark_rect_as_modified(0, 0, 1, 1, 1); last_send = now; } } /* * scan_display() wants to know if this tile can be skipped due to * blackout regions: (no data compare is done, just a quick geometric test) */ static int blackout_line_skip(int n, int x, int y, int rescan, int *tile_count) { if (tile_blackout[n].cover == 2) { tile_has_diff[n] = 0; return 1; /* skip it */ } else if (tile_blackout[n].cover == 1) { int w, x1, y1, x2, y2, b, hit = 0; if (x + NSCAN > dpy_x) { w = dpy_x - x; } else { w = NSCAN; } for (b=0; b < tile_blackout[n].count; b++) { /* n.b. these coords are in full display space: */ x1 = tile_blackout[n].bo[b].x1; x2 = tile_blackout[n].bo[b].x2; y1 = tile_blackout[n].bo[b].y1; y2 = tile_blackout[n].bo[b].y2; if (x2 - x1 < w) { /* need to cover full width */ continue; } if (y1 <= y && y < y2) { hit = 1; break; } } if (hit) { if (! rescan) { tile_has_diff[n] = 0; } else { *tile_count += tile_has_diff[n]; } return 1; /* skip */ } } return 0; /* do not skip */ } static int blackout_line_cmpskip(int n, int x, int y, char *dst, char *src, int w, int pixelsize) { int i, x1, y1, x2, y2, b, hit = 0; int beg = -1, end = -1; if (tile_blackout[n].cover == 0) { return 0; /* 0 means do not skip it. */ } else if (tile_blackout[n].cover == 2) { return 1; /* 1 means skip it. */ } /* tile has partial coverage: */ for (i=0; i < w * pixelsize; i++) { if (*(dst+i) != *(src+i)) { beg = i/pixelsize; /* beginning difference */ break; } } for (i = w * pixelsize - 1; i >= 0; i--) { if (*(dst+i) != *(src+i)) { end = i/pixelsize; /* ending difference */ break; } } if (beg < 0 || end < 0) { /* problem finding range... */ return 0; } /* loop over blackout rectangles: */ for (b=0; b < tile_blackout[n].count; b++) { /* y in full display space: */ y1 = tile_blackout[n].bo[b].y1; y2 = tile_blackout[n].bo[b].y2; /* x relative to tile origin: */ x1 = tile_blackout[n].bo[b].x1 - x; x2 = tile_blackout[n].bo[b].x2 - x; if (y1 > y || y >= y2) { continue; } if (x1 <= beg && end <= x2) { hit = 1; break; } } if (hit) { return 1; } else { return 0; } } /* * For the subwin case follows the window if it is moved. */ void set_offset(void) { Window w; if (! subwin) { return; } X_LOCK; xtranslate(window, rootwin, 0, 0, &off_x, &off_y, &w, 0); X_UNLOCK; } static int xd_samples = 0, xd_misses = 0, xd_do_check = 0; /* * Loop over 1-pixel tall horizontal scanlines looking for changes. * Record the changes in tile_has_diff[]. Scanlines in the loop are * equally spaced along y by NSCAN pixels, but have a slightly random * starting offset ystart ( < NSCAN ) from scanlines[]. */ static int scan_display(int ystart, int rescan) { char *src, *dst; int pixelsize = bpp/8; int x, y, w, n; int tile_count = 0; int nodiffs = 0, diff_hint; int xd_check = 0, xd_freq = 1; static int xd_tck = 0; y = ystart; g_now = dnow(); if (! main_fb) { rfbLog("scan_display: no main_fb!\n"); return 0; } X_LOCK; while (y < dpy_y) { if (use_xdamage) { XD_tot++; xd_check = 0; if (xdamage_hint_skip(y)) { if (xd_do_check && dpy && use_xdamage == 1) { xd_tck++; xd_tck = xd_tck % xd_freq; if (xd_tck == 0) { xd_check = 1; xd_samples++; } } if (!xd_check) { XD_skip++; y += NSCAN; continue; } } else { if (xd_do_check && 0) { fprintf(stderr, "ns y=%d\n", y); } } } /* grab the horizontal scanline from the display: */ #ifndef NO_NCACHE /* XXX Y test */ if (ncache > 0) { int gotone = 0; if (macosx_console) { if (macosx_checkevent(NULL)) { gotone = 1; } } else { #if !NO_X11 XEvent ev; if (raw_fb_str) { ; } else if (XEventsQueued(dpy, QueuedAlready) == 0) { ; /* XXX Y resp */ } else if (XCheckTypedEvent(dpy, MapNotify, &ev)) { gotone = 1; } else if (XCheckTypedEvent(dpy, UnmapNotify, &ev)) { gotone = 2; } else if (XCheckTypedEvent(dpy, CreateNotify, &ev)) { gotone = 3; } else if (XCheckTypedEvent(dpy, ConfigureNotify, &ev)) { gotone = 4; } else if (XCheckTypedEvent(dpy, VisibilityNotify, &ev)) { gotone = 5; } if (gotone) { XPutBackEvent(dpy, &ev); } #endif } if (gotone) { static int nomsg = 1; if (nomsg) { if (dnowx() > 20) { nomsg = 0; } } else { if (ncdb) fprintf(stderr, "\n*** SCAN_DISPLAY CHECK_NCACHE/%d *** %d rescan=%d\n", gotone, y, rescan); } X_UNLOCK; check_ncache(0, 1); X_LOCK; } } #endif XRANDR_SET_TRAP_RET(-1, "scan_display-set"); copy_image(scanline, 0, y, 0, 0); XRANDR_CHK_TRAP_RET(-1, "scan_display-chk"); /* for better memory i/o try the whole line at once */ src = scanline->data; dst = main_fb + y * main_bytes_per_line; if (! memcmp(dst, src, main_bytes_per_line)) { /* no changes anywhere in scan line */ nodiffs = 1; if (! rescan) { y += NSCAN; continue; } } if (xd_check) { xd_misses++; } x = 0; while (x < dpy_x) { n = (x/tile_x) + (y/tile_y) * ntiles_x; diff_hint = 0; if (blackouts) { if (blackout_line_skip(n, x, y, rescan, &tile_count)) { x += NSCAN; continue; } } if (rescan) { if (nodiffs || tile_has_diff[n]) { tile_count += tile_has_diff[n]; x += NSCAN; continue; } } else if (xdamage_tile_count && tile_has_xdamage_diff[n]) { tile_has_xdamage_diff[n] = 2; diff_hint = 1; } /* set ptrs to correspond to the x offset: */ src = scanline->data + x * pixelsize; dst = main_fb + y * main_bytes_per_line + x * pixelsize; /* compute the width of data to be compared: */ if (x + NSCAN > dpy_x) { w = dpy_x - x; } else { w = NSCAN; } if (diff_hint || memcmp(dst, src, w * pixelsize)) { /* found a difference, record it: */ if (! blackouts) { tile_has_diff[n] = 1; tile_count++; } else { if (blackout_line_cmpskip(n, x, y, dst, src, w, pixelsize)) { tile_has_diff[n] = 0; } else { tile_has_diff[n] = 1; tile_count++; } } } x += NSCAN; } y += NSCAN; } X_UNLOCK; return tile_count; } int scanlines[NSCAN] = { 0, 16, 8, 24, 4, 20, 12, 28, 10, 26, 18, 2, 22, 6, 30, 14, 1, 17, 9, 25, 7, 23, 15, 31, 19, 3, 27, 11, 29, 13, 5, 21 }; /* * toplevel for the scanning, rescanning, and applying the heuristics. * returns number of changed tiles. */ int scan_for_updates(int count_only) { int i, tile_count, tile_diffs; int old_copy_tile; double frac1 = 0.1; /* tweak parameter to try a 2nd scan_display() */ double frac2 = 0.35; /* or 3rd */ double frac3 = 0.02; /* do scan_display() again after copy_tiles() */ static double last_poll = 0.0; if (unixpw_in_progress) return 0; if (slow_fb > 0.0) { double now = dnow(); if (now < last_poll + slow_fb) { return 0; } last_poll = now; } for (i=0; i < ntiles; i++) { tile_has_diff[i] = 0; tile_has_xdamage_diff[i] = 0; tile_tried[i] = 0; tile_copied[i] = 0; } for (i=0; i < ntiles_y; i++) { /* could be useful, currently not used */ tile_row_has_xdamage_diff[i] = 0; } xdamage_tile_count = 0; /* * n.b. this program has only been tested so far with * tile_x = tile_y = NSCAN = 32! */ if (!count_only) { scan_count++; scan_count %= NSCAN; /* some periodic maintenance */ if (subwin && scan_count % 4 == 0) { set_offset(); /* follow the subwindow */ } if (indexed_color && scan_count % 4 == 0) { /* check for changed colormap */ set_colormap(0); } if (cmap8to24 && scan_count % 1 == 0) { check_for_multivis(); } #ifdef MACOSX if (macosx_console) { macosx_event_loop(); } #endif if (use_xdamage) { /* first pass collecting DAMAGE events: */ #ifdef MACOSX if (macosx_console) { collect_non_X_xdamage(-1, -1, -1, -1, 0); } else #endif { if (rawfb_vnc_reflect) { collect_non_X_xdamage(-1, -1, -1, -1, 0); } else { collect_xdamage(scan_count, 0); } } } } #define SCAN_FATAL(x) \ if (x < 0) { \ scan_in_progress = 0; \ fb_copy_in_progress = 0; \ return 0; \ } /* scan with the initial y to the jitter value from scanlines: */ scan_in_progress = 1; tile_count = scan_display(scanlines[scan_count], 0); SCAN_FATAL(tile_count); /* * we do the XDAMAGE here too since after scan_display() * there is a better chance we have received the events from * the X server (otherwise the DAMAGE events will be processed * in the *next* call, usually too late and wasteful since * the unchanged tiles are read in again). */ if (use_xdamage) { #ifdef MACOSX if (macosx_console) { ; } else #endif { if (rawfb_vnc_reflect) { ; } else { collect_xdamage(scan_count, 1); } } } if (count_only) { scan_in_progress = 0; fb_copy_in_progress = 0; return tile_count; } if (xdamage_tile_count) { /* pick up "known" damaged tiles we missed in scan_display() */ for (i=0; i < ntiles; i++) { if (tile_has_diff[i]) { continue; } if (tile_has_xdamage_diff[i]) { tile_has_diff[i] = 1; if (tile_has_xdamage_diff[i] == 1) { tile_has_xdamage_diff[i] = 2; tile_count++; } } } } if (dpy && use_xdamage == 1) { static time_t last_xd_check = 0; if (time(NULL) > last_xd_check + 2) { int cp = (scan_count + 3) % NSCAN; xd_do_check = 1; tile_count = scan_display(scanlines[cp], 0); xd_do_check = 0; SCAN_FATAL(tile_count); last_xd_check = time(NULL); if (xd_samples > 200) { static int bad = 0; if (xd_misses > (20 * xd_samples) / 100) { rfbLog("XDAMAGE is not working well... misses: %d/%d\n", xd_misses, xd_samples); rfbLog("Maybe an OpenGL app like Beryl or Compiz is the problem?\n"); rfbLog("Use x11vnc -noxdamage or disable the Beryl/Compiz app.\n"); rfbLog("To disable this check and warning specify -xdamage twice.\n"); if (++bad >= 10) { rfbLog("XDAMAGE appears broken (OpenGL app?), turning it off.\n"); use_xdamage = 0; initialize_xdamage(); destroy_xdamage_if_needed(); } } xd_samples = 0; xd_misses = 0; } } } nap_set(tile_count); if (fs_factor && frac1 >= fs_frac) { /* make frac1 < fs_frac if fullscreen updates are enabled */ frac1 = fs_frac/2.0; } if (tile_count > frac1 * ntiles) { /* * many tiles have changed, so try a rescan (since it should * be short compared to the many upcoming copy_tiles() calls) */ /* this check is done to skip the extra scan_display() call */ if (! fs_factor || tile_count <= fs_frac * ntiles) { int cp, tile_count_old = tile_count; /* choose a different y shift for the 2nd scan: */ cp = (NSCAN - scan_count) % NSCAN; tile_count = scan_display(scanlines[cp], 1); SCAN_FATAL(tile_count); if (tile_count >= (1 + frac2) * tile_count_old) { /* on a roll... do a 3rd scan */ cp = (NSCAN - scan_count + 7) % NSCAN; tile_count = scan_display(scanlines[cp], 1); SCAN_FATAL(tile_count); } } scan_in_progress = 0; /* * At some number of changed tiles it is better to just * copy the full screen at once. I.e. time = c1 + m * r1 * where m is number of tiles, r1 is the copy_tiles() * time, and c1 is the scan_display() time: for some m * it crosses the full screen update time. * * We try to predict that crossover with the fs_frac * fudge factor... seems to be about 1/2 the total number * of tiles. n.b. this ignores network bandwidth, * compression time etc... * * Use -fs 1.0 to disable on slow links. */ if (fs_factor && tile_count > fs_frac * ntiles) { int cs; fb_copy_in_progress = 1; cs = copy_screen(); fb_copy_in_progress = 0; SCAN_FATAL(cs); if (use_threads && pointer_mode != 1) { pointer_event(-1, 0, 0, NULL); } nap_check(tile_count); return tile_count; } } scan_in_progress = 0; /* copy all tiles with differences from display to rfb framebuffer: */ fb_copy_in_progress = 1; if (single_copytile || tile_shm_count < ntiles_x) { /* * Old way, copy I/O one tile at a time. */ old_copy_tile = 1; } else { /* * New way, does runs of horizontal tiles at once. * Note that below, for simplicity, the extra tile finding * (e.g. copy_tiles_backward_pass) is done the old way. */ old_copy_tile = 0; } if (unixpw_in_progress) return 0; if (old_copy_tile) { tile_diffs = copy_all_tiles(); } else { tile_diffs = copy_all_tile_runs(); } SCAN_FATAL(tile_diffs); /* * This backward pass for upward and left tiles complements what * was done in copy_all_tiles() for downward and right tiles. */ tile_diffs = copy_tiles_backward_pass(); SCAN_FATAL(tile_diffs); if (tile_diffs > frac3 * ntiles) { /* * we spent a lot of time in those copy_tiles, run * another scan, maybe more of the screen changed. */ int cp = (NSCAN - scan_count + 13) % NSCAN; scan_in_progress = 1; tile_count = scan_display(scanlines[cp], 1); SCAN_FATAL(tile_count); scan_in_progress = 0; tile_diffs = copy_tiles_additional_pass(); SCAN_FATAL(tile_diffs); } /* Given enough tile diffs, try the islands: */ if (grow_fill && tile_diffs > 4) { tile_diffs = grow_islands(); } SCAN_FATAL(tile_diffs); /* Given enough tile diffs, try the gaps: */ if (gaps_fill && tile_diffs > 4) { tile_diffs = fill_tile_gaps(); } SCAN_FATAL(tile_diffs); fb_copy_in_progress = 0; if (use_threads && pointer_mode != 1) { /* * tell the pointer handler it can process any queued * pointer events: */ pointer_event(-1, 0, 0, NULL); } if (blackouts) { /* ignore any diffs in completely covered tiles */ int x, y, n; for (y=0; y < ntiles_y; y++) { for (x=0; x < ntiles_x; x++) { n = x + y * ntiles_x; if (tile_blackout[n].cover == 2) { tile_has_diff[n] = 0; } } } } hint_updates(); /* use x0rfbserver hints algorithm */ /* Work around threaded rfbProcessClientMessage() calls timeouts */ if (use_threads) { ping_clients(tile_diffs); } else if (saw_ultra_chat || saw_ultra_file) { ping_clients(-1); } else if (use_openssl && !tile_diffs) { ping_clients(0); } /* -ping option: */ if (ping_interval) { int td = ping_interval > 0 ? ping_interval : -ping_interval; ping_clients(-td); } nap_check(tile_diffs); return tile_diffs; }
./CrossVul/dataset_final_sorted/CWE-862/c/good_4459_0
crossvul-cpp_data_bad_2978_0
/* Request a key from userspace * * Copyright (C) 2004-2007 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. * * See Documentation/security/keys/request-key.rst */ #include <linux/module.h> #include <linux/sched.h> #include <linux/kmod.h> #include <linux/err.h> #include <linux/keyctl.h> #include <linux/slab.h> #include "internal.h" #define key_negative_timeout 60 /* default timeout on a negative key's existence */ /** * complete_request_key - Complete the construction of a key. * @cons: The key construction record. * @error: The success or failute of the construction. * * Complete the attempt to construct a key. The key will be negated * if an error is indicated. The authorisation key will be revoked * unconditionally. */ void complete_request_key(struct key_construction *cons, int error) { kenter("{%d,%d},%d", cons->key->serial, cons->authkey->serial, error); if (error < 0) key_negate_and_link(cons->key, key_negative_timeout, NULL, cons->authkey); else key_revoke(cons->authkey); key_put(cons->key); key_put(cons->authkey); kfree(cons); } EXPORT_SYMBOL(complete_request_key); /* * Initialise a usermode helper that is going to have a specific session * keyring. * * This is called in context of freshly forked kthread before kernel_execve(), * so we can simply install the desired session_keyring at this point. */ static int umh_keys_init(struct subprocess_info *info, struct cred *cred) { struct key *keyring = info->data; return install_session_keyring_to_cred(cred, keyring); } /* * Clean up a usermode helper with session keyring. */ static void umh_keys_cleanup(struct subprocess_info *info) { struct key *keyring = info->data; key_put(keyring); } /* * Call a usermode helper with a specific session keyring. */ static int call_usermodehelper_keys(const char *path, char **argv, char **envp, struct key *session_keyring, int wait) { struct subprocess_info *info; info = call_usermodehelper_setup(path, argv, envp, GFP_KERNEL, umh_keys_init, umh_keys_cleanup, session_keyring); if (!info) return -ENOMEM; key_get(session_keyring); return call_usermodehelper_exec(info, wait); } /* * Request userspace finish the construction of a key * - execute "/sbin/request-key <op> <key> <uid> <gid> <keyring> <keyring> <keyring>" */ static int call_sbin_request_key(struct key_construction *cons, const char *op, void *aux) { static char const request_key[] = "/sbin/request-key"; const struct cred *cred = current_cred(); key_serial_t prkey, sskey; struct key *key = cons->key, *authkey = cons->authkey, *keyring, *session; char *argv[9], *envp[3], uid_str[12], gid_str[12]; char key_str[12], keyring_str[3][12]; char desc[20]; int ret, i; kenter("{%d},{%d},%s", key->serial, authkey->serial, op); ret = install_user_keyrings(); if (ret < 0) goto error_alloc; /* allocate a new session keyring */ sprintf(desc, "_req.%u", key->serial); cred = get_current_cred(); keyring = keyring_alloc(desc, cred->fsuid, cred->fsgid, cred, KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ, KEY_ALLOC_QUOTA_OVERRUN, NULL, NULL); put_cred(cred); if (IS_ERR(keyring)) { ret = PTR_ERR(keyring); goto error_alloc; } /* attach the auth key to the session keyring */ ret = key_link(keyring, authkey); if (ret < 0) goto error_link; /* record the UID and GID */ sprintf(uid_str, "%d", from_kuid(&init_user_ns, cred->fsuid)); sprintf(gid_str, "%d", from_kgid(&init_user_ns, cred->fsgid)); /* we say which key is under construction */ sprintf(key_str, "%d", key->serial); /* we specify the process's default keyrings */ sprintf(keyring_str[0], "%d", cred->thread_keyring ? cred->thread_keyring->serial : 0); prkey = 0; if (cred->process_keyring) prkey = cred->process_keyring->serial; sprintf(keyring_str[1], "%d", prkey); rcu_read_lock(); session = rcu_dereference(cred->session_keyring); if (!session) session = cred->user->session_keyring; sskey = session->serial; rcu_read_unlock(); sprintf(keyring_str[2], "%d", sskey); /* set up a minimal environment */ i = 0; envp[i++] = "HOME=/"; envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin"; envp[i] = NULL; /* set up the argument list */ i = 0; argv[i++] = (char *)request_key; argv[i++] = (char *) op; argv[i++] = key_str; argv[i++] = uid_str; argv[i++] = gid_str; argv[i++] = keyring_str[0]; argv[i++] = keyring_str[1]; argv[i++] = keyring_str[2]; argv[i] = NULL; /* do it */ ret = call_usermodehelper_keys(request_key, argv, envp, keyring, UMH_WAIT_PROC); kdebug("usermode -> 0x%x", ret); if (ret >= 0) { /* ret is the exit/wait code */ if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags) || key_validate(key) < 0) ret = -ENOKEY; else /* ignore any errors from userspace if the key was * instantiated */ ret = 0; } error_link: key_put(keyring); error_alloc: complete_request_key(cons, ret); kleave(" = %d", ret); return ret; } /* * Call out to userspace for key construction. * * Program failure is ignored in favour of key status. */ static int construct_key(struct key *key, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring) { struct key_construction *cons; request_key_actor_t actor; struct key *authkey; int ret; kenter("%d,%p,%zu,%p", key->serial, callout_info, callout_len, aux); cons = kmalloc(sizeof(*cons), GFP_KERNEL); if (!cons) return -ENOMEM; /* allocate an authorisation key */ authkey = request_key_auth_new(key, callout_info, callout_len, dest_keyring); if (IS_ERR(authkey)) { kfree(cons); ret = PTR_ERR(authkey); authkey = NULL; } else { cons->authkey = key_get(authkey); cons->key = key_get(key); /* make the call */ actor = call_sbin_request_key; if (key->type->request_key) actor = key->type->request_key; ret = actor(cons, "create", aux); /* check that the actor called complete_request_key() prior to * returning an error */ WARN_ON(ret < 0 && !test_bit(KEY_FLAG_REVOKED, &authkey->flags)); key_put(authkey); } kleave(" = %d", ret); return ret; } /* * Get the appropriate destination keyring for the request. * * The keyring selected is returned with an extra reference upon it which the * caller must release. */ static void construct_get_dest_keyring(struct key **_dest_keyring) { struct request_key_auth *rka; const struct cred *cred = current_cred(); struct key *dest_keyring = *_dest_keyring, *authkey; kenter("%p", dest_keyring); /* find the appropriate keyring */ if (dest_keyring) { /* the caller supplied one */ key_get(dest_keyring); } else { /* use a default keyring; falling through the cases until we * find one that we actually have */ switch (cred->jit_keyring) { case KEY_REQKEY_DEFL_DEFAULT: case KEY_REQKEY_DEFL_REQUESTOR_KEYRING: if (cred->request_key_auth) { authkey = cred->request_key_auth; down_read(&authkey->sem); rka = authkey->payload.data[0]; if (!test_bit(KEY_FLAG_REVOKED, &authkey->flags)) dest_keyring = key_get(rka->dest_keyring); up_read(&authkey->sem); if (dest_keyring) break; } case KEY_REQKEY_DEFL_THREAD_KEYRING: dest_keyring = key_get(cred->thread_keyring); if (dest_keyring) break; case KEY_REQKEY_DEFL_PROCESS_KEYRING: dest_keyring = key_get(cred->process_keyring); if (dest_keyring) break; case KEY_REQKEY_DEFL_SESSION_KEYRING: rcu_read_lock(); dest_keyring = key_get( rcu_dereference(cred->session_keyring)); rcu_read_unlock(); if (dest_keyring) break; case KEY_REQKEY_DEFL_USER_SESSION_KEYRING: dest_keyring = key_get(cred->user->session_keyring); break; case KEY_REQKEY_DEFL_USER_KEYRING: dest_keyring = key_get(cred->user->uid_keyring); break; case KEY_REQKEY_DEFL_GROUP_KEYRING: default: BUG(); } } *_dest_keyring = dest_keyring; kleave(" [dk %d]", key_serial(dest_keyring)); return; } /* * Allocate a new key in under-construction state and attempt to link it in to * the requested keyring. * * May return a key that's already under construction instead if there was a * race between two thread calling request_key(). */ static int construct_alloc_key(struct keyring_search_context *ctx, struct key *dest_keyring, unsigned long flags, struct key_user *user, struct key **_key) { struct assoc_array_edit *edit; struct key *key; key_perm_t perm; key_ref_t key_ref; int ret; kenter("%s,%s,,,", ctx->index_key.type->name, ctx->index_key.description); *_key = NULL; mutex_lock(&user->cons_lock); perm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR; perm |= KEY_USR_VIEW; if (ctx->index_key.type->read) perm |= KEY_POS_READ; if (ctx->index_key.type == &key_type_keyring || ctx->index_key.type->update) perm |= KEY_POS_WRITE; key = key_alloc(ctx->index_key.type, ctx->index_key.description, ctx->cred->fsuid, ctx->cred->fsgid, ctx->cred, perm, flags, NULL); if (IS_ERR(key)) goto alloc_failed; set_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags); if (dest_keyring) { ret = __key_link_begin(dest_keyring, &ctx->index_key, &edit); if (ret < 0) goto link_prealloc_failed; } /* attach the key to the destination keyring under lock, but we do need * to do another check just in case someone beat us to it whilst we * waited for locks */ mutex_lock(&key_construction_mutex); key_ref = search_process_keyrings(ctx); if (!IS_ERR(key_ref)) goto key_already_present; if (dest_keyring) __key_link(key, &edit); mutex_unlock(&key_construction_mutex); if (dest_keyring) __key_link_end(dest_keyring, &ctx->index_key, edit); mutex_unlock(&user->cons_lock); *_key = key; kleave(" = 0 [%d]", key_serial(key)); return 0; /* the key is now present - we tell the caller that we found it by * returning -EINPROGRESS */ key_already_present: key_put(key); mutex_unlock(&key_construction_mutex); key = key_ref_to_ptr(key_ref); if (dest_keyring) { ret = __key_link_check_live_key(dest_keyring, key); if (ret == 0) __key_link(key, &edit); __key_link_end(dest_keyring, &ctx->index_key, edit); if (ret < 0) goto link_check_failed; } mutex_unlock(&user->cons_lock); *_key = key; kleave(" = -EINPROGRESS [%d]", key_serial(key)); return -EINPROGRESS; link_check_failed: mutex_unlock(&user->cons_lock); key_put(key); kleave(" = %d [linkcheck]", ret); return ret; link_prealloc_failed: mutex_unlock(&user->cons_lock); key_put(key); kleave(" = %d [prelink]", ret); return ret; alloc_failed: mutex_unlock(&user->cons_lock); kleave(" = %ld", PTR_ERR(key)); return PTR_ERR(key); } /* * Commence key construction. */ static struct key *construct_key_and_link(struct keyring_search_context *ctx, const char *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct key_user *user; struct key *key; int ret; kenter(""); if (ctx->index_key.type == &key_type_keyring) return ERR_PTR(-EPERM); user = key_user_lookup(current_fsuid()); if (!user) return ERR_PTR(-ENOMEM); construct_get_dest_keyring(&dest_keyring); ret = construct_alloc_key(ctx, dest_keyring, flags, user, &key); key_user_put(user); if (ret == 0) { ret = construct_key(key, callout_info, callout_len, aux, dest_keyring); if (ret < 0) { kdebug("cons failed"); goto construction_failed; } } else if (ret == -EINPROGRESS) { ret = 0; } else { goto couldnt_alloc_key; } key_put(dest_keyring); kleave(" = key %d", key_serial(key)); return key; construction_failed: key_negate_and_link(key, key_negative_timeout, NULL, NULL); key_put(key); couldnt_alloc_key: key_put(dest_keyring); kleave(" = %d", ret); return ERR_PTR(ret); } /** * request_key_and_link - Request a key and cache it in a keyring. * @type: The type of key we want. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * @dest_keyring: Where to cache the key. * @flags: Flags to key_alloc(). * * A key matching the specified criteria is searched for in the process's * keyrings and returned with its usage count incremented if found. Otherwise, * if callout_info is not NULL, a key will be allocated and some service * (probably in userspace) will be asked to instantiate it. * * If successfully found or created, the key will be linked to the destination * keyring if one is provided. * * Returns a pointer to the key if successful; -EACCES, -ENOKEY, -EKEYREVOKED * or -EKEYEXPIRED if an inaccessible, negative, revoked or expired key was * found; -ENOKEY if no key was found and no @callout_info was given; -EDQUOT * if insufficient key quota was available to create a new key; or -ENOMEM if * insufficient memory was available. * * If the returned key was created, then it may still be under construction, * and wait_for_key_construction() should be used to wait for that to complete. */ struct key *request_key_and_link(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux, struct key *dest_keyring, unsigned long flags) { struct keyring_search_context ctx = { .index_key.type = type, .index_key.description = description, .cred = current_cred(), .match_data.cmp = key_default_cmp, .match_data.raw_data = description, .match_data.lookup_type = KEYRING_SEARCH_LOOKUP_DIRECT, .flags = (KEYRING_SEARCH_DO_STATE_CHECK | KEYRING_SEARCH_SKIP_EXPIRED), }; struct key *key; key_ref_t key_ref; int ret; kenter("%s,%s,%p,%zu,%p,%p,%lx", ctx.index_key.type->name, ctx.index_key.description, callout_info, callout_len, aux, dest_keyring, flags); if (type->match_preparse) { ret = type->match_preparse(&ctx.match_data); if (ret < 0) { key = ERR_PTR(ret); goto error; } } /* search all the process keyrings for a key */ key_ref = search_process_keyrings(&ctx); if (!IS_ERR(key_ref)) { key = key_ref_to_ptr(key_ref); if (dest_keyring) { ret = key_link(dest_keyring, key); if (ret < 0) { key_put(key); key = ERR_PTR(ret); goto error_free; } } } else if (PTR_ERR(key_ref) != -EAGAIN) { key = ERR_CAST(key_ref); } else { /* the search failed, but the keyrings were searchable, so we * should consult userspace if we can */ key = ERR_PTR(-ENOKEY); if (!callout_info) goto error_free; key = construct_key_and_link(&ctx, callout_info, callout_len, aux, dest_keyring, flags); } error_free: if (type->match_free) type->match_free(&ctx.match_data); error: kleave(" = %p", key); return key; } /** * wait_for_key_construction - Wait for construction of a key to complete * @key: The key being waited for. * @intr: Whether to wait interruptibly. * * Wait for a key to finish being constructed. * * Returns 0 if successful; -ERESTARTSYS if the wait was interrupted; -ENOKEY * if the key was negated; or -EKEYREVOKED or -EKEYEXPIRED if the key was * revoked or expired. */ int wait_for_key_construction(struct key *key, bool intr) { int ret; ret = wait_on_bit(&key->flags, KEY_FLAG_USER_CONSTRUCT, intr ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE); if (ret) return -ERESTARTSYS; ret = key_read_state(key); if (ret < 0) return ret; return key_validate(key); } EXPORT_SYMBOL(wait_for_key_construction); /** * request_key - Request a key and wait for construction * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found, new keys are always allocated in the user's quota, * the callout_info must be a NUL-terminated string and no auxiliary data can * be passed. * * Furthermore, it then works as wait_for_key_construction() to wait for the * completion of keys undergoing construction with a non-interruptible wait. */ struct key *request_key(struct key_type *type, const char *description, const char *callout_info) { struct key *key; size_t callout_len = 0; int ret; if (callout_info) callout_len = strlen(callout_info); key = request_key_and_link(type, description, callout_info, callout_len, NULL, NULL, KEY_ALLOC_IN_QUOTA); if (!IS_ERR(key)) { ret = wait_for_key_construction(key, false); if (ret < 0) { key_put(key); return ERR_PTR(ret); } } return key; } EXPORT_SYMBOL(request_key); /** * request_key_with_auxdata - Request a key with auxiliary data for the upcaller * @type: The type of key we want. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found and new keys are always allocated in the user's quota. * * Furthermore, it then works as wait_for_key_construction() to wait for the * completion of keys undergoing construction with a non-interruptible wait. */ struct key *request_key_with_auxdata(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux) { struct key *key; int ret; key = request_key_and_link(type, description, callout_info, callout_len, aux, NULL, KEY_ALLOC_IN_QUOTA); if (!IS_ERR(key)) { ret = wait_for_key_construction(key, false); if (ret < 0) { key_put(key); return ERR_PTR(ret); } } return key; } EXPORT_SYMBOL(request_key_with_auxdata); /* * request_key_async - Request a key (allow async construction) * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found, new keys are always allocated in the user's quota and * no auxiliary data can be passed. * * The caller should call wait_for_key_construction() to wait for the * completion of the returned key if it is still undergoing construction. */ struct key *request_key_async(struct key_type *type, const char *description, const void *callout_info, size_t callout_len) { return request_key_and_link(type, description, callout_info, callout_len, NULL, NULL, KEY_ALLOC_IN_QUOTA); } EXPORT_SYMBOL(request_key_async); /* * request a key with auxiliary data for the upcaller (allow async construction) * @type: Type of key. * @description: The searchable description of the key. * @callout_info: The data to pass to the instantiation upcall (or NULL). * @callout_len: The length of callout_info. * @aux: Auxiliary data for the upcall. * * As for request_key_and_link() except that it does not add the returned key * to a keyring if found and new keys are always allocated in the user's quota. * * The caller should call wait_for_key_construction() to wait for the * completion of the returned key if it is still undergoing construction. */ struct key *request_key_async_with_auxdata(struct key_type *type, const char *description, const void *callout_info, size_t callout_len, void *aux) { return request_key_and_link(type, description, callout_info, callout_len, aux, NULL, KEY_ALLOC_IN_QUOTA); } EXPORT_SYMBOL(request_key_async_with_auxdata);
./CrossVul/dataset_final_sorted/CWE-862/c/bad_2978_0
crossvul-cpp_data_bad_3155_0
/* * * Copyright © 2013 Serge Hallyn <serge.hallyn@ubuntu.com>. * Copyright © 2013 Canonical Ltd. * * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #define _GNU_SOURCE /* See feature_test_macros(7) */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <sys/types.h> #include <pwd.h> #include <grp.h> #include <unistd.h> #include <fcntl.h> #include <sys/file.h> #include <alloca.h> #include <string.h> #include <sched.h> #include <sys/mman.h> #include <sys/socket.h> #include <errno.h> #include <ctype.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <linux/netlink.h> #include <arpa/inet.h> #include <net/if.h> #include <net/if_arp.h> #include <netinet/in.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <linux/sockios.h> #include <sys/param.h> #include "config.h" #include "utils.h" #include "network.h" static void usage(char *me, bool fail) { fprintf(stderr, "Usage: %s lxcpath name pid type bridge nicname\n", me); fprintf(stderr, " nicname is the name to use inside the container\n"); exit(fail ? 1 : 0); } static char *lxcpath, *lxcname; static int open_and_lock(char *path) { int fd; struct flock lk; fd = open(path, O_RDWR|O_CREAT, S_IWUSR | S_IRUSR); if (fd < 0) { fprintf(stderr, "Failed to open %s: %s\n", path, strerror(errno)); return(fd); } lk.l_type = F_WRLCK; lk.l_whence = SEEK_SET; lk.l_start = 0; lk.l_len = 0; if (fcntl(fd, F_SETLKW, &lk) < 0) { fprintf(stderr, "Failed to lock %s: %s\n", path, strerror(errno)); close(fd); return -1; } return fd; } static char *get_username(void) { struct passwd *pwd = getpwuid(getuid()); if (pwd == NULL) { perror("getpwuid"); return NULL; } return pwd->pw_name; } static void free_groupnames(char **groupnames) { int i; if (!groupnames) return; for (i = 0; groupnames[i]; i++) free(groupnames[i]); free(groupnames); } static char **get_groupnames(void) { int ngroups; gid_t *group_ids; int ret, i; char **groupnames; struct group *gr; ngroups = getgroups(0, NULL); if (ngroups == -1) { fprintf(stderr, "Failed to get number of groups user belongs to: %s\n", strerror(errno)); return NULL; } if (ngroups == 0) return NULL; group_ids = (gid_t *)malloc(sizeof(gid_t)*ngroups); if (group_ids == NULL) { fprintf(stderr, "Out of memory while getting groups the user belongs to\n"); return NULL; } ret = getgroups(ngroups, group_ids); if (ret < 0) { free(group_ids); fprintf(stderr, "Failed to get process groups: %s\n", strerror(errno)); return NULL; } groupnames = (char **)malloc(sizeof(char *)*(ngroups+1)); if (groupnames == NULL) { free(group_ids); fprintf(stderr, "Out of memory while getting group names\n"); return NULL; } memset(groupnames, 0, sizeof(char *)*(ngroups+1)); for (i=0; i<ngroups; i++ ) { gr = getgrgid(group_ids[i]); if (gr == NULL) { fprintf(stderr, "Failed to get group name\n"); free(group_ids); free_groupnames(groupnames); return NULL; } groupnames[i] = strdup(gr->gr_name); if (groupnames[i] == NULL) { fprintf(stderr, "Failed to copy group name: %s", gr->gr_name); free(group_ids); free_groupnames(groupnames); return NULL; } } free(group_ids); return groupnames; } static bool name_is_in_groupnames(char *name, char **groupnames) { while (groupnames != NULL) { if (strcmp(name, *groupnames) == 0) return true; groupnames++; } return false; } struct alloted_s { char *name; int allowed; struct alloted_s *next; }; static struct alloted_s *append_alloted(struct alloted_s **head, char *name, int n) { struct alloted_s *cur, *al; if (head == NULL || name == NULL) { // sanity check. parameters should not be null fprintf(stderr, "NULL parameters to append_alloted not allowed\n"); return NULL; } al = (struct alloted_s *)malloc(sizeof(struct alloted_s)); if (al == NULL) { // unable to allocate memory to new struct fprintf(stderr, "Out of memory in append_alloted\n"); return NULL; } al->name = strdup(name); if (al->name == NULL) { free(al); return NULL; } al->allowed = n; al->next = NULL; if (*head == NULL) { *head = al; return al; } cur = *head; while (cur->next != NULL) cur = cur->next; cur->next = al; return al; } static void free_alloted(struct alloted_s **head) { struct alloted_s *cur; if (head == NULL) { return; } cur = *head; while (cur != NULL) { cur = cur->next; free((*head)->name); free(*head); *head = cur; } } /* The configuration file consists of lines of the form: * * user type bridge count * or * @group type bridge count * * Return the count entry for the calling user if there is one. Else * return -1. */ static int get_alloted(char *me, char *intype, char *link, struct alloted_s **alloted) { FILE *fin = fopen(LXC_USERNIC_CONF, "r"); char *line = NULL; char name[100], type[100], br[100]; size_t len = 0; int n, ret, count = 0; char **groups; if (!fin) { fprintf(stderr, "Failed to open %s: %s\n", LXC_USERNIC_CONF, strerror(errno)); return -1; } groups = get_groupnames(); while ((getline(&line, &len, fin)) != -1) { ret = sscanf(line, "%99[^ \t] %99[^ \t] %99[^ \t] %d", name, type, br, &n); if (ret != 4) continue; if (strlen(name) == 0) continue; if (strcmp(name, me) != 0) { if (name[0] != '@') continue; if (!name_is_in_groupnames(name+1, groups)) continue; } if (strcmp(type, intype) != 0) continue; if (strcmp(link, br) != 0) continue; /* found the user or group with the appropriate settings, therefore finish the search. * what to do if there are more than one applicable lines? not specified in the docs. * since getline is implemented with realloc, we don't need to free line until exiting func. * * if append_alloted returns NULL, e.g. due to a malloc error, we set count to 0 and break the loop, * allowing cleanup and then exiting from main() */ if (append_alloted(alloted, name, n) == NULL) { count = 0; break; } count += n; } free_groupnames(groups); fclose(fin); free(line); // now return the total number of nics that this user can create return count; } static char *get_eol(char *s, char *e) { while (s<e && *s && *s != '\n') s++; return s; } static char *get_eow(char *s, char *e) { while (s<e && *s && !isblank(*s) && *s != '\n') s++; return s; } static char *find_line(char *p, char *e, char *u, char *t, char *l) { char *p1, *p2, *ret; while (p<e && (p1 = get_eol(p, e)) < e) { ret = p; if (*p == '#') goto next; while (p<e && isblank(*p)) p++; p2 = get_eow(p, e); if (!p2 || p2-p != strlen(u) || strncmp(p, u, strlen(u)) != 0) goto next; p = p2+1; while (p<e && isblank(*p)) p++; p2 = get_eow(p, e); if (!p2 || p2-p != strlen(t) || strncmp(p, t, strlen(t)) != 0) goto next; p = p2+1; while (p<e && isblank(*p)) p++; p2 = get_eow(p, e); if (!p2 || p2-p != strlen(l) || strncmp(p, l, strlen(l)) != 0) goto next; return ret; next: p = p1 + 1; } return NULL; } static bool nic_exists(char *nic) { char path[MAXPATHLEN]; int ret; struct stat sb; if (strcmp(nic, "none") == 0) return true; ret = snprintf(path, MAXPATHLEN, "/sys/class/net/%s", nic); if (ret < 0 || ret >= MAXPATHLEN) // should never happen! return false; ret = stat(path, &sb); if (ret != 0) return false; return true; } static int instantiate_veth(char *n1, char **n2) { int err; err = snprintf(*n2, IFNAMSIZ, "%sp", n1); if (err < 0 || err >= IFNAMSIZ) { fprintf(stderr, "nic name too long\n"); return -1; } err = lxc_veth_create(n1, *n2); if (err) { fprintf(stderr, "failed to create %s-%s : %s\n", n1, *n2, strerror(-err)); return -1; } /* changing the high byte of the mac address to 0xfe, the bridge interface * will always keep the host's mac address and not take the mac address * of a container */ err = setup_private_host_hw_addr(n1); if (err) { fprintf(stderr, "failed to change mac address of host interface '%s' : %s\n", n1, strerror(-err)); } return netdev_set_flag(n1, IFF_UP); } static int get_mtu(char *name) { int idx = if_nametoindex(name); return netdev_get_mtu(idx); } static bool create_nic(char *nic, char *br, int pid, char **cnic) { char *veth1buf, *veth2buf; veth1buf = alloca(IFNAMSIZ); veth2buf = alloca(IFNAMSIZ); int ret, mtu; ret = snprintf(veth1buf, IFNAMSIZ, "%s", nic); if (ret < 0 || ret >= IFNAMSIZ) { fprintf(stderr, "host nic name too long\n"); return false; } /* create the nics */ if (instantiate_veth(veth1buf, &veth2buf) < 0) { fprintf(stderr, "Error creating veth tunnel\n"); return false; } if (strcmp(br, "none") != 0) { /* copy the bridge's mtu to both ends */ mtu = get_mtu(br); if (mtu != -1) { if (lxc_netdev_set_mtu(veth1buf, mtu) < 0 || lxc_netdev_set_mtu(veth2buf, mtu) < 0) { fprintf(stderr, "Failed setting mtu\n"); goto out_del; } } /* attach veth1 to bridge */ if (lxc_bridge_attach(lxcpath, lxcname, br, veth1buf) < 0) { fprintf(stderr, "Error attaching %s to %s\n", veth1buf, br); goto out_del; } } /* pass veth2 to target netns */ ret = lxc_netdev_move_by_name(veth2buf, pid, NULL); if (ret < 0) { fprintf(stderr, "Error moving %s to netns %d\n", veth2buf, pid); goto out_del; } *cnic = strdup(veth2buf); return true; out_del: lxc_netdev_delete_by_name(veth1buf); return false; } /* * Get a new nic. * *dest will container the name (vethXXXXXX) which is attached * on the host to the lxc bridge */ static bool get_new_nicname(char **dest, char *br, int pid, char **cnic) { char template[IFNAMSIZ]; snprintf(template, sizeof(template), "vethXXXXXX"); *dest = lxc_mkifname(template); if (!create_nic(*dest, br, pid, cnic)) { return false; } return true; } static bool get_nic_from_line(char *p, char **nic) { char user[100], type[100], br[100]; int ret; ret = sscanf(p, "%99[^ \t\n] %99[^ \t\n] %99[^ \t\n] %99[^ \t\n]", user, type, br, *nic); if (ret != 4) return false; return true; } struct entry_line { char *start; int len; bool keep; }; static bool cull_entries(int fd, char *me, char *t, char *br) { struct stat sb; char *buf, *p, *e, *nic; off_t len; struct entry_line *entry_lines = NULL; int i, n = 0; nic = alloca(100); if (fstat(fd, &sb) < 0) { fprintf(stderr, "Failed to fstat: %s\n", strerror(errno)); return false; } len = sb.st_size; if (len == 0) return true; buf = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if (buf == MAP_FAILED) { fprintf(stderr, "Failed to create mapping: %s\n", strerror(errno)); return false; } p = buf; e = buf + len; while ((p = find_line(p, e, me, t, br)) != NULL) { struct entry_line *newe = realloc(entry_lines, sizeof(*entry_lines)*(n+1)); if (!newe) { free(entry_lines); return false; } entry_lines = newe; entry_lines[n].start = p; entry_lines[n].len = get_eol(p, e) - entry_lines[n].start; entry_lines[n].keep = true; n++; if (!get_nic_from_line(p, &nic)) continue; if (nic && !nic_exists(nic)) entry_lines[n-1].keep = false; p += entry_lines[n-1].len + 1; if (p >= e) break; } p = buf; for (i=0; i<n; i++) { if (!entry_lines[i].keep) continue; memcpy(p, entry_lines[i].start, entry_lines[i].len); p += entry_lines[i].len; *p = '\n'; p++; } free(entry_lines); munmap(buf, sb.st_size); if (ftruncate(fd, p-buf)) fprintf(stderr, "Failed to set new file size\n"); return true; } static int count_entries(char *buf, off_t len, char *me, char *t, char *br) { char *e = &buf[len]; int count = 0; while ((buf = find_line(buf, e, me, t, br)) != NULL) { count++; buf = get_eol(buf, e)+1; if (buf >= e) break; } return count; } /* * The dbfile has lines of the format: * user type bridge nicname */ static bool get_nic_if_avail(int fd, struct alloted_s *names, int pid, char *intype, char *br, int allowed, char **nicname, char **cnic) { off_t len, slen; struct stat sb; char *buf = NULL, *newline; int ret, count = 0; char *owner; struct alloted_s *n; for (n=names; n!=NULL; n=n->next) cull_entries(fd, n->name, intype, br); if (allowed == 0) return false; owner = names->name; if (fstat(fd, &sb) < 0) { fprintf(stderr, "Failed to fstat: %s\n", strerror(errno)); return false; } len = sb.st_size; if (len != 0) { buf = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if (buf == MAP_FAILED) { fprintf(stderr, "Failed to create mapping\n"); return false; } owner = NULL; for (n=names; n!=NULL; n=n->next) { count = count_entries(buf, len, n->name, intype, br); if (count >= n->allowed) continue; owner = n->name; break; } } if (owner == NULL) return false; if (!get_new_nicname(nicname, br, pid, cnic)) return false; /* owner ' ' intype ' ' br ' ' *nicname + '\n' + '\0' */ slen = strlen(owner) + strlen(intype) + strlen(br) + strlen(*nicname) + 5; newline = alloca(slen); ret = snprintf(newline, slen, "%s %s %s %s\n", owner, intype, br, *nicname); if (ret < 0 || ret >= slen) { if (lxc_netdev_delete_by_name(*nicname) != 0) fprintf(stderr, "Error unlinking %s!\n", *nicname); return false; } if (len) munmap(buf, len); if (ftruncate(fd, len + slen)) fprintf(stderr, "Failed to set new file size\n"); buf = mmap(NULL, len + slen, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if (buf == MAP_FAILED) { fprintf(stderr, "Failed to create mapping after extending: %s\n", strerror(errno)); if (lxc_netdev_delete_by_name(*nicname) != 0) fprintf(stderr, "Error unlinking %s!\n", *nicname); return false; } strcpy(buf+len, newline); munmap(buf, len+slen); return true; } static bool create_db_dir(char *fnam) { char *p = alloca(strlen(fnam)+1); strcpy(p, fnam); fnam = p; p = p + 1; again: while (*p && *p != '/') p++; if (!*p) return true; *p = '\0'; if (mkdir(fnam, 0755) && errno != EEXIST) { fprintf(stderr, "failed to create %s\n", fnam); *p = '/'; return false; } *(p++) = '/'; goto again; } #define VETH_DEF_NAME "eth%d" static int rename_in_ns(int pid, char *oldname, char **newnamep) { int fd = -1, ofd = -1, ret, ifindex = -1; bool grab_newname = false; ofd = lxc_preserve_ns(getpid(), "net"); if (ofd < 0) { fprintf(stderr, "Failed opening network namespace path for '%d'.", getpid()); return -1; } fd = lxc_preserve_ns(pid, "net"); if (fd < 0) { fprintf(stderr, "Failed opening network namespace path for '%d'.", pid); return -1; } if (setns(fd, 0) < 0) { fprintf(stderr, "setns to container network namespace\n"); goto out_err; } close(fd); fd = -1; if (!*newnamep) { grab_newname = true; *newnamep = VETH_DEF_NAME; if (!(ifindex = if_nametoindex(oldname))) { fprintf(stderr, "failed to get netdev index\n"); goto out_err; } } if ((ret = lxc_netdev_rename_by_name(oldname, *newnamep)) < 0) { fprintf(stderr, "Error %d renaming netdev %s to %s in container\n", ret, oldname, *newnamep); goto out_err; } if (grab_newname) { char ifname[IFNAMSIZ], *namep = ifname; if (!if_indextoname(ifindex, namep)) { fprintf(stderr, "Failed to get new netdev name\n"); goto out_err; } *newnamep = strdup(namep); if (!*newnamep) goto out_err; } if (setns(ofd, 0) < 0) { fprintf(stderr, "Error returning to original netns\n"); close(ofd); return -1; } close(ofd); return 0; out_err: if (ofd >= 0) close(ofd); if (setns(ofd, 0) < 0) fprintf(stderr, "Error returning to original network namespace\n"); if (fd >= 0) close(fd); return -1; } /* * If the caller (real uid, not effective uid) may read the * /proc/[pid]/ns/net, then it is either the caller's netns or one * which it created. */ static bool may_access_netns(int pid) { int ret; char s[200]; uid_t ruid, suid, euid; bool may_access = false; ret = getresuid(&ruid, &euid, &suid); if (ret) { fprintf(stderr, "Failed to get my uids: %s\n", strerror(errno)); return false; } ret = setresuid(ruid, ruid, euid); if (ret) { fprintf(stderr, "Failed to set temp uids to (%d,%d,%d): %s\n", (int)ruid, (int)ruid, (int)euid, strerror(errno)); return false; } ret = snprintf(s, 200, "/proc/%d/ns/net", pid); if (ret < 0 || ret >= 200) // can't happen return false; ret = access(s, R_OK); if (ret) { fprintf(stderr, "Uid %d may not access %s: %s\n", (int)ruid, s, strerror(errno)); } may_access = ret == 0; ret = setresuid(ruid, euid, suid); if (ret) { fprintf(stderr, "Failed to restore uids to (%d,%d,%d): %s\n", (int)ruid, (int)euid, (int)suid, strerror(errno)); may_access = false; } return may_access; } int main(int argc, char *argv[]) { int n, fd; bool gotone = false; char *me; char *nicname = alloca(40); char *cnic = NULL; // created nic name in container is returned here. char *vethname = NULL; int pid; struct alloted_s *alloted = NULL; /* set a sane env, because we are setuid-root */ if (clearenv() < 0) { fprintf(stderr, "Failed to clear environment"); exit(1); } if (setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1) < 0) { fprintf(stderr, "Failed to set PATH, exiting\n"); exit(1); } if ((me = get_username()) == NULL) { fprintf(stderr, "Failed to get username\n"); exit(1); } if (argc < 6) usage(argv[0], true); if (argc >= 7) vethname = argv[6]; lxcpath = argv[1]; lxcname = argv[2]; errno = 0; pid = (int) strtol(argv[3], NULL, 10); if (errno) { fprintf(stderr, "Could not read pid: %s\n", argv[1]); exit(1); } if (!create_db_dir(LXC_USERNIC_DB)) { fprintf(stderr, "Failed to create directory for db file\n"); exit(1); } if ((fd = open_and_lock(LXC_USERNIC_DB)) < 0) { fprintf(stderr, "Failed to lock %s\n", LXC_USERNIC_DB); exit(1); } if (!may_access_netns(pid)) { fprintf(stderr, "User %s may not modify netns for pid %d\n", me, pid); exit(1); } n = get_alloted(me, argv[4], argv[5], &alloted); if (n > 0) gotone = get_nic_if_avail(fd, alloted, pid, argv[4], argv[5], n, &nicname, &cnic); close(fd); free_alloted(&alloted); if (!gotone) { fprintf(stderr, "Quota reached\n"); exit(1); } // Now rename the link if (rename_in_ns(pid, cnic, &vethname) < 0) { fprintf(stderr, "Failed to rename the link\n"); exit(1); } // write the name of the interface pair to the stdout - like eth0:veth9MT2L4 fprintf(stdout, "%s:%s\n", vethname, nicname); exit(0); }
./CrossVul/dataset_final_sorted/CWE-862/c/bad_3155_0
crossvul-cpp_data_bad_4459_0
/* Copyright (C) 2002-2010 Karl J. Runge <runge@karlrunge.com> All rights reserved. This file is part of x11vnc. x11vnc 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. x11vnc 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 x11vnc; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA or see <http://www.gnu.org/licenses/>. In addition, as a special exception, Karl J. Runge gives permission to link the code of its release of x11vnc with the OpenSSL project's "OpenSSL" library (or with modified versions of it that use the same license as the "OpenSSL" library), and distribute the linked executables. You must obey the GNU General Public License in all respects for all of the code used other than "OpenSSL". If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ /* -- scan.c -- */ #include "x11vnc.h" #include "xinerama.h" #include "xwrappers.h" #include "xdamage.h" #include "xrandr.h" #include "win_utils.h" #include "8to24.h" #include "screen.h" #include "pointer.h" #include "cleanup.h" #include "unixpw.h" #include "screen.h" #include "macosx.h" #include "userinput.h" /* * routines for scanning and reading the X11 display for changes, and * for doing all the tile work (shm, etc). */ void initialize_tiles(void); void free_tiles(void); void shm_delete(XShmSegmentInfo *shm); void shm_clean(XShmSegmentInfo *shm, XImage *xim); void initialize_polling_images(void); void scale_rect(double factor_x, double factor_y, int blend, int interpolate, int Bpp, char *src_fb, int src_bytes_per_line, char *dst_fb, int dst_bytes_per_line, int Nx, int Ny, int nx, int ny, int X1, int Y1, int X2, int Y2, int mark); void scale_and_mark_rect(int X1, int Y1, int X2, int Y2, int mark); void mark_rect_as_modified(int x1, int y1, int x2, int y2, int force); int copy_screen(void); int copy_snap(void); void nap_sleep(int ms, int split); void set_offset(void); int scan_for_updates(int count_only); void rotate_curs(char *dst_0, char *src_0, int Dx, int Dy, int Bpp); void rotate_coords(int x, int y, int *xo, int *yo, int dxi, int dyi); void rotate_coords_inverse(int x, int y, int *xo, int *yo, int dxi, int dyi); static void set_fs_factor(int max); static char *flip_ximage_byte_order(XImage *xim); static int shm_create(XShmSegmentInfo *shm, XImage **ximg_ptr, int w, int h, char *name); static void create_tile_hint(int x, int y, int tw, int th, hint_t *hint); static void extend_tile_hint(int x, int y, int tw, int th, hint_t *hint); static void save_hint(hint_t hint, int loc); static void hint_updates(void); static void mark_hint(hint_t hint); static int copy_tiles(int tx, int ty, int nt); static int copy_all_tiles(void); static int copy_all_tile_runs(void); static int copy_tiles_backward_pass(void); static int copy_tiles_additional_pass(void); static int gap_try(int x, int y, int *run, int *saw, int along_x); static int fill_tile_gaps(void); static int island_try(int x, int y, int u, int v, int *run); static int grow_islands(void); static void blackout_regions(void); static void nap_set(int tile_cnt); static void nap_check(int tile_cnt); static void ping_clients(int tile_cnt); static int blackout_line_skip(int n, int x, int y, int rescan, int *tile_count); static int blackout_line_cmpskip(int n, int x, int y, char *dst, char *src, int w, int pixelsize); static int scan_display(int ystart, int rescan); /* array to hold the hints: */ static hint_t *hint_list; /* nap state */ int nap_ok = 0; static int nap_diff_count = 0; static int scan_count = 0; /* indicates which scan pattern we are on */ static int scan_in_progress = 0; typedef struct tile_change_region { /* start and end lines, along y, of the changed area inside a tile. */ unsigned short first_line, last_line; short first_x, last_x; /* info about differences along edges. */ unsigned short left_diff, right_diff; unsigned short top_diff, bot_diff; } region_t; /* array to hold the tiles region_t-s. */ static region_t *tile_region; /* * setup tile numbers and allocate the tile and hint arrays: */ void initialize_tiles(void) { ntiles_x = (dpy_x - 1)/tile_x + 1; ntiles_y = (dpy_y - 1)/tile_y + 1; ntiles = ntiles_x * ntiles_y; tile_has_diff = (unsigned char *) calloc((size_t) (ntiles * sizeof(unsigned char)), 1); tile_has_xdamage_diff = (unsigned char *) calloc((size_t) (ntiles * sizeof(unsigned char)), 1); tile_row_has_xdamage_diff = (unsigned char *) calloc((size_t) (ntiles_y * sizeof(unsigned char)), 1); tile_tried = (unsigned char *) calloc((size_t) (ntiles * sizeof(unsigned char)), 1); tile_copied = (unsigned char *) calloc((size_t) (ntiles * sizeof(unsigned char)), 1); tile_blackout = (tile_blackout_t *) calloc((size_t) (ntiles * sizeof(tile_blackout_t)), 1); tile_region = (region_t *) calloc((size_t) (ntiles * sizeof(region_t)), 1); tile_row = (XImage **) calloc((size_t) ((ntiles_x + 1) * sizeof(XImage *)), 1); tile_row_shm = (XShmSegmentInfo *) calloc((size_t) ((ntiles_x + 1) * sizeof(XShmSegmentInfo)), 1); /* there will never be more hints than tiles: */ hint_list = (hint_t *) calloc((size_t) (ntiles * sizeof(hint_t)), 1); } void free_tiles(void) { if (tile_has_diff) { free(tile_has_diff); tile_has_diff = NULL; } if (tile_has_xdamage_diff) { free(tile_has_xdamage_diff); tile_has_xdamage_diff = NULL; } if (tile_row_has_xdamage_diff) { free(tile_row_has_xdamage_diff); tile_row_has_xdamage_diff = NULL; } if (tile_tried) { free(tile_tried); tile_tried = NULL; } if (tile_copied) { free(tile_copied); tile_copied = NULL; } if (tile_blackout) { free(tile_blackout); tile_blackout = NULL; } if (tile_region) { free(tile_region); tile_region = NULL; } if (tile_row) { free(tile_row); tile_row = NULL; } if (tile_row_shm) { free(tile_row_shm); tile_row_shm = NULL; } if (hint_list) { free(hint_list); hint_list = NULL; } } /* * silly function to factor dpy_y until fullscreen shm is not bigger than max. * should always work unless dpy_y is a large prime or something... under * failure fs_factor remains 0 and no fullscreen updates will be tried. */ static int fs_factor = 0; static void set_fs_factor(int max) { int f, fac = 1, n = dpy_y; fs_factor = 0; if ((bpp/8) * dpy_x * dpy_y <= max) { fs_factor = 1; return; } for (f=2; f <= 101; f++) { while (n % f == 0) { n = n / f; fac = fac * f; if ( (bpp/8) * dpy_x * (dpy_y/fac) <= max ) { fs_factor = fac; return; } } } } static char *flip_ximage_byte_order(XImage *xim) { char *order; if (xim->byte_order == LSBFirst) { order = "MSBFirst"; xim->byte_order = MSBFirst; xim->bitmap_bit_order = MSBFirst; } else { order = "LSBFirst"; xim->byte_order = LSBFirst; xim->bitmap_bit_order = LSBFirst; } return order; } /* * set up an XShm image, or if not using shm just create the XImage. */ static int shm_create(XShmSegmentInfo *shm, XImage **ximg_ptr, int w, int h, char *name) { XImage *xim; static int reported_flip = 0; int db = 0; shm->shmid = -1; shm->shmaddr = (char *) -1; *ximg_ptr = NULL; if (nofb) { return 1; } X_LOCK; if (! using_shm || xform24to32 || raw_fb) { /* we only need the XImage created */ xim = XCreateImage_wr(dpy, default_visual, depth, ZPixmap, 0, NULL, w, h, raw_fb ? 32 : BitmapPad(dpy), 0); X_UNLOCK; if (xim == NULL) { rfbErr("XCreateImage(%s) failed.\n", name); if (quiet) { fprintf(stderr, "XCreateImage(%s) failed.\n", name); } return 0; } if (db) fprintf(stderr, "shm_create simple %d %d\t%p %s\n", w, h, (void *)xim, name); xim->data = (char *) malloc(xim->bytes_per_line * xim->height); if (xim->data == NULL) { rfbErr("XCreateImage(%s) data malloc failed.\n", name); if (quiet) { fprintf(stderr, "XCreateImage(%s) data malloc" " failed.\n", name); } return 0; } if (flip_byte_order) { char *order = flip_ximage_byte_order(xim); if (! reported_flip && ! quiet) { rfbLog("Changing XImage byte order" " to %s\n", order); reported_flip = 1; } } *ximg_ptr = xim; return 1; } if (! dpy) { X_UNLOCK; return 0; } xim = XShmCreateImage_wr(dpy, default_visual, depth, ZPixmap, NULL, shm, w, h); if (xim == NULL) { rfbErr("XShmCreateImage(%s) failed.\n", name); if (quiet) { fprintf(stderr, "XShmCreateImage(%s) failed.\n", name); } X_UNLOCK; return 0; } *ximg_ptr = xim; #if HAVE_XSHM shm->shmid = shmget(IPC_PRIVATE, xim->bytes_per_line * xim->height, IPC_CREAT | 0777); if (shm->shmid == -1) { rfbErr("shmget(%s) failed.\n", name); rfbLogPerror("shmget"); XDestroyImage(xim); *ximg_ptr = NULL; X_UNLOCK; return 0; } shm->shmaddr = xim->data = (char *) shmat(shm->shmid, 0, 0); if (shm->shmaddr == (char *)-1) { rfbErr("shmat(%s) failed.\n", name); rfbLogPerror("shmat"); XDestroyImage(xim); *ximg_ptr = NULL; shmctl(shm->shmid, IPC_RMID, 0); shm->shmid = -1; X_UNLOCK; return 0; } shm->readOnly = False; if (! XShmAttach_wr(dpy, shm)) { rfbErr("XShmAttach(%s) failed.\n", name); XDestroyImage(xim); *ximg_ptr = NULL; shmdt(shm->shmaddr); shm->shmaddr = (char *) -1; shmctl(shm->shmid, IPC_RMID, 0); shm->shmid = -1; X_UNLOCK; return 0; } #endif X_UNLOCK; return 1; } void shm_delete(XShmSegmentInfo *shm) { #if HAVE_XSHM if (getenv("X11VNC_SHM_DEBUG")) fprintf(stderr, "shm_delete: %p\n", (void *) shm); if (shm != NULL && shm->shmaddr != (char *) -1) { shmdt(shm->shmaddr); } if (shm != NULL && shm->shmid != -1) { shmctl(shm->shmid, IPC_RMID, 0); } if (shm != NULL) { shm->shmaddr = (char *) -1; shm->shmid = -1; } #else if (!shm) {} #endif } void shm_clean(XShmSegmentInfo *shm, XImage *xim) { int db = 0; if (db) fprintf(stderr, "shm_clean: called: %p\n", (void *)xim); X_LOCK; #if HAVE_XSHM if (shm != NULL && shm->shmid != -1 && dpy) { if (db) fprintf(stderr, "shm_clean: XShmDetach_wr\n"); XShmDetach_wr(dpy, shm); } #endif if (xim != NULL) { if (! raw_fb_back_to_X) { /* raw_fb hack */ if (xim->bitmap_unit != -1) { if (db) fprintf(stderr, "shm_clean: XDestroyImage %p\n", (void *)xim); XDestroyImage(xim); } else { if (xim->data) { if (db) fprintf(stderr, "shm_clean: free xim->data %p %p\n", (void *)xim, (void *)(xim->data)); free(xim->data); xim->data = NULL; } } } xim = NULL; } X_UNLOCK; shm_delete(shm); } void initialize_polling_images(void) { int i, MB = 1024 * 1024; /* set all shm areas to "none" before trying to create any */ scanline_shm.shmid = -1; scanline_shm.shmaddr = (char *) -1; scanline = NULL; fullscreen_shm.shmid = -1; fullscreen_shm.shmaddr = (char *) -1; fullscreen = NULL; snaprect_shm.shmid = -1; snaprect_shm.shmaddr = (char *) -1; snaprect = NULL; for (i=1; i<=ntiles_x; i++) { tile_row_shm[i].shmid = -1; tile_row_shm[i].shmaddr = (char *) -1; tile_row[i] = NULL; } /* the scanline (e.g. 1280x1) shared memory area image: */ if (! shm_create(&scanline_shm, &scanline, dpy_x, 1, "scanline")) { clean_up_exit(1); } /* * the fullscreen (e.g. 1280x1024/fs_factor) shared memory area image: * (we cut down the size of the shm area to try avoid and shm segment * limits, e.g. the default 1MB on Solaris) */ if (UT.sysname && strstr(UT.sysname, "Linux")) { set_fs_factor(10 * MB); } else { set_fs_factor(1 * MB); } if (fs_frac >= 1.0) { fs_frac = 1.1; fs_factor = 0; } if (! fs_factor) { rfbLog("warning: fullscreen updates are disabled.\n"); } else { if (! shm_create(&fullscreen_shm, &fullscreen, dpy_x, dpy_y/fs_factor, "fullscreen")) { clean_up_exit(1); } } if (use_snapfb) { if (! fs_factor) { rfbLog("warning: disabling -snapfb mode.\n"); use_snapfb = 0; } else if (! shm_create(&snaprect_shm, &snaprect, dpy_x, dpy_y/fs_factor, "snaprect")) { clean_up_exit(1); } } /* * for copy_tiles we need a lot of shared memory areas, one for * each possible run length of changed tiles. 32 for 1024x768 * and 40 for 1280x1024, etc. */ tile_shm_count = 0; for (i=1; i<=ntiles_x; i++) { if (! shm_create(&tile_row_shm[i], &tile_row[i], tile_x * i, tile_y, "tile_row")) { if (i == 1) { clean_up_exit(1); } rfbLog("shm: Error creating shared memory tile-row for" " len=%d,\n", i); rfbLog("shm: reverting to -onetile mode. If this" " problem persists\n"); rfbLog("shm: try using the -onetile or -noshm options" " to limit\n"); rfbLog("shm: shared memory usage, or run ipcrm(1)" " to manually\n"); rfbLog("shm: delete unattached shm segments.\n"); single_copytile_count = i; single_copytile = 1; } tile_shm_count++; if (single_copytile && i >= 1) { /* only need 1x1 tiles */ break; } } if (verbose) { if (using_shm && ! xform24to32) { rfbLog("created %d tile_row shm polling images.\n", tile_shm_count); } else { rfbLog("created %d tile_row polling images.\n", tile_shm_count); } } } /* * A hint is a rectangular region built from 1 or more adjacent tiles * glued together. Ultimately, this information in a single hint is sent * to libvncserver rather than sending each tile separately. */ static void create_tile_hint(int x, int y, int tw, int th, hint_t *hint) { int w = dpy_x - x; int h = dpy_y - y; if (w > tw) { w = tw; } if (h > th) { h = th; } hint->x = x; hint->y = y; hint->w = w; hint->h = h; } static void extend_tile_hint(int x, int y, int tw, int th, hint_t *hint) { int w = dpy_x - x; int h = dpy_y - y; if (w > tw) { w = tw; } if (h > th) { h = th; } if (hint->x > x) { /* extend to the left */ hint->w += hint->x - x; hint->x = x; } if (hint->y > y) { /* extend upward */ hint->h += hint->y - y; hint->y = y; } if (hint->x + hint->w < x + w) { /* extend to the right */ hint->w = x + w - hint->x; } if (hint->y + hint->h < y + h) { /* extend downward */ hint->h = y + h - hint->y; } } static void save_hint(hint_t hint, int loc) { /* simply copy it to the global array for later use. */ hint_list[loc].x = hint.x; hint_list[loc].y = hint.y; hint_list[loc].w = hint.w; hint_list[loc].h = hint.h; } /* * Glue together horizontal "runs" of adjacent changed tiles into one big * rectangle change "hint" to be passed to the vnc machinery. */ static void hint_updates(void) { hint_t hint; int x, y, i, n, ty, th, tx, tw; int hint_count = 0, in_run = 0; hint.x = hint.y = hint.w = hint.h = 0; for (y=0; y < ntiles_y; y++) { for (x=0; x < ntiles_x; x++) { n = x + y * ntiles_x; if (tile_has_diff[n]) { ty = tile_region[n].first_line; th = tile_region[n].last_line - ty + 1; tx = tile_region[n].first_x; tw = tile_region[n].last_x - tx + 1; if (tx < 0) { tx = 0; tw = tile_x; } if (! in_run) { create_tile_hint( x * tile_x + tx, y * tile_y + ty, tw, th, &hint); in_run = 1; } else { extend_tile_hint( x * tile_x + tx, y * tile_y + ty, tw, th, &hint); } } else { if (in_run) { /* end of a row run of altered tiles: */ save_hint(hint, hint_count++); in_run = 0; } } } if (in_run) { /* save the last row run */ save_hint(hint, hint_count++); in_run = 0; } } for (i=0; i < hint_count; i++) { /* pass update info to vnc: */ mark_hint(hint_list[i]); } } /* * kludge, simple ceil+floor for non-negative doubles: */ #define CEIL(x) ( (double) ((int) (x)) == (x) ? \ (double) ((int) (x)) : (double) ((int) (x) + 1) ) #define FLOOR(x) ( (double) ((int) (x)) ) /* * Scaling: * * For shrinking, a destination (scaled) pixel will correspond to more * than one source (i.e. main fb) pixel. Think of an x-y plane made with * graph paper. Each unit square in the graph paper (i.e. collection of * points (x,y) such that N < x < N+1 and M < y < M+1, N and M integers) * corresponds to one pixel in the unscaled fb. There is a solid * color filling the inside of such a square. A scaled pixel has width * 1/scale_fac, e.g. for "-scale 3/4" the width of the scaled pixel * is 1.333. The area of this scaled pixel is 1.333 * 1.333 (so it * obviously overlaps more than one source pixel, each which have area 1). * * We take the weight an unscaled pixel (source) contributes to a * scaled pixel (destination) as simply proportional to the overlap area * between the two pixels. One can then think of the value of the scaled * pixel as an integral over the portion of the graph paper it covers. * The thing being integrated is the color value of the unscaled source. * That color value is constant over a graph paper square (source pixel), * and changes discontinuously from one unit square to the next. * Here is an example for -scale 3/4, the solid lines are the source pixels (graph paper unit squares), while the dotted lines denote the scaled pixels (destination pixels): 0 1 4/3 2 8/3 3 4=12/3 |---------|--.------|------.--|---------|. | | . | . | |. | A | . B | . | |. | | . | . | |. | | . | . | |. 1 |---------|--.------|------.--|---------|. 4/3|.........|.........|.........|.........|. | | . | . | |. | C | . D | . | |. | | . | . | |. 2 |---------|--.------|------.--|---------|. | | . | . | |. | | . | . | |. 8/3|.........|.........|.........|.........|. | | . | . | |. 3 |---------|--.------|------.--|---------|. So we see the first scaled pixel (0 < x < 4/3 and 0 < y < 4/3) mostly overlaps with unscaled source pixel "A". The integration (averaging) weights for this scaled pixel are: A 1 B 1/3 C 1/3 D 1/9 * * The Red, Green, and Blue color values must be averaged over separately * otherwise you can get a complete mess (except in solid regions), * because high order bits are averaged differently from the low order bits. * * So the algorithm is roughly: * * - Given as input a rectangle in the unscaled source fb with changes, * find the rectangle of pixels this affects in the scaled destination fb. * * - For each of the affected scaled (dest) pixels, determine all of the * unscaled (source) pixels it overlaps with. * * - Average those unscaled source values together, weighted by the area * overlap with the destination pixel. Average R, G, B separately. * * - Take this average value and convert to a valid pixel value if * necessary (e.g. rounding, shifting), and then insert it into the * destination framebuffer as the pixel value. * * - On to the next destination pixel... * * ======================================================================== * * For expanding, e.g. -scale 1.1 (which we don't think people will do * very often... or at least so we hope, the framebuffer can become huge) * the situation is reversed and the destination pixel is smaller than a * "graph paper" unit square (source pixel). Some destination pixels * will be completely within a single unscaled source pixel. * * What we do here is a simple 4 point interpolation scheme: * * Let P00 be the source pixel closest to the destination pixel but with * x and y values less than or equal to those of the destination pixel. * (for simplicity, think of the upper left corner of a pixel defining the * x,y location of the pixel, the center would work just as well). So it * is the source pixel immediately to the upper left of the destination * pixel. Let P10 be the source pixel one to the right of P00. Let P01 * be one down from P00. And let P11 be one down and one to the right * of P00. They form a 2x2 square we will interpolate inside of. * * Let V00, V10, V01, and V11 be the color values of those 4 source * pixels. Let dx be the displacement along x the destination pixel is * from P00. Note: 0 <= dx < 1 by definition of P00. Similarly let * dy be the displacement along y. The weighted average for the * interpolation is: * * V_ave = V00 * (1 - dx) * (1 - dy) * + V10 * dx * (1 - dy) * + V01 * (1 - dx) * dy * + V11 * dx * dy * * Note that the weights (1-dx)*(1-dy) + dx*(1-dy) + (1-dx)*dy + dx*dy * automatically add up to 1. It is also nice that all the weights are * positive (unsigned char stays unsigned char). The above formula can * be motivated by doing two 1D interpolations along x: * * VA = V00 * (1 - dx) + V10 * dx * VB = V01 * (1 - dx) + V11 * dx * * and then interpolating VA and VB along y: * * V_ave = VA * (1 - dy) + VB * dy * * VA * v |<-dx->| * -- V00 ------ V10 * dy | | * -- | o...|... "o" denotes the position of the desired * ^ | . | . destination pixel relative to the P00 * | . | . source pixel. * V10 ----.- V11 . * ........ * | * VB * * * Of course R, G, B averages are done separately as in the shrinking * case. This gives reasonable results, and the implementation for * shrinking can simply be used with different choices for weights for * the loop over the 4 pixels. */ void scale_rect(double factor_x, double factor_y, int blend, int interpolate, int Bpp, char *src_fb, int src_bytes_per_line, char *dst_fb, int dst_bytes_per_line, int Nx, int Ny, int nx, int ny, int X1, int Y1, int X2, int Y2, int mark) { /* * Notation: * "i" an x pixel index in the destination (scaled) framebuffer * "j" a y pixel index in the destination (scaled) framebuffer * "I" an x pixel index in the source (un-scaled, i.e. main) framebuffer * "J" a y pixel index in the source (un-scaled, i.e. main) framebuffer * * Similarly for nx, ny, Nx, Ny, etc. Lowercase: dest, Uppercase: source. */ int i, j, i1, i2, j1, j2; /* indices for scaled fb (dest) */ int I, J, I1, I2, J1, J2; /* indices for main fb (source) */ double w, wx, wy, wtot; /* pixel weights */ double x1, y1, x2, y2; /* x-y coords for destination pixels edges */ double dx, dy; /* size of destination pixel */ double ddx=0, ddy=0; /* for interpolation expansion */ char *src, *dest; /* pointers to the two framebuffers */ unsigned short us = 0; unsigned char uc = 0; unsigned int ui = 0; int use_noblend_shortcut = 1; int shrink; /* whether shrinking or expanding */ static int constant_weights = -1, mag_int = -1; static int last_Nx = -1, last_Ny = -1, cnt = 0; static double last_factor = -1.0; int b, k; double pixave[4]; /* for averaging pixel values */ if (factor_x <= 1.0 && factor_y <= 1.0) { shrink = 1; } else { shrink = 0; } /* * N.B. width and height (real numbers) of a scaled pixel. * both are > 1 (e.g. 1.333 for -scale 3/4) * they should also be equal but we don't assume it. * * This new way is probably the best we can do, take the inverse * of the scaling factor to double precision. */ dx = 1.0/factor_x; dy = 1.0/factor_y; /* * There is some speedup if the pixel weights are constant, so * let's special case these. * * If scale = 1/n and n divides Nx and Ny, the pixel weights * are constant (e.g. 1/2 => equal on 2x2 square). */ if (factor_x != last_factor || Nx != last_Nx || Ny != last_Ny) { constant_weights = -1; mag_int = -1; last_Nx = Nx; last_Ny = Ny; last_factor = factor_x; } if (constant_weights < 0 && factor_x != factor_y) { constant_weights = 0; mag_int = 0; } else if (constant_weights < 0) { int n = 0; constant_weights = 0; mag_int = 0; for (i = 2; i<=128; i++) { double test = ((double) 1)/ i; double diff, eps = 1.0e-7; diff = factor_x - test; if (-eps < diff && diff < eps) { n = i; break; } } if (! blend || ! shrink || interpolate) { ; } else if (n != 0) { if (Nx % n == 0 && Ny % n == 0) { static int didmsg = 0; if (mark && ! didmsg) { didmsg = 1; rfbLog("scale_and_mark_rect: using " "constant pixel weight speedup " "for 1/%d\n", n); } constant_weights = 1; } } n = 0; for (i = 2; i<=32; i++) { double test = (double) i; double diff, eps = 1.0e-7; diff = factor_x - test; if (-eps < diff && diff < eps) { n = i; break; } } if (! blend && factor_x > 1.0 && n) { mag_int = n; } } if (mark && factor_x > 1.0 && blend) { /* * kludge: correct for interpolating blurring leaking * up or left 1 destination pixel. */ if (X1 > 0) X1--; if (Y1 > 0) Y1--; } /* * find the extent of the change the input rectangle induces in * the scaled framebuffer. */ /* Left edges: find largest i such that i * dx <= X1 */ i1 = FLOOR(X1/dx); /* Right edges: find smallest i such that (i+1) * dx >= X2+1 */ i2 = CEIL( (X2+1)/dx ) - 1; /* To be safe, correct any overflows: */ i1 = nfix(i1, nx); i2 = nfix(i2, nx) + 1; /* add 1 to make a rectangle upper boundary */ /* Repeat above for y direction: */ j1 = FLOOR(Y1/dy); j2 = CEIL( (Y2+1)/dy ) - 1; j1 = nfix(j1, ny); j2 = nfix(j2, ny) + 1; /* * special case integer magnification with no blending. * vision impaired magnification usage is interested in this case. */ if (mark && ! blend && mag_int && Bpp != 3) { int jmin, jmax, imin, imax; /* outer loop over *source* pixels */ for (J=Y1; J < Y2; J++) { jmin = J * mag_int; jmax = jmin + mag_int; for (I=X1; I < X2; I++) { /* extract value */ src = src_fb + J*src_bytes_per_line + I*Bpp; if (Bpp == 4) { ui = *((unsigned int *)src); } else if (Bpp == 2) { us = *((unsigned short *)src); } else if (Bpp == 1) { uc = *((unsigned char *)src); } imin = I * mag_int; imax = imin + mag_int; /* inner loop over *dest* pixels */ for (j=jmin; j<jmax; j++) { dest = dst_fb + j*dst_bytes_per_line + imin*Bpp; for (i=imin; i<imax; i++) { if (Bpp == 4) { *((unsigned int *)dest) = ui; } else if (Bpp == 2) { *((unsigned short *)dest) = us; } else if (Bpp == 1) { *((unsigned char *)dest) = uc; } dest += Bpp; } } } } goto markit; } /* set these all to 1.0 to begin with */ wx = 1.0; wy = 1.0; w = 1.0; /* * Loop over destination pixels in scaled fb: */ for (j=j1; j<j2; j++) { y1 = j * dy; /* top edge */ if (y1 > Ny - 1) { /* can go over with dy = 1/scale_fac */ y1 = Ny - 1; } y2 = y1 + dy; /* bottom edge */ /* Find main fb indices covered by this dest pixel: */ J1 = (int) FLOOR(y1); J1 = nfix(J1, Ny); if (shrink && ! interpolate) { J2 = (int) CEIL(y2) - 1; J2 = nfix(J2, Ny); } else { J2 = J1 + 1; /* simple interpolation */ ddy = y1 - J1; } /* destination char* pointer: */ dest = dst_fb + j*dst_bytes_per_line + i1*Bpp; for (i=i1; i<i2; i++) { x1 = i * dx; /* left edge */ if (x1 > Nx - 1) { /* can go over with dx = 1/scale_fac */ x1 = Nx - 1; } x2 = x1 + dx; /* right edge */ cnt++; /* Find main fb indices covered by this dest pixel: */ I1 = (int) FLOOR(x1); if (I1 >= Nx) I1 = Nx - 1; if (! blend && use_noblend_shortcut) { /* * The noblend case involves no weights, * and 1 pixel, so just copy the value * directly. */ src = src_fb + J1*src_bytes_per_line + I1*Bpp; if (Bpp == 4) { *((unsigned int *)dest) = *((unsigned int *)src); } else if (Bpp == 2) { *((unsigned short *)dest) = *((unsigned short *)src); } else if (Bpp == 1) { *(dest) = *(src); } else if (Bpp == 3) { /* rare case */ for (k=0; k<=2; k++) { *(dest+k) = *(src+k); } } dest += Bpp; continue; } if (shrink && ! interpolate) { I2 = (int) CEIL(x2) - 1; if (I2 >= Nx) I2 = Nx - 1; } else { I2 = I1 + 1; /* simple interpolation */ ddx = x1 - I1; } /* Zero out accumulators for next pixel average: */ for (b=0; b<4; b++) { pixave[b] = 0.0; /* for RGB weighted sums */ } /* * wtot is for accumulating the total weight. * It should always sum to 1/(scale_fac * scale_fac). */ wtot = 0.0; /* * Loop over source pixels covered by this dest pixel. * * These "extra" loops over "J" and "I" make * the cache/cacheline performance unclear. * For example, will the data brought in from * src for j, i, and J=0 still be in the cache * after the J > 0 data have been accessed and * we are at j, i+1, J=0? The stride in J is * main_bytes_per_line, and so ~4 KB. * * Typical case when shrinking are 2x2 loop, so * just two lines to worry about. */ for (J=J1; J<=J2; J++) { /* see comments for I, x1, x2, etc. below */ if (constant_weights) { ; } else if (! blend) { if (J != J1) { continue; } wy = 1.0; /* interpolation scheme: */ } else if (! shrink || interpolate) { if (J >= Ny) { continue; } else if (J == J1) { wy = 1.0 - ddy; } else if (J != J1) { wy = ddy; } /* integration scheme: */ } else if (J < y1) { wy = J+1 - y1; } else if (J+1 > y2) { wy = y2 - J; } else { wy = 1.0; } src = src_fb + J*src_bytes_per_line + I1*Bpp; for (I=I1; I<=I2; I++) { /* Work out the weight: */ if (constant_weights) { ; } else if (! blend) { /* * Ugh, PseudoColor colormap is * bad news, to avoid random * colors just take the first * pixel. Or user may have * specified :nb to fraction. * The :fb will force blending * for this case. */ if (I != I1) { continue; } wx = 1.0; /* interpolation scheme: */ } else if (! shrink || interpolate) { if (I >= Nx) { continue; /* off edge */ } else if (I == I1) { wx = 1.0 - ddx; } else if (I != I1) { wx = ddx; } /* integration scheme: */ } else if (I < x1) { /* * source left edge (I) to the * left of dest left edge (x1): * fractional weight */ wx = I+1 - x1; } else if (I+1 > x2) { /* * source right edge (I+1) to the * right of dest right edge (x2): * fractional weight */ wx = x2 - I; } else { /* * source edges (I and I+1) completely * inside dest edges (x1 and x2): * full weight */ wx = 1.0; } w = wx * wy; wtot += w; /* * We average the unsigned char value * instead of char value: otherwise * the minimum (char 0) is right next * to the maximum (char -1)! This way * they are spread between 0 and 255. */ if (Bpp == 4) { /* unroll the loops, can give 20% */ pixave[0] += w * ((unsigned char) *(src )); pixave[1] += w * ((unsigned char) *(src+1)); pixave[2] += w * ((unsigned char) *(src+2)); pixave[3] += w * ((unsigned char) *(src+3)); } else if (Bpp == 2) { /* * 16bpp: trickier with green * split over two bytes, so we * use the masks: */ us = *((unsigned short *) src); pixave[0] += w*(us & main_red_mask); pixave[1] += w*(us & main_green_mask); pixave[2] += w*(us & main_blue_mask); } else if (Bpp == 1) { pixave[0] += w * ((unsigned char) *(src)); } else { for (b=0; b<Bpp; b++) { pixave[b] += w * ((unsigned char) *(src+b)); } } src += Bpp; } } if (wtot <= 0.0) { wtot = 1.0; } wtot = 1.0/wtot; /* normalization factor */ /* place weighted average pixel in the scaled fb: */ if (Bpp == 4) { *(dest ) = (char) (wtot * pixave[0]); *(dest+1) = (char) (wtot * pixave[1]); *(dest+2) = (char) (wtot * pixave[2]); *(dest+3) = (char) (wtot * pixave[3]); } else if (Bpp == 2) { /* 16bpp / 565 case: */ pixave[0] *= wtot; pixave[1] *= wtot; pixave[2] *= wtot; us = (main_red_mask & (int) pixave[0]) | (main_green_mask & (int) pixave[1]) | (main_blue_mask & (int) pixave[2]); *( (unsigned short *) dest ) = us; } else if (Bpp == 1) { *(dest) = (char) (wtot * pixave[0]); } else { for (b=0; b<Bpp; b++) { *(dest+b) = (char) (wtot * pixave[b]); } } dest += Bpp; } } markit: if (mark) { mark_rect_as_modified(i1, j1, i2, j2, 1); } } /* Framebuffers data flow: General case: -------- -------- -------- -------- ----- |8to24_fb| |main_fb | |snap_fb | | X | |rfbfb| <== | | <== | | <== | | <== | Server | ----- -------- -------- -------- -------- (to vnc) (optional) (usu = rfbfb) (optional) (read only) 8to24_fb mode will create side fbs: poll24_fb and poll8_fb for bookkeepping the different regions (merged into 8to24_fb). Normal case: -------- -------- |main_fb | | X | |= rfb_fb| <== | Server | -------- -------- Scaling case: -------- -------- ----- |main_fb | | X | |rfbfb| <== | | <== | Server | ----- -------- -------- Webcam/video case: -------- -------- -------- |main_fb | |snap_fb | | Video | | | <== | | <== | device | -------- -------- -------- If we ever do a -rr rotation/reflection tran, it probably should be done after any scaling (need a rr_fb for intermediate results) -rr option: transformation: none x -> x; y -> y; x x -> w - x - 1; y -> y; y x -> x; x -> h - y - 1; xy x -> w - x - 1; y -> h - y - 1; +90 x -> h - y - 1; y -> x; +90x x -> y; y -> x; +90y x -> h - y - 1; y -> w - x - 1; -90 x -> y; y -> w - x - 1; some aliases: xy: yx, +180, -180, 180 +90: 90 +90x: 90x +90y: 90y -90: +270, 270 */ void scale_and_mark_rect(int X1, int Y1, int X2, int Y2, int mark) { char *dst_fb, *src_fb = main_fb; int dst_bpl, Bpp = bpp/8, fac = 1; if (!screen || !rfb_fb || !main_fb) { return; } if (! screen->serverFormat.trueColour) { /* * PseudoColor colormap... blending leads to random colors. * User can override with ":fb" */ if (scaling_blend == 1) { /* :fb option sets it to 2 */ if (default_visual->class == StaticGray) { /* * StaticGray can be blended OK, otherwise * user can disable with :nb */ ; } else { scaling_blend = 0; } } } if (cmap8to24 && cmap8to24_fb) { src_fb = cmap8to24_fb; if (scaling) { if (depth <= 8) { fac = 4; } else if (depth <= 16) { fac = 2; } } } dst_fb = rfb_fb; dst_bpl = rfb_bytes_per_line; scale_rect(scale_fac_x, scale_fac_y, scaling_blend, scaling_interpolate, fac * Bpp, src_fb, fac * main_bytes_per_line, dst_fb, dst_bpl, dpy_x, dpy_y, scaled_x, scaled_y, X1, Y1, X2, Y2, mark); } void rotate_coords(int x, int y, int *xo, int *yo, int dxi, int dyi) { int xi = x, yi = y; int Dx, Dy; if (dxi >= 0) { Dx = dxi; Dy = dyi; } else if (scaling) { Dx = scaled_x; Dy = scaled_y; } else { Dx = dpy_x; Dy = dpy_y; } /* ncache?? */ if (rotating == ROTATE_NONE) { *xo = xi; *yo = yi; } else if (rotating == ROTATE_X) { *xo = Dx - xi - 1; *yo = yi; } else if (rotating == ROTATE_Y) { *xo = xi; *yo = Dy - yi - 1; } else if (rotating == ROTATE_XY) { *xo = Dx - xi - 1; *yo = Dy - yi - 1; } else if (rotating == ROTATE_90) { *xo = Dy - yi - 1; *yo = xi; } else if (rotating == ROTATE_90X) { *xo = yi; *yo = xi; } else if (rotating == ROTATE_90Y) { *xo = Dy - yi - 1; *yo = Dx - xi - 1; } else if (rotating == ROTATE_270) { *xo = yi; *yo = Dx - xi - 1; } } void rotate_coords_inverse(int x, int y, int *xo, int *yo, int dxi, int dyi) { int xi = x, yi = y; int Dx, Dy; if (dxi >= 0) { Dx = dxi; Dy = dyi; } else if (scaling) { Dx = scaled_x; Dy = scaled_y; } else { Dx = dpy_x; Dy = dpy_y; } if (! rotating_same) { int t = Dx; Dx = Dy; Dy = t; } if (rotating == ROTATE_NONE) { *xo = xi; *yo = yi; } else if (rotating == ROTATE_X) { *xo = Dx - xi - 1; *yo = yi; } else if (rotating == ROTATE_Y) { *xo = xi; *yo = Dy - yi - 1; } else if (rotating == ROTATE_XY) { *xo = Dx - xi - 1; *yo = Dy - yi - 1; } else if (rotating == ROTATE_90) { *xo = yi; *yo = Dx - xi - 1; } else if (rotating == ROTATE_90X) { *xo = yi; *yo = xi; } else if (rotating == ROTATE_90Y) { *xo = Dy - yi - 1; *yo = Dx - xi - 1; } else if (rotating == ROTATE_270) { *xo = Dy - yi - 1; *yo = xi; } } /* unroll the Bpp loop to be used in each case: */ #define ROT_COPY \ src = src_0 + fbl*y + Bpp*x; \ dst = dst_0 + rbl*yn + Bpp*xn; \ if (Bpp == 1) { \ *(dst) = *(src); \ } else if (Bpp == 2) { \ *(dst+0) = *(src+0); \ *(dst+1) = *(src+1); \ } else if (Bpp == 3) { \ *(dst+0) = *(src+0); \ *(dst+1) = *(src+1); \ *(dst+2) = *(src+2); \ } else if (Bpp == 4) { \ *(dst+0) = *(src+0); \ *(dst+1) = *(src+1); \ *(dst+2) = *(src+2); \ *(dst+3) = *(src+3); \ } void rotate_fb(int x1, int y1, int x2, int y2) { int x, y, xn, yn, r_x1, r_y1, r_x2, r_y2, Bpp = bpp/8; int fbl = rfb_bytes_per_line; int rbl = rot_bytes_per_line; int Dx, Dy; char *src, *dst; char *src_0 = rfb_fb; char *dst_0 = rot_fb; if (! rotating || ! rot_fb) { return; } if (scaling) { Dx = scaled_x; Dy = scaled_y; } else { Dx = dpy_x; Dy = dpy_y; } rotate_coords(x1, y1, &r_x1, &r_y1, -1, -1); rotate_coords(x2, y2, &r_x2, &r_y2, -1, -1); dst = rot_fb; if (rotating == ROTATE_X) { for (y = y1; y < y2; y++) { for (x = x1; x < x2; x++) { xn = Dx - x - 1; yn = y; ROT_COPY } } } else if (rotating == ROTATE_Y) { for (y = y1; y < y2; y++) { for (x = x1; x < x2; x++) { xn = x; yn = Dy - y - 1; ROT_COPY } } } else if (rotating == ROTATE_XY) { for (y = y1; y < y2; y++) { for (x = x1; x < x2; x++) { xn = Dx - x - 1; yn = Dy - y - 1; ROT_COPY } } } else if (rotating == ROTATE_90) { for (y = y1; y < y2; y++) { for (x = x1; x < x2; x++) { xn = Dy - y - 1; yn = x; ROT_COPY } } } else if (rotating == ROTATE_90X) { for (y = y1; y < y2; y++) { for (x = x1; x < x2; x++) { xn = y; yn = x; ROT_COPY } } } else if (rotating == ROTATE_90Y) { for (y = y1; y < y2; y++) { for (x = x1; x < x2; x++) { xn = Dy - y - 1; yn = Dx - x - 1; ROT_COPY } } } else if (rotating == ROTATE_270) { for (y = y1; y < y2; y++) { for (x = x1; x < x2; x++) { xn = y; yn = Dx - x - 1; ROT_COPY } } } } void rotate_curs(char *dst_0, char *src_0, int Dx, int Dy, int Bpp) { int x, y, xn, yn; char *src, *dst; int fbl, rbl; if (! rotating) { return; } fbl = Dx * Bpp; if (rotating_same) { rbl = Dx * Bpp; } else { rbl = Dy * Bpp; } if (rotating == ROTATE_X) { for (y = 0; y < Dy; y++) { for (x = 0; x < Dx; x++) { xn = Dx - x - 1; yn = y; ROT_COPY if (0) fprintf(stderr, "rcurs: %d %d %d %d\n", x, y, xn, yn); } } } else if (rotating == ROTATE_Y) { for (y = 0; y < Dy; y++) { for (x = 0; x < Dx; x++) { xn = x; yn = Dy - y - 1; ROT_COPY } } } else if (rotating == ROTATE_XY) { for (y = 0; y < Dy; y++) { for (x = 0; x < Dx; x++) { xn = Dx - x - 1; yn = Dy - y - 1; ROT_COPY } } } else if (rotating == ROTATE_90) { for (y = 0; y < Dy; y++) { for (x = 0; x < Dx; x++) { xn = Dy - y - 1; yn = x; ROT_COPY } } } else if (rotating == ROTATE_90X) { for (y = 0; y < Dy; y++) { for (x = 0; x < Dx; x++) { xn = y; yn = x; ROT_COPY } } } else if (rotating == ROTATE_90Y) { for (y = 0; y < Dy; y++) { for (x = 0; x < Dx; x++) { xn = Dy - y - 1; yn = Dx - x - 1; ROT_COPY } } } else if (rotating == ROTATE_270) { for (y = 0; y < Dy; y++) { for (x = 0; x < Dx; x++) { xn = y; yn = Dx - x - 1; ROT_COPY } } } } void mark_wrapper(int x1, int y1, int x2, int y2) { int t, r_x1 = x1, r_y1 = y1, r_x2 = x2, r_y2 = y2; if (rotating) { /* well we hope rot_fb will always be the last one... */ rotate_coords(x1, y1, &r_x1, &r_y1, -1, -1); rotate_coords(x2, y2, &r_x2, &r_y2, -1, -1); rotate_fb(x1, y1, x2, y2); if (r_x1 > r_x2) { t = r_x1; r_x1 = r_x2; r_x2 = t; } if (r_y1 > r_y2) { t = r_y1; r_y1 = r_y2; r_y2 = t; } /* painting errors */ r_x1--; r_x2++; r_y1--; r_y2++; } rfbMarkRectAsModified(screen, r_x1, r_y1, r_x2, r_y2); } void mark_rect_as_modified(int x1, int y1, int x2, int y2, int force) { if (damage_time != 0) { /* * This is not XDAMAGE, rather a hack for testing * where we allow the framebuffer to be corrupted for * damage_delay seconds. */ int debug = 0; if (time(NULL) > damage_time + damage_delay) { if (! quiet) { rfbLog("damaging turned off.\n"); } damage_time = 0; damage_delay = 0; } else { if (debug) { rfbLog("damaging viewer fb by not marking " "rect: %d,%d,%d,%d\n", x1, y1, x2, y2); } return; } } if (rfb_fb == main_fb || force) { mark_wrapper(x1, y1, x2, y2); return; } if (cmap8to24) { bpp8to24(x1, y1, x2, y2); } if (scaling) { scale_and_mark_rect(x1, y1, x2, y2, 1); } else { mark_wrapper(x1, y1, x2, y2); } } /* * Notifies libvncserver of a changed hint rectangle. */ static void mark_hint(hint_t hint) { int x = hint.x; int y = hint.y; int w = hint.w; int h = hint.h; mark_rect_as_modified(x, y, x + w, y + h, 0); } /* * copy_tiles() gives a slight improvement over copy_tile() since * adjacent runs of tiles are done all at once there is some savings * due to contiguous memory access. Not a great speedup, but in some * cases it can be up to 2X. Even more on a SunRay or ShadowFB where * no graphics hardware is involved in the read. Generally, graphics * devices are optimized for write, not read, so we are limited by the * read bandwidth, sometimes only 5 MB/sec on otherwise fast hardware. */ static int *first_line = NULL, *last_line = NULL; static unsigned short *left_diff = NULL, *right_diff = NULL; static int copy_tiles(int tx, int ty, int nt) { int x, y, line; int size_x, size_y, width1, width2; int off, len, n, dw, dx, t; int w1, w2, dx1, dx2; /* tmps for normal and short tiles */ int pixelsize = bpp/8; int first_min, last_max; int first_x = -1, last_x = -1; static int prev_ntiles_x = -1; char *src, *dst, *s_src, *s_dst, *m_src, *m_dst; char *h_src, *h_dst; if (unixpw_in_progress) return 0; if (ntiles_x != prev_ntiles_x && first_line != NULL) { free(first_line); first_line = NULL; free(last_line); last_line = NULL; free(left_diff); left_diff = NULL; free(right_diff); right_diff = NULL; } if (first_line == NULL) { /* allocate arrays first time in. */ int n = ntiles_x + 1; rfbLog("copy_tiles: allocating first_line at size %d\n", n); first_line = (int *) malloc((size_t) (n * sizeof(int))); last_line = (int *) malloc((size_t) (n * sizeof(int))); left_diff = (unsigned short *) malloc((size_t) (n * sizeof(unsigned short))); right_diff = (unsigned short *) malloc((size_t) (n * sizeof(unsigned short))); } prev_ntiles_x = ntiles_x; x = tx * tile_x; y = ty * tile_y; size_x = dpy_x - x; if ( size_x > tile_x * nt ) { size_x = tile_x * nt; width1 = tile_x; width2 = tile_x; } else { /* short tile */ width1 = tile_x; /* internal tile */ width2 = size_x - (nt - 1) * tile_x; /* right hand tile */ } size_y = dpy_y - y; if ( size_y > tile_y ) { size_y = tile_y; } n = tx + ty * ntiles_x; /* number of the first tile */ if (blackouts && tile_blackout[n].cover == 2) { /* * If there are blackouts and this tile is completely covered * no need to poll screen or do anything else.. * n.b. we are in single copy_tile mode: nt=1 */ tile_has_diff[n] = 0; return(0); } X_LOCK; XRANDR_SET_TRAP_RET(-1, "copy_tile-set"); /* read in the whole tile run at once: */ copy_image(tile_row[nt], x, y, size_x, size_y); XRANDR_CHK_TRAP_RET(-1, "copy_tile-chk"); X_UNLOCK; if (blackouts && tile_blackout[n].cover == 1) { /* * If there are blackouts and this tile is partially covered * we should re-black-out the portion. * n.b. we are in single copy_tile mode: nt=1 */ int x1, x2, y1, y2, b; int w, s, fill = 0; for (b=0; b < tile_blackout[n].count; b++) { char *b_dst = tile_row[nt]->data; x1 = tile_blackout[n].bo[b].x1 - x; y1 = tile_blackout[n].bo[b].y1 - y; x2 = tile_blackout[n].bo[b].x2 - x; y2 = tile_blackout[n].bo[b].y2 - y; w = (x2 - x1) * pixelsize; s = x1 * pixelsize; for (line = 0; line < size_y; line++) { if (y1 <= line && line < y2) { memset(b_dst + s, fill, (size_t) w); } b_dst += tile_row[nt]->bytes_per_line; } } } src = tile_row[nt]->data; dst = main_fb + y * main_bytes_per_line + x * pixelsize; s_src = src; s_dst = dst; for (t=1; t <= nt; t++) { first_line[t] = -1; } /* find the first line with difference: */ w1 = width1 * pixelsize; w2 = width2 * pixelsize; /* foreach line: */ for (line = 0; line < size_y; line++) { /* foreach horizontal tile: */ for (t=1; t <= nt; t++) { if (first_line[t] != -1) { continue; } off = (t-1) * w1; if (t == nt) { len = w2; /* possible short tile */ } else { len = w1; } if (memcmp(s_dst + off, s_src + off, len)) { first_line[t] = line; } } s_src += tile_row[nt]->bytes_per_line; s_dst += main_bytes_per_line; } /* see if there were any differences for any tile: */ first_min = -1; for (t=1; t <= nt; t++) { tile_tried[n+(t-1)] = 1; if (first_line[t] != -1) { if (first_min == -1 || first_line[t] < first_min) { first_min = first_line[t]; } } } if (first_min == -1) { /* no tile has a difference, note this and get out: */ for (t=1; t <= nt; t++) { tile_has_diff[n+(t-1)] = 0; } return(0); } else { /* * at least one tile has a difference. make sure info * is recorded (e.g. sometimes we guess tiles and they * came in with tile_has_diff 0) */ for (t=1; t <= nt; t++) { if (first_line[t] == -1) { tile_has_diff[n+(t-1)] = 0; } else { tile_has_diff[n+(t-1)] = 1; } } } m_src = src + (tile_row[nt]->bytes_per_line * size_y); m_dst = dst + (main_bytes_per_line * size_y); for (t=1; t <= nt; t++) { last_line[t] = first_line[t]; } /* find the last line with difference: */ w1 = width1 * pixelsize; w2 = width2 * pixelsize; /* foreach line: */ for (line = size_y - 1; line > first_min; line--) { m_src -= tile_row[nt]->bytes_per_line; m_dst -= main_bytes_per_line; /* foreach tile: */ for (t=1; t <= nt; t++) { if (first_line[t] == -1 || last_line[t] != first_line[t]) { /* tile has no changes or already done */ continue; } off = (t-1) * w1; if (t == nt) { len = w2; /* possible short tile */ } else { len = w1; } if (memcmp(m_dst + off, m_src + off, len)) { last_line[t] = line; } } } /* * determine the farthest down last changed line * will be used below to limit our memcpy() to the framebuffer. */ last_max = -1; for (t=1; t <= nt; t++) { if (first_line[t] == -1) { continue; } if (last_max == -1 || last_line[t] > last_max) { last_max = last_line[t]; } } /* look for differences on left and right hand edges: */ for (t=1; t <= nt; t++) { left_diff[t] = 0; right_diff[t] = 0; } h_src = src; h_dst = dst; w1 = width1 * pixelsize; w2 = width2 * pixelsize; dx1 = (width1 - tile_fuzz) * pixelsize; dx2 = (width2 - tile_fuzz) * pixelsize; dw = tile_fuzz * pixelsize; /* foreach line: */ for (line = 0; line < size_y; line++) { /* foreach tile: */ for (t=1; t <= nt; t++) { if (first_line[t] == -1) { /* tile has no changes at all */ continue; } off = (t-1) * w1; if (t == nt) { dx = dx2; /* possible short tile */ if (dx <= 0) { break; } } else { dx = dx1; } if (! left_diff[t] && memcmp(h_dst + off, h_src + off, dw)) { left_diff[t] = 1; } if (! right_diff[t] && memcmp(h_dst + off + dx, h_src + off + dx, dw) ) { right_diff[t] = 1; } } h_src += tile_row[nt]->bytes_per_line; h_dst += main_bytes_per_line; } /* now finally copy the difference to the rfb framebuffer: */ s_src = src + tile_row[nt]->bytes_per_line * first_min; s_dst = dst + main_bytes_per_line * first_min; for (line = first_min; line <= last_max; line++) { /* for I/O speed we do not do this tile by tile */ memcpy(s_dst, s_src, size_x * pixelsize); if (nt == 1) { /* * optimization for tall skinny lines, e.g. wm * frame. try to find first_x and last_x to limit * the size of the hint. could help for a slow * link. Unfortunately we spent a lot of time * reading in the many tiles. * * BTW, we like to think the above memcpy leaves * the data we use below in the cache... (but * it could be two 128 byte segments at 32bpp) * so this inner loop is not as bad as it seems. */ int k, kx; kx = pixelsize; for (k=0; k<size_x; k++) { if (memcmp(s_dst + k*kx, s_src + k*kx, kx)) { if (first_x == -1 || k < first_x) { first_x = k; } if (last_x == -1 || k > last_x) { last_x = k; } } } } s_src += tile_row[nt]->bytes_per_line; s_dst += main_bytes_per_line; } /* record all the info in the region array for this tile: */ for (t=1; t <= nt; t++) { int s = t - 1; if (first_line[t] == -1) { /* tile unchanged */ continue; } tile_region[n+s].first_line = first_line[t]; tile_region[n+s].last_line = last_line[t]; tile_region[n+s].first_x = first_x; tile_region[n+s].last_x = last_x; tile_region[n+s].top_diff = 0; tile_region[n+s].bot_diff = 0; if ( first_line[t] < tile_fuzz ) { tile_region[n+s].top_diff = 1; } if ( last_line[t] > (size_y - 1) - tile_fuzz ) { tile_region[n+s].bot_diff = 1; } tile_region[n+s].left_diff = left_diff[t]; tile_region[n+s].right_diff = right_diff[t]; tile_copied[n+s] = 1; } return(1); } /* * The copy_tile() call in the loop below copies the changed tile into * the rfb framebuffer. Note that copy_tile() sets the tile_region * struct to have info about the y-range of the changed region and also * whether the tile edges contain diffs (within distance tile_fuzz). * * We use this tile_region info to try to guess if the downward and right * tiles will have diffs. These tiles will be checked later in the loop * (since y+1 > y and x+1 > x). * * See copy_tiles_backward_pass() for analogous checking upward and * left tiles. */ static int copy_all_tiles(void) { int x, y, n, m; int diffs = 0, ct; if (unixpw_in_progress) return 0; for (y=0; y < ntiles_y; y++) { for (x=0; x < ntiles_x; x++) { n = x + y * ntiles_x; if (tile_has_diff[n]) { ct = copy_tiles(x, y, 1); if (ct < 0) return ct; /* fatal */ } if (! tile_has_diff[n]) { /* * n.b. copy_tiles() may have detected * no change and reset tile_has_diff to 0. */ continue; } diffs++; /* neighboring tile downward: */ if ( (y+1) < ntiles_y && tile_region[n].bot_diff) { m = x + (y+1) * ntiles_x; if (! tile_has_diff[m]) { tile_has_diff[m] = 2; } } /* neighboring tile to right: */ if ( (x+1) < ntiles_x && tile_region[n].right_diff) { m = (x+1) + y * ntiles_x; if (! tile_has_diff[m]) { tile_has_diff[m] = 2; } } } } return diffs; } /* * Routine analogous to copy_all_tiles() above, but for horizontal runs * of adjacent changed tiles. */ static int copy_all_tile_runs(void) { int x, y, n, m, i; int diffs = 0, ct; int in_run = 0, run = 0; int ntave = 0, ntcnt = 0; if (unixpw_in_progress) return 0; for (y=0; y < ntiles_y; y++) { for (x=0; x < ntiles_x + 1; x++) { n = x + y * ntiles_x; if (x != ntiles_x && tile_has_diff[n]) { in_run = 1; run++; } else { if (! in_run) { in_run = 0; run = 0; continue; } ct = copy_tiles(x - run, y, run); if (ct < 0) return ct; /* fatal */ ntcnt++; ntave += run; diffs += run; /* neighboring tile downward: */ for (i=1; i <= run; i++) { if ((y+1) < ntiles_y && tile_region[n-i].bot_diff) { m = (x-i) + (y+1) * ntiles_x; if (! tile_has_diff[m]) { tile_has_diff[m] = 2; } } } /* neighboring tile to right: */ if (((x-1)+1) < ntiles_x && tile_region[n-1].right_diff) { m = ((x-1)+1) + y * ntiles_x; if (! tile_has_diff[m]) { tile_has_diff[m] = 2; } /* note that this starts a new run */ in_run = 1; run = 1; } else { in_run = 0; run = 0; } } } /* * Could some activity go here, to emulate threaded * behavior by servicing some libvncserver tasks? */ } return diffs; } /* * Here starts a bunch of heuristics to guess/detect changed tiles. * They are: * copy_tiles_backward_pass, fill_tile_gaps/gap_try, grow_islands/island_try */ /* * Try to predict whether the upward and/or leftward tile has been modified. * copy_all_tiles() has already done downward and rightward tiles. */ static int copy_tiles_backward_pass(void) { int x, y, n, m; int diffs = 0, ct; if (unixpw_in_progress) return 0; for (y = ntiles_y - 1; y >= 0; y--) { for (x = ntiles_x - 1; x >= 0; x--) { n = x + y * ntiles_x; /* number of this tile */ if (! tile_has_diff[n]) { continue; } m = x + (y-1) * ntiles_x; /* neighboring tile upward */ if (y >= 1 && ! tile_has_diff[m] && tile_region[n].top_diff) { if (! tile_tried[m]) { tile_has_diff[m] = 2; ct = copy_tiles(x, y-1, 1); if (ct < 0) return ct; /* fatal */ } } m = (x-1) + y * ntiles_x; /* neighboring tile to left */ if (x >= 1 && ! tile_has_diff[m] && tile_region[n].left_diff) { if (! tile_tried[m]) { tile_has_diff[m] = 2; ct = copy_tiles(x-1, y, 1); if (ct < 0) return ct; /* fatal */ } } } } for (n=0; n < ntiles; n++) { if (tile_has_diff[n]) { diffs++; } } return diffs; } static int copy_tiles_additional_pass(void) { int x, y, n; int diffs = 0, ct; if (unixpw_in_progress) return 0; for (y=0; y < ntiles_y; y++) { for (x=0; x < ntiles_x; x++) { n = x + y * ntiles_x; /* number of this tile */ if (! tile_has_diff[n]) { continue; } if (tile_copied[n]) { continue; } ct = copy_tiles(x, y, 1); if (ct < 0) return ct; /* fatal */ } } for (n=0; n < ntiles; n++) { if (tile_has_diff[n]) { diffs++; } } return diffs; } static int gap_try(int x, int y, int *run, int *saw, int along_x) { int n, m, i, xt, yt, ct; n = x + y * ntiles_x; if (! tile_has_diff[n]) { if (*saw) { (*run)++; /* extend the gap run. */ } return 0; } if (! *saw || *run == 0 || *run > gaps_fill) { *run = 0; /* unacceptable run. */ *saw = 1; return 0; } for (i=1; i <= *run; i++) { /* iterate thru the run. */ if (along_x) { xt = x - i; yt = y; } else { xt = x; yt = y - i; } m = xt + yt * ntiles_x; if (tile_tried[m]) { /* do not repeat tiles */ continue; } ct = copy_tiles(xt, yt, 1); if (ct < 0) return ct; /* fatal */ } *run = 0; *saw = 1; return 1; } /* * Look for small gaps of unchanged tiles that may actually contain changes. * E.g. when paging up and down in a web broswer or terminal there can * be a distracting delayed filling in of such gaps. gaps_fill is the * tweak parameter that sets the width of the gaps that are checked. * * BTW, grow_islands() is actually pretty successful at doing this too... */ static int fill_tile_gaps(void) { int x, y, run, saw; int n, diffs = 0, ct; /* horizontal: */ for (y=0; y < ntiles_y; y++) { run = 0; saw = 0; for (x=0; x < ntiles_x; x++) { ct = gap_try(x, y, &run, &saw, 1); if (ct < 0) return ct; /* fatal */ } } /* vertical: */ for (x=0; x < ntiles_x; x++) { run = 0; saw = 0; for (y=0; y < ntiles_y; y++) { ct = gap_try(x, y, &run, &saw, 0); if (ct < 0) return ct; /* fatal */ } } for (n=0; n < ntiles; n++) { if (tile_has_diff[n]) { diffs++; } } return diffs; } static int island_try(int x, int y, int u, int v, int *run) { int n, m, ct; n = x + y * ntiles_x; m = u + v * ntiles_x; if (tile_has_diff[n]) { (*run)++; } else { *run = 0; } if (tile_has_diff[n] && ! tile_has_diff[m]) { /* found a discontinuity */ if (tile_tried[m]) { return 0; } else if (*run < grow_fill) { return 0; } ct = copy_tiles(u, v, 1); if (ct < 0) return ct; /* fatal */ } return 1; } /* * Scan looking for discontinuities in tile_has_diff[]. Try to extend * the boundary of the discontinuity (i.e. make the island larger). * Vertical scans are skipped since they do not seem to yield much... */ static int grow_islands(void) { int x, y, n, run; int diffs = 0, ct; /* * n.b. the way we scan here should keep an extension going, * and so also fill in gaps effectively... */ /* left to right: */ for (y=0; y < ntiles_y; y++) { run = 0; for (x=0; x <= ntiles_x - 2; x++) { ct = island_try(x, y, x+1, y, &run); if (ct < 0) return ct; /* fatal */ } } /* right to left: */ for (y=0; y < ntiles_y; y++) { run = 0; for (x = ntiles_x - 1; x >= 1; x--) { ct = island_try(x, y, x-1, y, &run); if (ct < 0) return ct; /* fatal */ } } for (n=0; n < ntiles; n++) { if (tile_has_diff[n]) { diffs++; } } return diffs; } /* * Fill the framebuffer with zeros for each blackout region */ static void blackout_regions(void) { int i; for (i=0; i < blackouts; i++) { zero_fb(blackr[i].x1, blackr[i].y1, blackr[i].x2, blackr[i].y2); } } /* * copy the whole X screen to the rfb framebuffer. For a large enough * number of changed tiles, this is faster than tiles scheme at retrieving * the info from the X server. Bandwidth to client and compression time * are other issues... use -fs 1.0 to disable. */ int copy_screen(void) { char *fbp; int i, y, block_size; if (! fs_factor) { return 0; } if (debug_tiles) fprintf(stderr, "copy_screen\n"); if (unixpw_in_progress) return 0; if (! main_fb) { return 0; } block_size = ((dpy_y/fs_factor) * main_bytes_per_line); fbp = main_fb; y = 0; X_LOCK; /* screen may be too big for 1 shm area, so broken into fs_factor */ for (i=0; i < fs_factor; i++) { XRANDR_SET_TRAP_RET(-1, "copy_screen-set"); copy_image(fullscreen, 0, y, 0, 0); XRANDR_CHK_TRAP_RET(-1, "copy_screen-chk"); memcpy(fbp, fullscreen->data, (size_t) block_size); y += dpy_y / fs_factor; fbp += block_size; } X_UNLOCK; if (blackouts) { blackout_regions(); } mark_rect_as_modified(0, 0, dpy_x, dpy_y, 0); return 0; } #include <default8x16.h> /* * Color values from the vcsadump program. * void dumpcss(FILE *fp, char *attribs_used) * char *colormap[] = { * "#000000", "#0000AA", "#00AA00", "#00AAAA", "#AA0000", "#AA00AA", "#AA5500", "#AAAAAA", * "#555555", "#5555AA", "#55FF55", "#55FFFF", "#FF5555", "#FF55FF", "#FFFF00", "#FFFFFF" }; */ static unsigned char console_cmap[16*3]={ /* 0 */ 0x00, 0x00, 0x00, /* 1 */ 0x00, 0x00, 0xAA, /* 2 */ 0x00, 0xAA, 0x00, /* 3 */ 0x00, 0xAA, 0xAA, /* 4 */ 0xAA, 0x00, 0x00, /* 5 */ 0xAA, 0x00, 0xAA, /* 6 */ 0xAA, 0x55, 0x00, /* 7 */ 0xAA, 0xAA, 0xAA, /* 8 */ 0x55, 0x55, 0x55, /* 9 */ 0x55, 0x55, 0xAA, /* 10 */ 0x55, 0xFF, 0x55, /* 11 */ 0x55, 0xFF, 0xFF, /* 12 */ 0xFF, 0x55, 0x55, /* 13 */ 0xFF, 0x55, 0xFF, /* 14 */ 0xFF, 0xFF, 0x00, /* 15 */ 0xFF, 0xFF, 0xFF }; static void snap_vcsa_rawfb(void) { int n; char *dst; char buf[32]; int i, len, del; unsigned char rows, cols, xpos, ypos; static int prev_rows = -1, prev_cols = -1; static unsigned char prev_xpos = -1, prev_ypos = -1; static char *vcsabuf = NULL; static char *vcsabuf0 = NULL; static unsigned int color_tab[16]; static int Cw = 8, Ch = 16; static int db = -1, first = 1; int created = 0; rfbScreenInfo s; rfbScreenInfoPtr fake_screen = &s; int Bpp = raw_fb_native_bpp / 8; if (db < 0) { if (getenv("X11VNC_DEBUG_VCSA")) { db = atoi(getenv("X11VNC_DEBUG_VCSA")); } else { db = 0; } } if (first) { unsigned int rm = raw_fb_native_red_mask; unsigned int gm = raw_fb_native_green_mask; unsigned int bm = raw_fb_native_blue_mask; unsigned int rs = raw_fb_native_red_shift; unsigned int gs = raw_fb_native_green_shift; unsigned int bs = raw_fb_native_blue_shift; unsigned int rx = raw_fb_native_red_max; unsigned int gx = raw_fb_native_green_max; unsigned int bx = raw_fb_native_blue_max; for (i=0; i < 16; i++) { int r = console_cmap[3*i+0]; int g = console_cmap[3*i+1]; int b = console_cmap[3*i+2]; r = rx * r / 255; g = gx * g / 255; b = bx * b / 255; color_tab[i] = (r << rs) | (g << gs) | (b << bs); if (db) fprintf(stderr, "cmap[%02d] 0x%08x %04d %04d %04d\n", i, color_tab[i], r, g, b); if (i != 0 && getenv("RAWFB_VCSA_BW")) { color_tab[i] = rm | gm | bm; } } } first = 0; lseek(raw_fb_fd, 0, SEEK_SET); len = 4; del = 0; memset(buf, 0, sizeof(buf)); while (len > 0) { n = read(raw_fb_fd, buf + del, len); if (n > 0) { del += n; len -= n; } else if (n == 0) { break; } else if (errno != EINTR && errno != EAGAIN) { break; } } rows = (unsigned char) buf[0]; cols = (unsigned char) buf[1]; xpos = (unsigned char) buf[2]; ypos = (unsigned char) buf[3]; if (db) fprintf(stderr, "rows=%d cols=%d xpos=%d ypos=%d Bpp=%d\n", rows, cols, xpos, ypos, Bpp); if (rows == 0 || cols == 0) { usleep(100 * 1000); return; } if (vcsabuf == NULL || prev_rows != rows || prev_cols != cols) { if (vcsabuf) { free(vcsabuf); free(vcsabuf0); } vcsabuf = (char *) calloc(2 * rows * cols, 1); vcsabuf0 = (char *) calloc(2 * rows * cols, 1); created = 1; if (prev_rows != -1 && prev_cols != -1) { do_new_fb(1); } prev_rows = rows; prev_cols = cols; } if (!rfbEndianTest) { unsigned char tc = rows; rows = cols; cols = tc; tc = xpos; xpos = ypos; ypos = tc; } len = 2 * rows * cols; del = 0; memset(vcsabuf, 0, len); while (len > 0) { n = read(raw_fb_fd, vcsabuf + del, len); if (n > 0) { del += n; len -= n; } else if (n == 0) { break; } else if (errno != EINTR && errno != EAGAIN) { break; } } fake_screen->frameBuffer = snap->data; fake_screen->paddedWidthInBytes = snap->bytes_per_line; fake_screen->serverFormat.bitsPerPixel = raw_fb_native_bpp; fake_screen->width = snap->width; fake_screen->height = snap->height; for (i=0; i < rows * cols; i++) { int ix, iy, x, y, w, h; unsigned char chr = 0; unsigned char attr; unsigned int fore, back; unsigned short *usp; unsigned int *uip; chr = (unsigned char) vcsabuf[2*i]; attr = vcsabuf[2*i+1]; iy = i / cols; ix = i - iy * cols; if (ix == prev_xpos && iy == prev_ypos) { ; } else if (ix == xpos && iy == ypos) { ; } else if (!created && chr == vcsabuf0[2*i] && attr == vcsabuf0[2*i+1]) { continue; } if (!rfbEndianTest) { unsigned char tc = chr; chr = attr; attr = tc; } y = iy * Ch; x = ix * Cw; dst = snap->data + y * snap->bytes_per_line + x * Bpp; fore = color_tab[attr & 0xf]; back = color_tab[(attr >> 4) & 0x7]; if (ix == xpos && iy == ypos) { unsigned int ti = fore; fore = back; back = ti; } for (h = 0; h < Ch; h++) { if (Bpp == 1) { memset(dst, back, Cw); } else if (Bpp == 2) { for (w = 0; w < Cw; w++) { usp = (unsigned short *) (dst + w*Bpp); *usp = (unsigned short) back; } } else if (Bpp == 4) { for (w = 0; w < Cw; w++) { uip = (unsigned int *) (dst + w*Bpp); *uip = (unsigned int) back; } } dst += snap->bytes_per_line; } rfbDrawChar(fake_screen, &default8x16Font, x, y + Ch, chr, fore); } memcpy(vcsabuf0, vcsabuf, 2 * rows * cols); prev_xpos = xpos; prev_ypos = ypos; } static void snap_all_rawfb(void) { int pixelsize = bpp/8; int n, sz; char *dst; static char *unclipped_dst = NULL; static int unclipped_len = 0; dst = snap->data; if (xform24to32 && bpp == 32) { pixelsize = 3; } sz = dpy_y * snap->bytes_per_line; if (wdpy_x > dpy_x || wdpy_y > dpy_y) { sz = wdpy_x * wdpy_y * pixelsize; if (sz > unclipped_len || unclipped_dst == NULL) { if (unclipped_dst) { free(unclipped_dst); } unclipped_dst = (char *) malloc(sz+4); unclipped_len = sz; } dst = unclipped_dst; } if (! raw_fb_seek) { memcpy(dst, raw_fb_addr + raw_fb_offset, sz); } else { int len = sz, del = 0; off_t off = (off_t) raw_fb_offset; lseek(raw_fb_fd, off, SEEK_SET); while (len > 0) { n = read(raw_fb_fd, dst + del, len); if (n > 0) { del += n; len -= n; } else if (n == 0) { break; } else if (errno != EINTR && errno != EAGAIN) { break; } } } if (dst == unclipped_dst) { char *src; int h; int x = off_x + coff_x; int y = off_y + coff_y; src = unclipped_dst + y * wdpy_x * pixelsize + x * pixelsize; dst = snap->data; for (h = 0; h < dpy_y; h++) { memcpy(dst, src, dpy_x * pixelsize); src += wdpy_x * pixelsize; dst += snap->bytes_per_line; } } } int copy_snap(void) { int db = 1; char *fbp; int i, y, block_size; double dt; static int first = 1, snapcnt = 0; if (raw_fb_str) { int read_all_at_once = 1; double start = dnow(); if (rawfb_reset < 0) { if (getenv("SNAPFB_RAWFB_RESET")) { rawfb_reset = 1; } else { rawfb_reset = 0; } } if (snap_fb == NULL || snap == NULL) { rfbLog("copy_snap: rawfb mode and null snap fb\n"); clean_up_exit(1); } if (rawfb_reset) { initialize_raw_fb(1); } if (raw_fb_bytes_per_line != snap->bytes_per_line) { read_all_at_once = 0; } if (raw_fb_full_str && strstr(raw_fb_full_str, "/dev/vcsa")) { snap_vcsa_rawfb(); } else if (read_all_at_once) { snap_all_rawfb(); } else { /* this goes line by line, XXX not working for video */ copy_raw_fb(snap, 0, 0, dpy_x, dpy_y); } if (db && snapcnt++ < 5) rfbLog("rawfb copy_snap took: %.5f secs\n", dnow() - start); return 0; } if (! fs_factor) { return 0; } if (! snap_fb || ! snap || ! snaprect) { return 0; } block_size = ((dpy_y/fs_factor) * snap->bytes_per_line); fbp = snap_fb; y = 0; dtime0(&dt); X_LOCK; /* screen may be too big for 1 shm area, so broken into fs_factor */ for (i=0; i < fs_factor; i++) { XRANDR_SET_TRAP_RET(-1, "copy_snap-set"); copy_image(snaprect, 0, y, 0, 0); XRANDR_CHK_TRAP_RET(-1, "copy_snap-chk"); memcpy(fbp, snaprect->data, (size_t) block_size); y += dpy_y / fs_factor; fbp += block_size; } X_UNLOCK; dt = dtime(&dt); if (first) { rfbLog("copy_snap: time for -snapfb snapshot: %.3f sec\n", dt); first = 0; } return 0; } /* STFU: Only for debugging */ #if 0 /* * debugging: print out a picture of the tiles. */ static void print_tiles(void) { /* hack for viewing tile diffs on the screen. */ static char *prev = NULL; int n, x, y, ms = 1500; ms = 1; if (! prev) { prev = (char *) malloc((size_t) ntiles); for (n=0; n < ntiles; n++) { prev[n] = 0; } } fprintf(stderr, " "); for (x=0; x < ntiles_x; x++) { fprintf(stderr, "%1d", x % 10); } fprintf(stderr, "\n"); n = 0; for (y=0; y < ntiles_y; y++) { fprintf(stderr, "%2d ", y); for (x=0; x < ntiles_x; x++) { if (tile_has_diff[n]) { fprintf(stderr, "X"); } else if (prev[n]) { fprintf(stderr, "o"); } else { fprintf(stderr, "."); } n++; } fprintf(stderr, "\n"); } for (n=0; n < ntiles; n++) { prev[n] = tile_has_diff[n]; } usleep(ms * 1000); } #endif /* * Utilities for managing the "naps" to cut down on amount of polling. */ static void nap_set(int tile_cnt) { int nap_in = nap_ok; time_t now = time(NULL); if (scan_count == 0) { /* roll up check for all NSCAN scans */ nap_ok = 0; if (naptile && nap_diff_count < 2 * NSCAN * naptile) { /* "2" is a fudge to permit a bit of bg drawing */ nap_ok = 1; } nap_diff_count = 0; } if (nap_ok && ! nap_in && use_xdamage) { if (XD_skip > 0.8 * XD_tot) { /* X DAMAGE is keeping load low, so skip nap */ nap_ok = 0; } } if (! nap_ok && client_count) { if(now > last_fb_bytes_sent + no_fbu_blank) { if (debug_tiles > 1) { fprintf(stderr, "nap_set: nap_ok=1: now: %d last: %d\n", (int) now, (int) last_fb_bytes_sent); } nap_ok = 1; } } if (show_cursor) { /* kludge for the up to 4 tiles the mouse patch could occupy */ if ( tile_cnt > 4) { last_event = now; } } else if (tile_cnt != 0) { last_event = now; } } /* * split up a long nap to improve the wakeup time */ void nap_sleep(int ms, int split) { int i, input = got_user_input; int gd = got_local_pointer_input; for (i=0; i<split; i++) { usleep(ms * 1000 / split); if (! use_threads && i != split - 1) { rfbPE(-1); } if (input != got_user_input) { break; } if (gd != got_local_pointer_input) { break; } } } static char *get_load(void) { static char tmp[64]; static int count = 0; if (count++ % 5 == 0) { struct stat sb; memset(tmp, 0, sizeof(tmp)); if (stat("/proc/loadavg", &sb) == 0) { int d = open("/proc/loadavg", O_RDONLY); if (d >= 0) { read(d, tmp, 60); close(d); } } if (tmp[0] == '\0') { strcat(tmp, "unknown"); } } return tmp; } /* * see if we should take a nap of some sort between polls */ static void nap_check(int tile_cnt) { time_t now; nap_diff_count += tile_cnt; if (! take_naps) { return; } now = time(NULL); if (screen_blank > 0) { int dt_ev, dt_fbu; static int ms = 0; if (ms == 0) { ms = 2000; if (getenv("X11VNC_SB_FACTOR")) { ms = ms * atof(getenv("X11VNC_SB_FACTOR")); } if (ms <= 0) { ms = 2000; } } /* if no activity, pause here for a second or so. */ dt_ev = (int) (now - last_event); dt_fbu = (int) (now - last_fb_bytes_sent); if (dt_fbu > screen_blank) { /* sleep longer for no fb requests */ if (debug_tiles > 1) { fprintf(stderr, "screen blank sleep1: %d ms / 16, load: %s\n", 2 * ms, get_load()); } nap_sleep(2 * ms, 16); return; } if (dt_ev > screen_blank) { if (debug_tiles > 1) { fprintf(stderr, "screen blank sleep2: %d ms / 8, load: %s\n", ms, get_load()); } nap_sleep(ms, 8); return; } } if (naptile && nap_ok && tile_cnt < naptile) { int ms = napfac * waitms; ms = ms > napmax ? napmax : ms; if (now - last_input <= 3) { nap_ok = 0; } else if (now - last_local_input <= 3) { nap_ok = 0; } else { if (debug_tiles > 1) { fprintf(stderr, "nap_check sleep: %d ms / 1, load: %s\n", ms, get_load()); } nap_sleep(ms, 1); } } } /* * This is called to avoid a ~20 second timeout in libvncserver. * May no longer be needed. */ static void ping_clients(int tile_cnt) { static time_t last_send = 0; time_t now = time(NULL); if (rfbMaxClientWait < 20000) { rfbMaxClientWait = 20000; rfbLog("reset rfbMaxClientWait to %d msec.\n", rfbMaxClientWait); } if (tile_cnt > 0) { last_send = now; } else if (tile_cnt < 0) { /* negative tile_cnt is -ping case */ if (now >= last_send - tile_cnt) { mark_rect_as_modified(0, 0, 1, 1, 1); last_send = now; } } else if (now - last_send > 5) { /* Send small heartbeat to client */ mark_rect_as_modified(0, 0, 1, 1, 1); last_send = now; } } /* * scan_display() wants to know if this tile can be skipped due to * blackout regions: (no data compare is done, just a quick geometric test) */ static int blackout_line_skip(int n, int x, int y, int rescan, int *tile_count) { if (tile_blackout[n].cover == 2) { tile_has_diff[n] = 0; return 1; /* skip it */ } else if (tile_blackout[n].cover == 1) { int w, x1, y1, x2, y2, b, hit = 0; if (x + NSCAN > dpy_x) { w = dpy_x - x; } else { w = NSCAN; } for (b=0; b < tile_blackout[n].count; b++) { /* n.b. these coords are in full display space: */ x1 = tile_blackout[n].bo[b].x1; x2 = tile_blackout[n].bo[b].x2; y1 = tile_blackout[n].bo[b].y1; y2 = tile_blackout[n].bo[b].y2; if (x2 - x1 < w) { /* need to cover full width */ continue; } if (y1 <= y && y < y2) { hit = 1; break; } } if (hit) { if (! rescan) { tile_has_diff[n] = 0; } else { *tile_count += tile_has_diff[n]; } return 1; /* skip */ } } return 0; /* do not skip */ } static int blackout_line_cmpskip(int n, int x, int y, char *dst, char *src, int w, int pixelsize) { int i, x1, y1, x2, y2, b, hit = 0; int beg = -1, end = -1; if (tile_blackout[n].cover == 0) { return 0; /* 0 means do not skip it. */ } else if (tile_blackout[n].cover == 2) { return 1; /* 1 means skip it. */ } /* tile has partial coverage: */ for (i=0; i < w * pixelsize; i++) { if (*(dst+i) != *(src+i)) { beg = i/pixelsize; /* beginning difference */ break; } } for (i = w * pixelsize - 1; i >= 0; i--) { if (*(dst+i) != *(src+i)) { end = i/pixelsize; /* ending difference */ break; } } if (beg < 0 || end < 0) { /* problem finding range... */ return 0; } /* loop over blackout rectangles: */ for (b=0; b < tile_blackout[n].count; b++) { /* y in full display space: */ y1 = tile_blackout[n].bo[b].y1; y2 = tile_blackout[n].bo[b].y2; /* x relative to tile origin: */ x1 = tile_blackout[n].bo[b].x1 - x; x2 = tile_blackout[n].bo[b].x2 - x; if (y1 > y || y >= y2) { continue; } if (x1 <= beg && end <= x2) { hit = 1; break; } } if (hit) { return 1; } else { return 0; } } /* * For the subwin case follows the window if it is moved. */ void set_offset(void) { Window w; if (! subwin) { return; } X_LOCK; xtranslate(window, rootwin, 0, 0, &off_x, &off_y, &w, 0); X_UNLOCK; } static int xd_samples = 0, xd_misses = 0, xd_do_check = 0; /* * Loop over 1-pixel tall horizontal scanlines looking for changes. * Record the changes in tile_has_diff[]. Scanlines in the loop are * equally spaced along y by NSCAN pixels, but have a slightly random * starting offset ystart ( < NSCAN ) from scanlines[]. */ static int scan_display(int ystart, int rescan) { char *src, *dst; int pixelsize = bpp/8; int x, y, w, n; int tile_count = 0; int nodiffs = 0, diff_hint; int xd_check = 0, xd_freq = 1; static int xd_tck = 0; y = ystart; g_now = dnow(); if (! main_fb) { rfbLog("scan_display: no main_fb!\n"); return 0; } X_LOCK; while (y < dpy_y) { if (use_xdamage) { XD_tot++; xd_check = 0; if (xdamage_hint_skip(y)) { if (xd_do_check && dpy && use_xdamage == 1) { xd_tck++; xd_tck = xd_tck % xd_freq; if (xd_tck == 0) { xd_check = 1; xd_samples++; } } if (!xd_check) { XD_skip++; y += NSCAN; continue; } } else { if (xd_do_check && 0) { fprintf(stderr, "ns y=%d\n", y); } } } /* grab the horizontal scanline from the display: */ #ifndef NO_NCACHE /* XXX Y test */ if (ncache > 0) { int gotone = 0; if (macosx_console) { if (macosx_checkevent(NULL)) { gotone = 1; } } else { #if !NO_X11 XEvent ev; if (raw_fb_str) { ; } else if (XEventsQueued(dpy, QueuedAlready) == 0) { ; /* XXX Y resp */ } else if (XCheckTypedEvent(dpy, MapNotify, &ev)) { gotone = 1; } else if (XCheckTypedEvent(dpy, UnmapNotify, &ev)) { gotone = 2; } else if (XCheckTypedEvent(dpy, CreateNotify, &ev)) { gotone = 3; } else if (XCheckTypedEvent(dpy, ConfigureNotify, &ev)) { gotone = 4; } else if (XCheckTypedEvent(dpy, VisibilityNotify, &ev)) { gotone = 5; } if (gotone) { XPutBackEvent(dpy, &ev); } #endif } if (gotone) { static int nomsg = 1; if (nomsg) { if (dnowx() > 20) { nomsg = 0; } } else { if (ncdb) fprintf(stderr, "\n*** SCAN_DISPLAY CHECK_NCACHE/%d *** %d rescan=%d\n", gotone, y, rescan); } X_UNLOCK; check_ncache(0, 1); X_LOCK; } } #endif XRANDR_SET_TRAP_RET(-1, "scan_display-set"); copy_image(scanline, 0, y, 0, 0); XRANDR_CHK_TRAP_RET(-1, "scan_display-chk"); /* for better memory i/o try the whole line at once */ src = scanline->data; dst = main_fb + y * main_bytes_per_line; if (! memcmp(dst, src, main_bytes_per_line)) { /* no changes anywhere in scan line */ nodiffs = 1; if (! rescan) { y += NSCAN; continue; } } if (xd_check) { xd_misses++; } x = 0; while (x < dpy_x) { n = (x/tile_x) + (y/tile_y) * ntiles_x; diff_hint = 0; if (blackouts) { if (blackout_line_skip(n, x, y, rescan, &tile_count)) { x += NSCAN; continue; } } if (rescan) { if (nodiffs || tile_has_diff[n]) { tile_count += tile_has_diff[n]; x += NSCAN; continue; } } else if (xdamage_tile_count && tile_has_xdamage_diff[n]) { tile_has_xdamage_diff[n] = 2; diff_hint = 1; } /* set ptrs to correspond to the x offset: */ src = scanline->data + x * pixelsize; dst = main_fb + y * main_bytes_per_line + x * pixelsize; /* compute the width of data to be compared: */ if (x + NSCAN > dpy_x) { w = dpy_x - x; } else { w = NSCAN; } if (diff_hint || memcmp(dst, src, w * pixelsize)) { /* found a difference, record it: */ if (! blackouts) { tile_has_diff[n] = 1; tile_count++; } else { if (blackout_line_cmpskip(n, x, y, dst, src, w, pixelsize)) { tile_has_diff[n] = 0; } else { tile_has_diff[n] = 1; tile_count++; } } } x += NSCAN; } y += NSCAN; } X_UNLOCK; return tile_count; } int scanlines[NSCAN] = { 0, 16, 8, 24, 4, 20, 12, 28, 10, 26, 18, 2, 22, 6, 30, 14, 1, 17, 9, 25, 7, 23, 15, 31, 19, 3, 27, 11, 29, 13, 5, 21 }; /* * toplevel for the scanning, rescanning, and applying the heuristics. * returns number of changed tiles. */ int scan_for_updates(int count_only) { int i, tile_count, tile_diffs; int old_copy_tile; double frac1 = 0.1; /* tweak parameter to try a 2nd scan_display() */ double frac2 = 0.35; /* or 3rd */ double frac3 = 0.02; /* do scan_display() again after copy_tiles() */ static double last_poll = 0.0; if (unixpw_in_progress) return 0; if (slow_fb > 0.0) { double now = dnow(); if (now < last_poll + slow_fb) { return 0; } last_poll = now; } for (i=0; i < ntiles; i++) { tile_has_diff[i] = 0; tile_has_xdamage_diff[i] = 0; tile_tried[i] = 0; tile_copied[i] = 0; } for (i=0; i < ntiles_y; i++) { /* could be useful, currently not used */ tile_row_has_xdamage_diff[i] = 0; } xdamage_tile_count = 0; /* * n.b. this program has only been tested so far with * tile_x = tile_y = NSCAN = 32! */ if (!count_only) { scan_count++; scan_count %= NSCAN; /* some periodic maintenance */ if (subwin && scan_count % 4 == 0) { set_offset(); /* follow the subwindow */ } if (indexed_color && scan_count % 4 == 0) { /* check for changed colormap */ set_colormap(0); } if (cmap8to24 && scan_count % 1 == 0) { check_for_multivis(); } #ifdef MACOSX if (macosx_console) { macosx_event_loop(); } #endif if (use_xdamage) { /* first pass collecting DAMAGE events: */ #ifdef MACOSX if (macosx_console) { collect_non_X_xdamage(-1, -1, -1, -1, 0); } else #endif { if (rawfb_vnc_reflect) { collect_non_X_xdamage(-1, -1, -1, -1, 0); } else { collect_xdamage(scan_count, 0); } } } } #define SCAN_FATAL(x) \ if (x < 0) { \ scan_in_progress = 0; \ fb_copy_in_progress = 0; \ return 0; \ } /* scan with the initial y to the jitter value from scanlines: */ scan_in_progress = 1; tile_count = scan_display(scanlines[scan_count], 0); SCAN_FATAL(tile_count); /* * we do the XDAMAGE here too since after scan_display() * there is a better chance we have received the events from * the X server (otherwise the DAMAGE events will be processed * in the *next* call, usually too late and wasteful since * the unchanged tiles are read in again). */ if (use_xdamage) { #ifdef MACOSX if (macosx_console) { ; } else #endif { if (rawfb_vnc_reflect) { ; } else { collect_xdamage(scan_count, 1); } } } if (count_only) { scan_in_progress = 0; fb_copy_in_progress = 0; return tile_count; } if (xdamage_tile_count) { /* pick up "known" damaged tiles we missed in scan_display() */ for (i=0; i < ntiles; i++) { if (tile_has_diff[i]) { continue; } if (tile_has_xdamage_diff[i]) { tile_has_diff[i] = 1; if (tile_has_xdamage_diff[i] == 1) { tile_has_xdamage_diff[i] = 2; tile_count++; } } } } if (dpy && use_xdamage == 1) { static time_t last_xd_check = 0; if (time(NULL) > last_xd_check + 2) { int cp = (scan_count + 3) % NSCAN; xd_do_check = 1; tile_count = scan_display(scanlines[cp], 0); xd_do_check = 0; SCAN_FATAL(tile_count); last_xd_check = time(NULL); if (xd_samples > 200) { static int bad = 0; if (xd_misses > (20 * xd_samples) / 100) { rfbLog("XDAMAGE is not working well... misses: %d/%d\n", xd_misses, xd_samples); rfbLog("Maybe an OpenGL app like Beryl or Compiz is the problem?\n"); rfbLog("Use x11vnc -noxdamage or disable the Beryl/Compiz app.\n"); rfbLog("To disable this check and warning specify -xdamage twice.\n"); if (++bad >= 10) { rfbLog("XDAMAGE appears broken (OpenGL app?), turning it off.\n"); use_xdamage = 0; initialize_xdamage(); destroy_xdamage_if_needed(); } } xd_samples = 0; xd_misses = 0; } } } nap_set(tile_count); if (fs_factor && frac1 >= fs_frac) { /* make frac1 < fs_frac if fullscreen updates are enabled */ frac1 = fs_frac/2.0; } if (tile_count > frac1 * ntiles) { /* * many tiles have changed, so try a rescan (since it should * be short compared to the many upcoming copy_tiles() calls) */ /* this check is done to skip the extra scan_display() call */ if (! fs_factor || tile_count <= fs_frac * ntiles) { int cp, tile_count_old = tile_count; /* choose a different y shift for the 2nd scan: */ cp = (NSCAN - scan_count) % NSCAN; tile_count = scan_display(scanlines[cp], 1); SCAN_FATAL(tile_count); if (tile_count >= (1 + frac2) * tile_count_old) { /* on a roll... do a 3rd scan */ cp = (NSCAN - scan_count + 7) % NSCAN; tile_count = scan_display(scanlines[cp], 1); SCAN_FATAL(tile_count); } } scan_in_progress = 0; /* * At some number of changed tiles it is better to just * copy the full screen at once. I.e. time = c1 + m * r1 * where m is number of tiles, r1 is the copy_tiles() * time, and c1 is the scan_display() time: for some m * it crosses the full screen update time. * * We try to predict that crossover with the fs_frac * fudge factor... seems to be about 1/2 the total number * of tiles. n.b. this ignores network bandwidth, * compression time etc... * * Use -fs 1.0 to disable on slow links. */ if (fs_factor && tile_count > fs_frac * ntiles) { int cs; fb_copy_in_progress = 1; cs = copy_screen(); fb_copy_in_progress = 0; SCAN_FATAL(cs); if (use_threads && pointer_mode != 1) { pointer_event(-1, 0, 0, NULL); } nap_check(tile_count); return tile_count; } } scan_in_progress = 0; /* copy all tiles with differences from display to rfb framebuffer: */ fb_copy_in_progress = 1; if (single_copytile || tile_shm_count < ntiles_x) { /* * Old way, copy I/O one tile at a time. */ old_copy_tile = 1; } else { /* * New way, does runs of horizontal tiles at once. * Note that below, for simplicity, the extra tile finding * (e.g. copy_tiles_backward_pass) is done the old way. */ old_copy_tile = 0; } if (unixpw_in_progress) return 0; if (old_copy_tile) { tile_diffs = copy_all_tiles(); } else { tile_diffs = copy_all_tile_runs(); } SCAN_FATAL(tile_diffs); /* * This backward pass for upward and left tiles complements what * was done in copy_all_tiles() for downward and right tiles. */ tile_diffs = copy_tiles_backward_pass(); SCAN_FATAL(tile_diffs); if (tile_diffs > frac3 * ntiles) { /* * we spent a lot of time in those copy_tiles, run * another scan, maybe more of the screen changed. */ int cp = (NSCAN - scan_count + 13) % NSCAN; scan_in_progress = 1; tile_count = scan_display(scanlines[cp], 1); SCAN_FATAL(tile_count); scan_in_progress = 0; tile_diffs = copy_tiles_additional_pass(); SCAN_FATAL(tile_diffs); } /* Given enough tile diffs, try the islands: */ if (grow_fill && tile_diffs > 4) { tile_diffs = grow_islands(); } SCAN_FATAL(tile_diffs); /* Given enough tile diffs, try the gaps: */ if (gaps_fill && tile_diffs > 4) { tile_diffs = fill_tile_gaps(); } SCAN_FATAL(tile_diffs); fb_copy_in_progress = 0; if (use_threads && pointer_mode != 1) { /* * tell the pointer handler it can process any queued * pointer events: */ pointer_event(-1, 0, 0, NULL); } if (blackouts) { /* ignore any diffs in completely covered tiles */ int x, y, n; for (y=0; y < ntiles_y; y++) { for (x=0; x < ntiles_x; x++) { n = x + y * ntiles_x; if (tile_blackout[n].cover == 2) { tile_has_diff[n] = 0; } } } } hint_updates(); /* use x0rfbserver hints algorithm */ /* Work around threaded rfbProcessClientMessage() calls timeouts */ if (use_threads) { ping_clients(tile_diffs); } else if (saw_ultra_chat || saw_ultra_file) { ping_clients(-1); } else if (use_openssl && !tile_diffs) { ping_clients(0); } /* -ping option: */ if (ping_interval) { int td = ping_interval > 0 ? ping_interval : -ping_interval; ping_clients(-td); } nap_check(tile_diffs); return tile_diffs; }
./CrossVul/dataset_final_sorted/CWE-862/c/bad_4459_0
crossvul-cpp_data_good_3155_0
/* * * Copyright © 2013 Serge Hallyn <serge.hallyn@ubuntu.com>. * Copyright © 2013 Canonical Ltd. * * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #define _GNU_SOURCE /* See feature_test_macros(7) */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <sys/types.h> #include <pwd.h> #include <grp.h> #include <unistd.h> #include <fcntl.h> #include <sys/file.h> #include <alloca.h> #include <string.h> #include <sched.h> #include <sys/mman.h> #include <sys/socket.h> #include <errno.h> #include <ctype.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <linux/netlink.h> #include <arpa/inet.h> #include <net/if.h> #include <net/if_arp.h> #include <netinet/in.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <linux/sockios.h> #include <sys/param.h> #include "config.h" #include "utils.h" #include "network.h" #define usernic_debug_stream(stream, format, ...) \ do { \ fprintf(stream, "%s: %d: %s: " format, __FILE__, __LINE__, \ __func__, __VA_ARGS__); \ } while (false) #define usernic_error(format, ...) usernic_debug_stream(stderr, format, __VA_ARGS__) static void usage(char *me, bool fail) { fprintf(stderr, "Usage: %s lxcpath name pid type bridge nicname\n", me); fprintf(stderr, " nicname is the name to use inside the container\n"); exit(fail ? 1 : 0); } static char *lxcpath, *lxcname; static int open_and_lock(char *path) { int fd; struct flock lk; fd = open(path, O_RDWR|O_CREAT, S_IWUSR | S_IRUSR); if (fd < 0) { fprintf(stderr, "Failed to open %s: %s\n", path, strerror(errno)); return(fd); } lk.l_type = F_WRLCK; lk.l_whence = SEEK_SET; lk.l_start = 0; lk.l_len = 0; if (fcntl(fd, F_SETLKW, &lk) < 0) { fprintf(stderr, "Failed to lock %s: %s\n", path, strerror(errno)); close(fd); return -1; } return fd; } static char *get_username(void) { struct passwd *pwd = getpwuid(getuid()); if (pwd == NULL) { perror("getpwuid"); return NULL; } return pwd->pw_name; } static void free_groupnames(char **groupnames) { int i; if (!groupnames) return; for (i = 0; groupnames[i]; i++) free(groupnames[i]); free(groupnames); } static char **get_groupnames(void) { int ngroups; gid_t *group_ids; int ret, i; char **groupnames; struct group *gr; ngroups = getgroups(0, NULL); if (ngroups == -1) { fprintf(stderr, "Failed to get number of groups user belongs to: %s\n", strerror(errno)); return NULL; } if (ngroups == 0) return NULL; group_ids = (gid_t *)malloc(sizeof(gid_t)*ngroups); if (group_ids == NULL) { fprintf(stderr, "Out of memory while getting groups the user belongs to\n"); return NULL; } ret = getgroups(ngroups, group_ids); if (ret < 0) { free(group_ids); fprintf(stderr, "Failed to get process groups: %s\n", strerror(errno)); return NULL; } groupnames = (char **)malloc(sizeof(char *)*(ngroups+1)); if (groupnames == NULL) { free(group_ids); fprintf(stderr, "Out of memory while getting group names\n"); return NULL; } memset(groupnames, 0, sizeof(char *)*(ngroups+1)); for (i=0; i<ngroups; i++ ) { gr = getgrgid(group_ids[i]); if (gr == NULL) { fprintf(stderr, "Failed to get group name\n"); free(group_ids); free_groupnames(groupnames); return NULL; } groupnames[i] = strdup(gr->gr_name); if (groupnames[i] == NULL) { fprintf(stderr, "Failed to copy group name: %s", gr->gr_name); free(group_ids); free_groupnames(groupnames); return NULL; } } free(group_ids); return groupnames; } static bool name_is_in_groupnames(char *name, char **groupnames) { while (groupnames != NULL) { if (strcmp(name, *groupnames) == 0) return true; groupnames++; } return false; } struct alloted_s { char *name; int allowed; struct alloted_s *next; }; static struct alloted_s *append_alloted(struct alloted_s **head, char *name, int n) { struct alloted_s *cur, *al; if (head == NULL || name == NULL) { // sanity check. parameters should not be null fprintf(stderr, "NULL parameters to append_alloted not allowed\n"); return NULL; } al = (struct alloted_s *)malloc(sizeof(struct alloted_s)); if (al == NULL) { // unable to allocate memory to new struct fprintf(stderr, "Out of memory in append_alloted\n"); return NULL; } al->name = strdup(name); if (al->name == NULL) { free(al); return NULL; } al->allowed = n; al->next = NULL; if (*head == NULL) { *head = al; return al; } cur = *head; while (cur->next != NULL) cur = cur->next; cur->next = al; return al; } static void free_alloted(struct alloted_s **head) { struct alloted_s *cur; if (head == NULL) { return; } cur = *head; while (cur != NULL) { cur = cur->next; free((*head)->name); free(*head); *head = cur; } } /* The configuration file consists of lines of the form: * * user type bridge count * or * @group type bridge count * * Return the count entry for the calling user if there is one. Else * return -1. */ static int get_alloted(char *me, char *intype, char *link, struct alloted_s **alloted) { FILE *fin = fopen(LXC_USERNIC_CONF, "r"); char *line = NULL; char name[100], type[100], br[100]; size_t len = 0; int n, ret, count = 0; char **groups; if (!fin) { fprintf(stderr, "Failed to open %s: %s\n", LXC_USERNIC_CONF, strerror(errno)); return -1; } groups = get_groupnames(); while ((getline(&line, &len, fin)) != -1) { ret = sscanf(line, "%99[^ \t] %99[^ \t] %99[^ \t] %d", name, type, br, &n); if (ret != 4) continue; if (strlen(name) == 0) continue; if (strcmp(name, me) != 0) { if (name[0] != '@') continue; if (!name_is_in_groupnames(name+1, groups)) continue; } if (strcmp(type, intype) != 0) continue; if (strcmp(link, br) != 0) continue; /* found the user or group with the appropriate settings, therefore finish the search. * what to do if there are more than one applicable lines? not specified in the docs. * since getline is implemented with realloc, we don't need to free line until exiting func. * * if append_alloted returns NULL, e.g. due to a malloc error, we set count to 0 and break the loop, * allowing cleanup and then exiting from main() */ if (append_alloted(alloted, name, n) == NULL) { count = 0; break; } count += n; } free_groupnames(groups); fclose(fin); free(line); // now return the total number of nics that this user can create return count; } static char *get_eol(char *s, char *e) { while (s<e && *s && *s != '\n') s++; return s; } static char *get_eow(char *s, char *e) { while (s<e && *s && !isblank(*s) && *s != '\n') s++; return s; } static char *find_line(char *p, char *e, char *u, char *t, char *l) { char *p1, *p2, *ret; while (p<e && (p1 = get_eol(p, e)) < e) { ret = p; if (*p == '#') goto next; while (p<e && isblank(*p)) p++; p2 = get_eow(p, e); if (!p2 || p2-p != strlen(u) || strncmp(p, u, strlen(u)) != 0) goto next; p = p2+1; while (p<e && isblank(*p)) p++; p2 = get_eow(p, e); if (!p2 || p2-p != strlen(t) || strncmp(p, t, strlen(t)) != 0) goto next; p = p2+1; while (p<e && isblank(*p)) p++; p2 = get_eow(p, e); if (!p2 || p2-p != strlen(l) || strncmp(p, l, strlen(l)) != 0) goto next; return ret; next: p = p1 + 1; } return NULL; } static bool nic_exists(char *nic) { char path[MAXPATHLEN]; int ret; struct stat sb; if (strcmp(nic, "none") == 0) return true; ret = snprintf(path, MAXPATHLEN, "/sys/class/net/%s", nic); if (ret < 0 || ret >= MAXPATHLEN) // should never happen! return false; ret = stat(path, &sb); if (ret != 0) return false; return true; } static int instantiate_veth(char *n1, char **n2) { int err; err = snprintf(*n2, IFNAMSIZ, "%sp", n1); if (err < 0 || err >= IFNAMSIZ) { fprintf(stderr, "nic name too long\n"); return -1; } err = lxc_veth_create(n1, *n2); if (err) { fprintf(stderr, "failed to create %s-%s : %s\n", n1, *n2, strerror(-err)); return -1; } /* changing the high byte of the mac address to 0xfe, the bridge interface * will always keep the host's mac address and not take the mac address * of a container */ err = setup_private_host_hw_addr(n1); if (err) { fprintf(stderr, "failed to change mac address of host interface '%s' : %s\n", n1, strerror(-err)); } return netdev_set_flag(n1, IFF_UP); } static int get_mtu(char *name) { int idx = if_nametoindex(name); return netdev_get_mtu(idx); } static bool create_nic(char *nic, char *br, int pid, char **cnic) { char *veth1buf, *veth2buf; veth1buf = alloca(IFNAMSIZ); veth2buf = alloca(IFNAMSIZ); int ret, mtu; ret = snprintf(veth1buf, IFNAMSIZ, "%s", nic); if (ret < 0 || ret >= IFNAMSIZ) { fprintf(stderr, "host nic name too long\n"); return false; } /* create the nics */ if (instantiate_veth(veth1buf, &veth2buf) < 0) { fprintf(stderr, "Error creating veth tunnel\n"); return false; } if (strcmp(br, "none") != 0) { /* copy the bridge's mtu to both ends */ mtu = get_mtu(br); if (mtu != -1) { if (lxc_netdev_set_mtu(veth1buf, mtu) < 0 || lxc_netdev_set_mtu(veth2buf, mtu) < 0) { fprintf(stderr, "Failed setting mtu\n"); goto out_del; } } /* attach veth1 to bridge */ if (lxc_bridge_attach(lxcpath, lxcname, br, veth1buf) < 0) { fprintf(stderr, "Error attaching %s to %s\n", veth1buf, br); goto out_del; } } /* pass veth2 to target netns */ ret = lxc_netdev_move_by_name(veth2buf, pid, NULL); if (ret < 0) { fprintf(stderr, "Error moving %s to netns %d\n", veth2buf, pid); goto out_del; } *cnic = strdup(veth2buf); return true; out_del: lxc_netdev_delete_by_name(veth1buf); return false; } /* * Get a new nic. * *dest will container the name (vethXXXXXX) which is attached * on the host to the lxc bridge */ static bool get_new_nicname(char **dest, char *br, int pid, char **cnic) { char template[IFNAMSIZ]; snprintf(template, sizeof(template), "vethXXXXXX"); *dest = lxc_mkifname(template); if (!create_nic(*dest, br, pid, cnic)) { return false; } return true; } static bool get_nic_from_line(char *p, char **nic) { char user[100], type[100], br[100]; int ret; ret = sscanf(p, "%99[^ \t\n] %99[^ \t\n] %99[^ \t\n] %99[^ \t\n]", user, type, br, *nic); if (ret != 4) return false; return true; } struct entry_line { char *start; int len; bool keep; }; static bool cull_entries(int fd, char *me, char *t, char *br) { struct stat sb; char *buf, *p, *e, *nic; off_t len; struct entry_line *entry_lines = NULL; int i, n = 0; nic = alloca(100); if (fstat(fd, &sb) < 0) { fprintf(stderr, "Failed to fstat: %s\n", strerror(errno)); return false; } len = sb.st_size; if (len == 0) return true; buf = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if (buf == MAP_FAILED) { fprintf(stderr, "Failed to create mapping: %s\n", strerror(errno)); return false; } p = buf; e = buf + len; while ((p = find_line(p, e, me, t, br)) != NULL) { struct entry_line *newe = realloc(entry_lines, sizeof(*entry_lines)*(n+1)); if (!newe) { free(entry_lines); return false; } entry_lines = newe; entry_lines[n].start = p; entry_lines[n].len = get_eol(p, e) - entry_lines[n].start; entry_lines[n].keep = true; n++; if (!get_nic_from_line(p, &nic)) continue; if (nic && !nic_exists(nic)) entry_lines[n-1].keep = false; p += entry_lines[n-1].len + 1; if (p >= e) break; } p = buf; for (i=0; i<n; i++) { if (!entry_lines[i].keep) continue; memcpy(p, entry_lines[i].start, entry_lines[i].len); p += entry_lines[i].len; *p = '\n'; p++; } free(entry_lines); munmap(buf, sb.st_size); if (ftruncate(fd, p-buf)) fprintf(stderr, "Failed to set new file size\n"); return true; } static int count_entries(char *buf, off_t len, char *me, char *t, char *br) { char *e = &buf[len]; int count = 0; while ((buf = find_line(buf, e, me, t, br)) != NULL) { count++; buf = get_eol(buf, e)+1; if (buf >= e) break; } return count; } /* * The dbfile has lines of the format: * user type bridge nicname */ static bool get_nic_if_avail(int fd, struct alloted_s *names, int pid, char *intype, char *br, int allowed, char **nicname, char **cnic) { off_t len, slen; struct stat sb; char *buf = NULL, *newline; int ret, count = 0; char *owner; struct alloted_s *n; for (n=names; n!=NULL; n=n->next) cull_entries(fd, n->name, intype, br); if (allowed == 0) return false; owner = names->name; if (fstat(fd, &sb) < 0) { fprintf(stderr, "Failed to fstat: %s\n", strerror(errno)); return false; } len = sb.st_size; if (len != 0) { buf = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if (buf == MAP_FAILED) { fprintf(stderr, "Failed to create mapping\n"); return false; } owner = NULL; for (n=names; n!=NULL; n=n->next) { count = count_entries(buf, len, n->name, intype, br); if (count >= n->allowed) continue; owner = n->name; break; } } if (owner == NULL) return false; if (!get_new_nicname(nicname, br, pid, cnic)) return false; /* owner ' ' intype ' ' br ' ' *nicname + '\n' + '\0' */ slen = strlen(owner) + strlen(intype) + strlen(br) + strlen(*nicname) + 5; newline = alloca(slen); ret = snprintf(newline, slen, "%s %s %s %s\n", owner, intype, br, *nicname); if (ret < 0 || ret >= slen) { if (lxc_netdev_delete_by_name(*nicname) != 0) fprintf(stderr, "Error unlinking %s!\n", *nicname); return false; } if (len) munmap(buf, len); if (ftruncate(fd, len + slen)) fprintf(stderr, "Failed to set new file size\n"); buf = mmap(NULL, len + slen, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if (buf == MAP_FAILED) { fprintf(stderr, "Failed to create mapping after extending: %s\n", strerror(errno)); if (lxc_netdev_delete_by_name(*nicname) != 0) fprintf(stderr, "Error unlinking %s!\n", *nicname); return false; } strcpy(buf+len, newline); munmap(buf, len+slen); return true; } static bool create_db_dir(char *fnam) { char *p = alloca(strlen(fnam)+1); strcpy(p, fnam); fnam = p; p = p + 1; again: while (*p && *p != '/') p++; if (!*p) return true; *p = '\0'; if (mkdir(fnam, 0755) && errno != EEXIST) { fprintf(stderr, "failed to create %s\n", fnam); *p = '/'; return false; } *(p++) = '/'; goto again; } #define VETH_DEF_NAME "eth%d" static int rename_in_ns(int pid, char *oldname, char **newnamep) { uid_t ruid, suid, euid; int fret = -1; int fd = -1, ifindex = -1, ofd = -1, ret; bool grab_newname = false; ofd = lxc_preserve_ns(getpid(), "net"); if (ofd < 0) { usernic_error("Failed opening network namespace path for '%d'.", getpid()); return fret; } fd = lxc_preserve_ns(pid, "net"); if (fd < 0) { usernic_error("Failed opening network namespace path for '%d'.", pid); goto do_partial_cleanup; } ret = getresuid(&ruid, &euid, &suid); if (ret < 0) { usernic_error("Failed to retrieve real, effective, and saved " "user IDs: %s\n", strerror(errno)); goto do_partial_cleanup; } ret = setns(fd, CLONE_NEWNET); close(fd); fd = -1; if (ret < 0) { usernic_error("Failed to setns() to the network namespace of " "the container with PID %d: %s.\n", pid, strerror(errno)); goto do_partial_cleanup; } ret = setresuid(ruid, ruid, 0); if (ret < 0) { usernic_error("Failed to drop privilege by setting effective " "user id and real user id to %d, and saved user " "ID to 0: %s.\n", ruid, strerror(errno)); // COMMENT(brauner): It's ok to jump to do_full_cleanup here // since setresuid() will succeed when trying to set real, // effective, and saved to values they currently have. goto do_full_cleanup; } if (!*newnamep) { grab_newname = true; *newnamep = VETH_DEF_NAME; ifindex = if_nametoindex(oldname); if (!ifindex) { usernic_error("Failed to get netdev index: %s.\n", strerror(errno)); goto do_full_cleanup; } } ret = lxc_netdev_rename_by_name(oldname, *newnamep); if (ret < 0) { usernic_error("Error %d renaming netdev %s to %s in container.\n", ret, oldname, *newnamep); goto do_full_cleanup; } if (grab_newname) { char ifname[IFNAMSIZ]; char *namep = ifname; if (!if_indextoname(ifindex, namep)) { usernic_error("Failed to get new netdev name: %s.\n", strerror(errno)); goto do_full_cleanup; } *newnamep = strdup(namep); if (!*newnamep) goto do_full_cleanup; } fret = 0; do_full_cleanup: ret = setresuid(ruid, euid, suid); if (ret < 0) { usernic_error("Failed to restore privilege by setting effective " "user id to %d, real user id to %d, and saved user " "ID to %d: %s.\n", ruid, euid, suid, strerror(errno)); fret = -1; // COMMENT(brauner): setns() should fail if setresuid() doesn't // succeed but there's no harm in falling through; keeps the // code cleaner. } ret = setns(ofd, CLONE_NEWNET); if (ret < 0) { usernic_error("Failed to setns() to original network namespace " "of PID %d: %s.\n", ofd, strerror(errno)); fret = -1; } do_partial_cleanup: if (fd >= 0) close(fd); close(ofd); return fret; } /* * If the caller (real uid, not effective uid) may read the * /proc/[pid]/ns/net, then it is either the caller's netns or one * which it created. */ static bool may_access_netns(int pid) { int ret; char s[200]; uid_t ruid, suid, euid; bool may_access = false; ret = getresuid(&ruid, &euid, &suid); if (ret) { fprintf(stderr, "Failed to get my uids: %s\n", strerror(errno)); return false; } ret = setresuid(ruid, ruid, euid); if (ret) { fprintf(stderr, "Failed to set temp uids to (%d,%d,%d): %s\n", (int)ruid, (int)ruid, (int)euid, strerror(errno)); return false; } ret = snprintf(s, 200, "/proc/%d/ns/net", pid); if (ret < 0 || ret >= 200) // can't happen return false; ret = access(s, R_OK); if (ret) { fprintf(stderr, "Uid %d may not access %s: %s\n", (int)ruid, s, strerror(errno)); } may_access = ret == 0; ret = setresuid(ruid, euid, suid); if (ret) { fprintf(stderr, "Failed to restore uids to (%d,%d,%d): %s\n", (int)ruid, (int)euid, (int)suid, strerror(errno)); may_access = false; } return may_access; } int main(int argc, char *argv[]) { int n, fd; bool gotone = false; char *me; char *nicname = alloca(40); char *cnic = NULL; // created nic name in container is returned here. char *vethname = NULL; int pid; struct alloted_s *alloted = NULL; /* set a sane env, because we are setuid-root */ if (clearenv() < 0) { fprintf(stderr, "Failed to clear environment"); exit(1); } if (setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", 1) < 0) { fprintf(stderr, "Failed to set PATH, exiting\n"); exit(1); } if ((me = get_username()) == NULL) { fprintf(stderr, "Failed to get username\n"); exit(1); } if (argc < 6) usage(argv[0], true); if (argc >= 7) vethname = argv[6]; lxcpath = argv[1]; lxcname = argv[2]; errno = 0; pid = (int) strtol(argv[3], NULL, 10); if (errno) { fprintf(stderr, "Could not read pid: %s\n", argv[1]); exit(1); } if (!create_db_dir(LXC_USERNIC_DB)) { fprintf(stderr, "Failed to create directory for db file\n"); exit(1); } if ((fd = open_and_lock(LXC_USERNIC_DB)) < 0) { fprintf(stderr, "Failed to lock %s\n", LXC_USERNIC_DB); exit(1); } if (!may_access_netns(pid)) { fprintf(stderr, "User %s may not modify netns for pid %d\n", me, pid); exit(1); } n = get_alloted(me, argv[4], argv[5], &alloted); if (n > 0) gotone = get_nic_if_avail(fd, alloted, pid, argv[4], argv[5], n, &nicname, &cnic); close(fd); free_alloted(&alloted); if (!gotone) { fprintf(stderr, "Quota reached\n"); exit(1); } // Now rename the link if (rename_in_ns(pid, cnic, &vethname) < 0) { fprintf(stderr, "Failed to rename the link\n"); exit(1); } // write the name of the interface pair to the stdout - like eth0:veth9MT2L4 fprintf(stdout, "%s:%s\n", vethname, nicname); exit(0); }
./CrossVul/dataset_final_sorted/CWE-862/c/good_3155_0
crossvul-cpp_data_good_1539_0
/*************************************************************************** * Copyright (C) 2005-2015 by the Quassel Project * * devel@quassel-irc.org * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) version 3. * * * * 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 "corebasichandler.h" #include "util.h" #include "logger.h" CoreBasicHandler::CoreBasicHandler(CoreNetwork *parent) : BasicHandler(parent), _network(parent) { connect(this, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)), network(), SLOT(displayMsg(Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags))); connect(this, SIGNAL(putCmd(QString, const QList<QByteArray> &, const QByteArray &)), network(), SLOT(putCmd(QString, const QList<QByteArray> &, const QByteArray &))); connect(this, SIGNAL(putCmd(QString, const QList<QList<QByteArray>> &, const QByteArray &)), network(), SLOT(putCmd(QString, const QList<QList<QByteArray>> &, const QByteArray &))); connect(this, SIGNAL(putRawLine(const QByteArray &)), network(), SLOT(putRawLine(const QByteArray &))); } QString CoreBasicHandler::serverDecode(const QByteArray &string) { return network()->serverDecode(string); } QStringList CoreBasicHandler::serverDecode(const QList<QByteArray> &stringlist) { QStringList list; foreach(QByteArray s, stringlist) list << network()->serverDecode(s); return list; } QString CoreBasicHandler::channelDecode(const QString &bufferName, const QByteArray &string) { return network()->channelDecode(bufferName, string); } QStringList CoreBasicHandler::channelDecode(const QString &bufferName, const QList<QByteArray> &stringlist) { QStringList list; foreach(QByteArray s, stringlist) list << network()->channelDecode(bufferName, s); return list; } QString CoreBasicHandler::userDecode(const QString &userNick, const QByteArray &string) { return network()->userDecode(userNick, string); } QStringList CoreBasicHandler::userDecode(const QString &userNick, const QList<QByteArray> &stringlist) { QStringList list; foreach(QByteArray s, stringlist) list << network()->userDecode(userNick, s); return list; } /*** ***/ QByteArray CoreBasicHandler::serverEncode(const QString &string) { return network()->serverEncode(string); } QList<QByteArray> CoreBasicHandler::serverEncode(const QStringList &stringlist) { QList<QByteArray> list; foreach(QString s, stringlist) list << network()->serverEncode(s); return list; } QByteArray CoreBasicHandler::channelEncode(const QString &bufferName, const QString &string) { return network()->channelEncode(bufferName, string); } QList<QByteArray> CoreBasicHandler::channelEncode(const QString &bufferName, const QStringList &stringlist) { QList<QByteArray> list; foreach(QString s, stringlist) list << network()->channelEncode(bufferName, s); return list; } QByteArray CoreBasicHandler::userEncode(const QString &userNick, const QString &string) { return network()->userEncode(userNick, string); } QList<QByteArray> CoreBasicHandler::userEncode(const QString &userNick, const QStringList &stringlist) { QList<QByteArray> list; foreach(QString s, stringlist) list << network()->userEncode(userNick, s); return list; } // ==================== // protected: // ==================== BufferInfo::Type CoreBasicHandler::typeByTarget(const QString &target) const { if (target.isEmpty()) return BufferInfo::StatusBuffer; if (network()->isChannelName(target)) return BufferInfo::ChannelBuffer; return BufferInfo::QueryBuffer; } void CoreBasicHandler::putCmd(const QString &cmd, const QByteArray &param, const QByteArray &prefix) { QList<QByteArray> list; list << param; emit putCmd(cmd, list, prefix); }
./CrossVul/dataset_final_sorted/CWE-399/cpp/good_1539_0
crossvul-cpp_data_bad_1539_0
/*************************************************************************** * Copyright (C) 2005-2015 by the Quassel Project * * devel@quassel-irc.org * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) version 3. * * * * 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 "corebasichandler.h" #include "util.h" #include "logger.h" CoreBasicHandler::CoreBasicHandler(CoreNetwork *parent) : BasicHandler(parent), _network(parent) { connect(this, SIGNAL(displayMsg(Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags)), network(), SLOT(displayMsg(Message::Type, BufferInfo::Type, const QString &, const QString &, const QString &, Message::Flags))); connect(this, SIGNAL(putCmd(QString, const QList<QByteArray> &, const QByteArray &)), network(), SLOT(putCmd(QString, const QList<QByteArray> &, const QByteArray &))); connect(this, SIGNAL(putRawLine(const QByteArray &)), network(), SLOT(putRawLine(const QByteArray &))); } QString CoreBasicHandler::serverDecode(const QByteArray &string) { return network()->serverDecode(string); } QStringList CoreBasicHandler::serverDecode(const QList<QByteArray> &stringlist) { QStringList list; foreach(QByteArray s, stringlist) list << network()->serverDecode(s); return list; } QString CoreBasicHandler::channelDecode(const QString &bufferName, const QByteArray &string) { return network()->channelDecode(bufferName, string); } QStringList CoreBasicHandler::channelDecode(const QString &bufferName, const QList<QByteArray> &stringlist) { QStringList list; foreach(QByteArray s, stringlist) list << network()->channelDecode(bufferName, s); return list; } QString CoreBasicHandler::userDecode(const QString &userNick, const QByteArray &string) { return network()->userDecode(userNick, string); } QStringList CoreBasicHandler::userDecode(const QString &userNick, const QList<QByteArray> &stringlist) { QStringList list; foreach(QByteArray s, stringlist) list << network()->userDecode(userNick, s); return list; } /*** ***/ QByteArray CoreBasicHandler::serverEncode(const QString &string) { return network()->serverEncode(string); } QList<QByteArray> CoreBasicHandler::serverEncode(const QStringList &stringlist) { QList<QByteArray> list; foreach(QString s, stringlist) list << network()->serverEncode(s); return list; } QByteArray CoreBasicHandler::channelEncode(const QString &bufferName, const QString &string) { return network()->channelEncode(bufferName, string); } QList<QByteArray> CoreBasicHandler::channelEncode(const QString &bufferName, const QStringList &stringlist) { QList<QByteArray> list; foreach(QString s, stringlist) list << network()->channelEncode(bufferName, s); return list; } QByteArray CoreBasicHandler::userEncode(const QString &userNick, const QString &string) { return network()->userEncode(userNick, string); } QList<QByteArray> CoreBasicHandler::userEncode(const QString &userNick, const QStringList &stringlist) { QList<QByteArray> list; foreach(QString s, stringlist) list << network()->userEncode(userNick, s); return list; } // ==================== // protected: // ==================== BufferInfo::Type CoreBasicHandler::typeByTarget(const QString &target) const { if (target.isEmpty()) return BufferInfo::StatusBuffer; if (network()->isChannelName(target)) return BufferInfo::ChannelBuffer; return BufferInfo::QueryBuffer; } void CoreBasicHandler::putCmd(const QString &cmd, const QByteArray &param, const QByteArray &prefix) { QList<QByteArray> list; list << param; emit putCmd(cmd, list, prefix); }
./CrossVul/dataset_final_sorted/CWE-399/cpp/bad_1539_0
crossvul-cpp_data_bad_3854_0
/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2010 InspIRCd Development Team * See: http://wiki.inspircd.org/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ /* $Core */ /* dns.cpp - Nonblocking DNS functions. Very very loosely based on the firedns library, Copyright (C) 2002 Ian Gulliver. This file is no longer anything like firedns, there are many major differences between this code and the original. Please do not assume that firedns works like this, looks like this, walks like this or tastes like this. */ #ifndef WIN32 #include <sys/types.h> #include <sys/socket.h> #include <errno.h> #include <netinet/in.h> #include <arpa/inet.h> #else #include "inspircd_win32wrapper.h" #endif #include "inspircd.h" #include "socketengine.h" #include "configreader.h" #include "socket.h" #define DN_COMP_BITMASK 0xC000 /* highest 6 bits in a DN label header */ /** Masks to mask off the responses we get from the DNSRequest methods */ enum QueryInfo { ERROR_MASK = 0x10000 /* Result is an error */ }; /** Flags which can be ORed into a request or reply for different meanings */ enum QueryFlags { FLAGS_MASK_RD = 0x01, /* Recursive */ FLAGS_MASK_TC = 0x02, FLAGS_MASK_AA = 0x04, /* Authoritative */ FLAGS_MASK_OPCODE = 0x78, FLAGS_MASK_QR = 0x80, FLAGS_MASK_RCODE = 0x0F, /* Request */ FLAGS_MASK_Z = 0x70, FLAGS_MASK_RA = 0x80 }; /** Represents a dns resource record (rr) */ struct ResourceRecord { QueryType type; /* Record type */ unsigned int rr_class; /* Record class */ unsigned long ttl; /* Time to live */ unsigned int rdlength; /* Record length */ }; /** Represents a dns request/reply header, and its payload as opaque data. */ class DNSHeader { public: unsigned char id[2]; /* Request id */ unsigned int flags1; /* Flags */ unsigned int flags2; /* Flags */ unsigned int qdcount; unsigned int ancount; /* Answer count */ unsigned int nscount; /* Nameserver count */ unsigned int arcount; unsigned char payload[512]; /* Packet payload */ }; class DNSRequest { public: unsigned char id[2]; /* Request id */ unsigned char* res; /* Result processing buffer */ unsigned int rr_class; /* Request class */ QueryType type; /* Request type */ DNS* dnsobj; /* DNS caller (where we get our FD from) */ unsigned long ttl; /* Time to live */ std::string orig; /* Original requested name/ip */ DNSRequest(DNS* dns, int id, const std::string &original); ~DNSRequest(); DNSInfo ResultIsReady(DNSHeader &h, unsigned length); int SendRequests(const DNSHeader *header, const int length, QueryType qt); }; class CacheTimer : public Timer { private: DNS* dns; public: CacheTimer(DNS* thisdns) : Timer(3600, ServerInstance->Time(), true), dns(thisdns) { } virtual void Tick(time_t) { dns->PruneCache(); } }; class RequestTimeout : public Timer { DNSRequest* watch; int watchid; public: RequestTimeout(unsigned long n, DNSRequest* watching, int id) : Timer(n, ServerInstance->Time()), watch(watching), watchid(id) { } ~RequestTimeout() { if (ServerInstance->Res) Tick(0); } void Tick(time_t) { if (ServerInstance->Res->requests[watchid] == watch) { /* Still exists, whack it */ if (ServerInstance->Res->Classes[watchid]) { ServerInstance->Res->Classes[watchid]->OnError(RESOLVER_TIMEOUT, "Request timed out"); delete ServerInstance->Res->Classes[watchid]; ServerInstance->Res->Classes[watchid] = NULL; } ServerInstance->Res->requests[watchid] = NULL; delete watch; } } }; CachedQuery::CachedQuery(const std::string &res, unsigned int ttl) : data(res) { expires = ServerInstance->Time() + ttl; } int CachedQuery::CalcTTLRemaining() { int n = expires - ServerInstance->Time(); return (n < 0 ? 0 : n); } /* Allocate the processing buffer */ DNSRequest::DNSRequest(DNS* dns, int rid, const std::string &original) : dnsobj(dns) { /* hardening against overflow here: make our work buffer twice the theoretical * maximum size so that hostile input doesn't screw us over. */ res = new unsigned char[sizeof(DNSHeader) * 2]; *res = 0; orig = original; RequestTimeout* RT = new RequestTimeout(ServerInstance->Config->dns_timeout ? ServerInstance->Config->dns_timeout : 5, this, rid); ServerInstance->Timers->AddTimer(RT); /* The timer manager frees this */ } /* Deallocate the processing buffer */ DNSRequest::~DNSRequest() { delete[] res; } /** Fill a ResourceRecord class based on raw data input */ inline void DNS::FillResourceRecord(ResourceRecord* rr, const unsigned char *input) { rr->type = (QueryType)((input[0] << 8) + input[1]); rr->rr_class = (input[2] << 8) + input[3]; rr->ttl = (input[4] << 24) + (input[5] << 16) + (input[6] << 8) + input[7]; rr->rdlength = (input[8] << 8) + input[9]; } /** Fill a DNSHeader class based on raw data input of a given length */ inline void DNS::FillHeader(DNSHeader *header, const unsigned char *input, const int length) { header->id[0] = input[0]; header->id[1] = input[1]; header->flags1 = input[2]; header->flags2 = input[3]; header->qdcount = (input[4] << 8) + input[5]; header->ancount = (input[6] << 8) + input[7]; header->nscount = (input[8] << 8) + input[9]; header->arcount = (input[10] << 8) + input[11]; memcpy(header->payload,&input[12],length); } /** Empty a DNSHeader class out into raw data, ready for transmission */ inline void DNS::EmptyHeader(unsigned char *output, const DNSHeader *header, const int length) { output[0] = header->id[0]; output[1] = header->id[1]; output[2] = header->flags1; output[3] = header->flags2; output[4] = header->qdcount >> 8; output[5] = header->qdcount & 0xFF; output[6] = header->ancount >> 8; output[7] = header->ancount & 0xFF; output[8] = header->nscount >> 8; output[9] = header->nscount & 0xFF; output[10] = header->arcount >> 8; output[11] = header->arcount & 0xFF; memcpy(&output[12],header->payload,length); } /** Send requests we have previously built down the UDP socket */ int DNSRequest::SendRequests(const DNSHeader *header, const int length, QueryType qt) { ServerInstance->Logs->Log("RESOLVER", DEBUG,"DNSRequest::SendRequests"); unsigned char payload[sizeof(DNSHeader)]; this->rr_class = 1; this->type = qt; DNS::EmptyHeader(payload,header,length); if (ServerInstance->SE->SendTo(dnsobj, payload, length + 12, 0, &(dnsobj->myserver.sa), sa_size(dnsobj->myserver)) != length+12) return -1; ServerInstance->Logs->Log("RESOLVER",DEBUG,"Sent OK"); return 0; } /** Add a query with a predefined header, and allocate an ID for it. */ DNSRequest* DNS::AddQuery(DNSHeader *header, int &id, const char* original) { /* Is the DNS connection down? */ if (this->GetFd() == -1) return NULL; /* Create an id */ do { id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID); } while (requests[id]); DNSRequest* req = new DNSRequest(this, id, original); header->id[0] = req->id[0] = id >> 8; header->id[1] = req->id[1] = id & 0xFF; header->flags1 = FLAGS_MASK_RD; header->flags2 = 0; header->qdcount = 1; header->ancount = 0; header->nscount = 0; header->arcount = 0; /* At this point we already know the id doesnt exist, * so there needs to be no second check for the ::end() */ requests[id] = req; /* According to the C++ spec, new never returns NULL. */ return req; } int DNS::ClearCache() { /* This ensures the buckets are reset to sane levels */ int rv = this->cache->size(); delete this->cache; this->cache = new dnscache(); return rv; } int DNS::PruneCache() { int n = 0; dnscache* newcache = new dnscache(); for (dnscache::iterator i = this->cache->begin(); i != this->cache->end(); i++) /* Dont include expired items (theres no point) */ if (i->second.CalcTTLRemaining()) newcache->insert(*i); else n++; delete this->cache; this->cache = newcache; return n; } void DNS::Rehash() { if (this->GetFd() > -1) { ServerInstance->SE->DelFd(this); ServerInstance->SE->Shutdown(this, 2); ServerInstance->SE->Close(this); this->SetFd(-1); /* Rehash the cache */ this->PruneCache(); } else { /* Create initial dns cache */ this->cache = new dnscache(); } irc::sockets::aptosa(ServerInstance->Config->DNSServer, DNS::QUERY_PORT, myserver); /* Initialize mastersocket */ int s = socket(myserver.sa.sa_family, SOCK_DGRAM, 0); this->SetFd(s); /* Have we got a socket and is it nonblocking? */ if (this->GetFd() != -1) { ServerInstance->SE->SetReuse(s); ServerInstance->SE->NonBlocking(s); irc::sockets::sockaddrs bindto; memset(&bindto, 0, sizeof(bindto)); bindto.sa.sa_family = myserver.sa.sa_family; if (ServerInstance->SE->Bind(this->GetFd(), bindto) < 0) { /* Failed to bind */ ServerInstance->Logs->Log("RESOLVER",SPARSE,"Error binding dns socket - hostnames will NOT resolve"); ServerInstance->SE->Shutdown(this, 2); ServerInstance->SE->Close(this); this->SetFd(-1); } else if (!ServerInstance->SE->AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE)) { ServerInstance->Logs->Log("RESOLVER",SPARSE,"Internal error starting DNS - hostnames will NOT resolve."); ServerInstance->SE->Shutdown(this, 2); ServerInstance->SE->Close(this); this->SetFd(-1); } } else { ServerInstance->Logs->Log("RESOLVER",SPARSE,"Error creating DNS socket - hostnames will NOT resolve"); } } /** Initialise the DNS UDP socket so that we can send requests */ DNS::DNS() { ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::DNS"); /* Clear the Resolver class table */ memset(Classes,0,sizeof(Classes)); /* Clear the requests class table */ memset(requests,0,sizeof(requests)); /* Set the id of the next request to 0 */ currid = 0; /* DNS::Rehash() sets this to a valid ptr */ this->cache = NULL; /* Again, DNS::Rehash() sets this to a * valid value */ this->SetFd(-1); /* Actually read the settings */ this->Rehash(); this->PruneTimer = new CacheTimer(this); ServerInstance->Timers->AddTimer(this->PruneTimer); } /** Build a payload to be placed after the header, based upon input data, a resource type, a class and a pointer to a buffer */ int DNS::MakePayload(const char * const name, const QueryType rr, const unsigned short rr_class, unsigned char * const payload) { short payloadpos = 0; const char* tempchr, *tempchr2 = name; unsigned short length; /* split name up into labels, create query */ while ((tempchr = strchr(tempchr2,'.')) != NULL) { length = tempchr - tempchr2; if (payloadpos + length + 1 > 507) return -1; payload[payloadpos++] = length; memcpy(&payload[payloadpos],tempchr2,length); payloadpos += length; tempchr2 = &tempchr[1]; } length = strlen(tempchr2); if (length) { if (payloadpos + length + 2 > 507) return -1; payload[payloadpos++] = length; memcpy(&payload[payloadpos],tempchr2,length); payloadpos += length; payload[payloadpos++] = 0; } if (payloadpos > 508) return -1; length = htons(rr); memcpy(&payload[payloadpos],&length,2); length = htons(rr_class); memcpy(&payload[payloadpos + 2],&length,2); return payloadpos + 4; } /** Start lookup of an hostname to an IP address */ int DNS::GetIP(const char *name) { DNSHeader h; int id; int length; if ((length = this->MakePayload(name, DNS_QUERY_A, 1, (unsigned char*)&h.payload)) == -1) return -1; DNSRequest* req = this->AddQuery(&h, id, name); if ((!req) || (req->SendRequests(&h, length, DNS_QUERY_A) == -1)) return -1; return id; } /** Start lookup of an hostname to an IPv6 address */ int DNS::GetIP6(const char *name) { DNSHeader h; int id; int length; if ((length = this->MakePayload(name, DNS_QUERY_AAAA, 1, (unsigned char*)&h.payload)) == -1) return -1; DNSRequest* req = this->AddQuery(&h, id, name); if ((!req) || (req->SendRequests(&h, length, DNS_QUERY_AAAA) == -1)) return -1; return id; } /** Start lookup of a cname to another name */ int DNS::GetCName(const char *alias) { DNSHeader h; int id; int length; if ((length = this->MakePayload(alias, DNS_QUERY_CNAME, 1, (unsigned char*)&h.payload)) == -1) return -1; DNSRequest* req = this->AddQuery(&h, id, alias); if ((!req) || (req->SendRequests(&h, length, DNS_QUERY_CNAME) == -1)) return -1; return id; } /** Start lookup of an IP address to a hostname */ int DNS::GetNameForce(const char *ip, ForceProtocol fp) { char query[128]; DNSHeader h; int id; int length; if (fp == PROTOCOL_IPV6) { in6_addr i; if (inet_pton(AF_INET6, ip, &i) > 0) { DNS::MakeIP6Int(query, &i); } else { ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce IPv6 bad format for '%s'", ip); /* Invalid IP address */ return -1; } } else { in_addr i; if (inet_aton(ip, &i)) { unsigned char* c = (unsigned char*)&i.s_addr; sprintf(query,"%d.%d.%d.%d.in-addr.arpa",c[3],c[2],c[1],c[0]); } else { ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce IPv4 bad format for '%s'", ip); /* Invalid IP address */ return -1; } } length = this->MakePayload(query, DNS_QUERY_PTR, 1, (unsigned char*)&h.payload); if (length == -1) { ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce can't query '%s' using '%s' because it's too long", ip, query); return -1; } DNSRequest* req = this->AddQuery(&h, id, ip); if (!req) { ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce can't add query (resolver down?)"); return -1; } if (req->SendRequests(&h, length, DNS_QUERY_PTR) == -1) { ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce can't send (firewall?)"); return -1; } return id; } /** Build an ipv6 reverse domain from an in6_addr */ void DNS::MakeIP6Int(char* query, const in6_addr *ip) { const char* hex = "0123456789abcdef"; for (int index = 31; index >= 0; index--) /* for() loop steps twice per byte */ { if (index % 2) /* low nibble */ *query++ = hex[ip->s6_addr[index / 2] & 0x0F]; else /* high nibble */ *query++ = hex[(ip->s6_addr[index / 2] & 0xF0) >> 4]; *query++ = '.'; /* Seperator */ } strcpy(query,"ip6.arpa"); /* Suffix the string */ } /** Return the next id which is ready, and the result attached to it */ DNSResult DNS::GetResult() { /* Fetch dns query response and decide where it belongs */ DNSHeader header; DNSRequest *req; unsigned char buffer[sizeof(DNSHeader)]; irc::sockets::sockaddrs from; memset(&from, 0, sizeof(from)); socklen_t x = sizeof(from); int length = ServerInstance->SE->RecvFrom(this, (char*)buffer, sizeof(DNSHeader), 0, &from.sa, &x); /* Did we get the whole header? */ if (length < 12) { ServerInstance->Logs->Log("RESOLVER",DEBUG,"GetResult didn't get a full packet (len=%d)", length); /* Nope - something screwed up. */ return DNSResult(-1,"",0,""); } /* Check wether the reply came from a different DNS * server to the one we sent it to, or the source-port * is not 53. * A user could in theory still spoof dns packets anyway * but this is less trivial than just sending garbage * to the server, which is possible without this check. * * -- Thanks jilles for pointing this one out. */ if (from != myserver) { ServerInstance->Logs->Log("RESOLVER",DEBUG,"Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'", from.str().c_str(), myserver.str().c_str()); return DNSResult(-1,"",0,""); } /* Put the read header info into a header class */ DNS::FillHeader(&header,buffer,length - 12); /* Get the id of this request. * Its a 16 bit value stored in two char's, * so we use logic shifts to create the value. */ unsigned long this_id = header.id[1] + (header.id[0] << 8); /* Do we have a pending request matching this id? */ if (!requests[this_id]) { /* Somehow we got a DNS response for a request we never made... */ ServerInstance->Logs->Log("RESOLVER",DEBUG,"Hmm, got a result that we didn't ask for (id=%lx). Ignoring.", this_id); return DNSResult(-1,"",0,""); } else { /* Remove the query from the list of pending queries */ req = requests[this_id]; requests[this_id] = NULL; } /* Inform the DNSRequest class that it has a result to be read. * When its finished it will return a DNSInfo which is a pair of * unsigned char* resource record data, and an error message. */ DNSInfo data = req->ResultIsReady(header, length); std::string resultstr; /* Check if we got a result, if we didnt, its an error */ if (data.first == NULL) { /* An error. * Mask the ID with the value of ERROR_MASK, so that * the dns_deal_with_classes() function knows that its * an error response and needs to be treated uniquely. * Put the error message in the second field. */ std::string ro = req->orig; delete req; return DNSResult(this_id | ERROR_MASK, data.second, 0, ro); } else { unsigned long ttl = req->ttl; char formatted[128]; /* Forward lookups come back as binary data. We must format them into ascii */ switch (req->type) { case DNS_QUERY_A: snprintf(formatted,16,"%u.%u.%u.%u",data.first[0],data.first[1],data.first[2],data.first[3]); resultstr = formatted; break; case DNS_QUERY_AAAA: { inet_ntop(AF_INET6, data.first, formatted, sizeof(formatted)); char* c = strstr(formatted,":0:"); if (c != NULL) { memmove(c+1,c+2,strlen(c+2) + 1); c += 2; while (memcmp(c,"0:",2) == 0) memmove(c,c+2,strlen(c+2) + 1); if (memcmp(c,"0",2) == 0) *c = 0; if (memcmp(formatted,"0::",3) == 0) memmove(formatted,formatted + 1, strlen(formatted + 1) + 1); } resultstr = formatted; /* Special case. Sending ::1 around between servers * and to clients is dangerous, because the : on the * start makes the client or server interpret the IP * as the last parameter on the line with a value ":1". */ if (*formatted == ':') resultstr.insert(0, "0"); } break; case DNS_QUERY_CNAME: /* Identical handling to PTR */ case DNS_QUERY_PTR: /* Reverse lookups just come back as char* */ resultstr = std::string((const char*)data.first); break; default: break; } /* Build the reply with the id and hostname/ip in it */ std::string ro = req->orig; delete req; return DNSResult(this_id,resultstr,ttl,ro); } } /** A result is ready, process it */ DNSInfo DNSRequest::ResultIsReady(DNSHeader &header, unsigned length) { unsigned i = 0, o; int q = 0; int curanswer; ResourceRecord rr; unsigned short ptr; /* This is just to keep _FORTIFY_SOURCE happy */ rr.type = DNS_QUERY_NONE; rr.rdlength = 0; rr.ttl = 1; /* GCC is a whiney bastard -- see the XXX below. */ rr.rr_class = 0; /* Same for VC++ */ if (!(header.flags1 & FLAGS_MASK_QR)) return std::make_pair((unsigned char*)NULL,"Not a query result"); if (header.flags1 & FLAGS_MASK_OPCODE) return std::make_pair((unsigned char*)NULL,"Unexpected value in DNS reply packet"); if (header.flags2 & FLAGS_MASK_RCODE) return std::make_pair((unsigned char*)NULL,"Domain name not found"); if (header.ancount < 1) return std::make_pair((unsigned char*)NULL,"No resource records returned"); /* Subtract the length of the header from the length of the packet */ length -= 12; while ((unsigned int)q < header.qdcount && i < length) { if (header.payload[i] > 63) { i += 6; q++; } else { if (header.payload[i] == 0) { q++; i += 5; } else i += header.payload[i] + 1; } } curanswer = 0; while ((unsigned)curanswer < header.ancount) { q = 0; while (q == 0 && i < length) { if (header.payload[i] > 63) { i += 2; q = 1; } else { if (header.payload[i] == 0) { i++; q = 1; } else i += header.payload[i] + 1; /* skip length and label */ } } if (static_cast<int>(length - i) < 10) return std::make_pair((unsigned char*)NULL,"Incorrectly sized DNS reply"); /* XXX: We actually initialise 'rr' here including its ttl field */ DNS::FillResourceRecord(&rr,&header.payload[i]); i += 10; ServerInstance->Logs->Log("RESOLVER",DEBUG,"Resolver: rr.type is %d and this.type is %d rr.class %d this.class %d", rr.type, this->type, rr.rr_class, this->rr_class); if (rr.type != this->type) { curanswer++; i += rr.rdlength; continue; } if (rr.rr_class != this->rr_class) { curanswer++; i += rr.rdlength; continue; } break; } if ((unsigned int)curanswer == header.ancount) return std::make_pair((unsigned char*)NULL,"No A, AAAA or PTR type answers (" + ConvToStr(header.ancount) + " answers)"); if (i + rr.rdlength > (unsigned int)length) return std::make_pair((unsigned char*)NULL,"Resource record larger than stated"); if (rr.rdlength > 1023) return std::make_pair((unsigned char*)NULL,"Resource record too large"); this->ttl = rr.ttl; switch (rr.type) { /* * CNAME and PTR are compressed. We need to decompress them. */ case DNS_QUERY_CNAME: case DNS_QUERY_PTR: o = 0; q = 0; while (q == 0 && i < length && o + 256 < 1023) { /* DN label found (byte over 63) */ if (header.payload[i] > 63) { memcpy(&ptr,&header.payload[i],2); i = ntohs(ptr); /* check that highest two bits are set. if not, we've been had */ if (!(i & DN_COMP_BITMASK)) return std::make_pair((unsigned char *) NULL, "DN label decompression header is bogus"); /* mask away the two highest bits. */ i &= ~DN_COMP_BITMASK; /* and decrease length by 12 bytes. */ i =- 12; } else { if (header.payload[i] == 0) { q = 1; } else { res[o] = 0; if (o != 0) res[o++] = '.'; if (o + header.payload[i] > sizeof(DNSHeader)) return std::make_pair((unsigned char *) NULL, "DN label decompression is impossible -- malformed/hostile packet?"); memcpy(&res[o], &header.payload[i + 1], header.payload[i]); o += header.payload[i]; i += header.payload[i] + 1; } } } res[o] = 0; break; case DNS_QUERY_AAAA: if (rr.rdlength != sizeof(struct in6_addr)) return std::make_pair((unsigned char *) NULL, "rr.rdlength is larger than 16 bytes for an ipv6 entry -- malformed/hostile packet?"); memcpy(res,&header.payload[i],rr.rdlength); res[rr.rdlength] = 0; break; case DNS_QUERY_A: if (rr.rdlength != sizeof(struct in_addr)) return std::make_pair((unsigned char *) NULL, "rr.rdlength is larger than 4 bytes for an ipv4 entry -- malformed/hostile packet?"); memcpy(res,&header.payload[i],rr.rdlength); res[rr.rdlength] = 0; break; default: return std::make_pair((unsigned char *) NULL, "don't know how to handle undefined type (" + ConvToStr(rr.type) + ") -- rejecting"); break; } return std::make_pair(res,"No error"); } /** Close the master socket */ DNS::~DNS() { ServerInstance->SE->Shutdown(this, 2); ServerInstance->SE->Close(this); ServerInstance->Timers->DelTimer(this->PruneTimer); if (cache) delete cache; } CachedQuery* DNS::GetCache(const std::string &source) { dnscache::iterator x = cache->find(source.c_str()); if (x != cache->end()) return &(x->second); else return NULL; } void DNS::DelCache(const std::string &source) { cache->erase(source.c_str()); } void Resolver::TriggerCachedResult() { if (CQ) OnLookupComplete(CQ->data, time_left, true); } /** High level abstraction of dns used by application at large */ Resolver::Resolver(const std::string &source, QueryType qt, bool &cached, Module* creator) : Creator(creator), input(source), querytype(qt) { ServerInstance->Logs->Log("RESOLVER",DEBUG,"Resolver::Resolver"); cached = false; CQ = ServerInstance->Res->GetCache(source); if (CQ) { time_left = CQ->CalcTTLRemaining(); if (!time_left) { ServerInstance->Res->DelCache(source); } else { cached = true; return; } } switch (querytype) { case DNS_QUERY_A: this->myid = ServerInstance->Res->GetIP(source.c_str()); break; case DNS_QUERY_PTR4: querytype = DNS_QUERY_PTR; this->myid = ServerInstance->Res->GetNameForce(source.c_str(), PROTOCOL_IPV4); break; case DNS_QUERY_PTR6: querytype = DNS_QUERY_PTR; this->myid = ServerInstance->Res->GetNameForce(source.c_str(), PROTOCOL_IPV6); break; case DNS_QUERY_AAAA: this->myid = ServerInstance->Res->GetIP6(source.c_str()); break; case DNS_QUERY_CNAME: this->myid = ServerInstance->Res->GetCName(source.c_str()); break; default: ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS request with unknown query type %d", querytype); this->myid = -1; break; } if (this->myid == -1) { throw ModuleException("Resolver: Couldn't get an id to make a request"); } else { ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS request id %d", this->myid); } } /** Called when an error occurs */ void Resolver::OnError(ResolverError, const std::string&) { /* Nothing in here */ } /** Destroy a resolver */ Resolver::~Resolver() { /* Nothing here (yet) either */ } /** Get the request id associated with this class */ int Resolver::GetId() { return this->myid; } Module* Resolver::GetCreator() { return this->Creator; } /** Process a socket read event */ void DNS::HandleEvent(EventType, int) { /* Fetch the id and result of the next available packet */ DNSResult res(0,"",0,""); res.id = 0; ServerInstance->Logs->Log("RESOLVER",DEBUG,"Handle DNS event"); res = this->GetResult(); ServerInstance->Logs->Log("RESOLVER",DEBUG,"Result id %d", res.id); /* Is there a usable request id? */ if (res.id != -1) { /* Its an error reply */ if (res.id & ERROR_MASK) { /* Mask off the error bit */ res.id -= ERROR_MASK; /* Marshall the error to the correct class */ if (Classes[res.id]) { if (ServerInstance && ServerInstance->stats) ServerInstance->stats->statsDnsBad++; Classes[res.id]->OnError(RESOLVER_NXDOMAIN, res.result); delete Classes[res.id]; Classes[res.id] = NULL; } return; } else { /* It is a non-error result, marshall the result to the correct class */ if (Classes[res.id]) { if (ServerInstance && ServerInstance->stats) ServerInstance->stats->statsDnsGood++; if (!this->GetCache(res.original.c_str())) this->cache->insert(std::make_pair(res.original.c_str(), CachedQuery(res.result, res.ttl))); Classes[res.id]->OnLookupComplete(res.result, res.ttl, false); delete Classes[res.id]; Classes[res.id] = NULL; } } if (ServerInstance && ServerInstance->stats) ServerInstance->stats->statsDns++; } } /** Add a derived Resolver to the working set */ bool DNS::AddResolverClass(Resolver* r) { ServerInstance->Logs->Log("RESOLVER",DEBUG,"AddResolverClass 0x%08lx", (unsigned long)r); /* Check the pointers validity and the id's validity */ if ((r) && (r->GetId() > -1)) { /* Check the slot isnt already occupied - * This should NEVER happen unless we have * a severely broken DNS server somewhere */ if (!Classes[r->GetId()]) { /* Set up the pointer to the class */ Classes[r->GetId()] = r; return true; } else /* Duplicate id */ return false; } else { /* Pointer or id not valid. * Free the item and return */ if (r) delete r; return false; } } void DNS::CleanResolvers(Module* module) { for (int i = 0; i < MAX_REQUEST_ID; i++) { if (Classes[i]) { if (Classes[i]->GetCreator() == module) { Classes[i]->OnError(RESOLVER_FORCEUNLOAD, "Parent module is unloading"); delete Classes[i]; Classes[i] = NULL; } } } }
./CrossVul/dataset_final_sorted/CWE-399/cpp/bad_3854_0
crossvul-cpp_data_good_5642_0
/* -*- C++ -*- * File: libraw_cxx.cpp * Copyright 2008-2013 LibRaw LLC (info@libraw.org) * Created: Sat Mar 8 , 2008 * * LibRaw C++ interface (implementation) LibRaw is free software; you can redistribute it and/or modify it under the terms of the one of three licenses as you choose: 1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1 (See file LICENSE.LGPL provided in LibRaw distribution archive for details). 2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 (See file LICENSE.CDDL provided in LibRaw distribution archive for details). 3. LibRaw Software License 27032010 (See file LICENSE.LibRaw.pdf provided in LibRaw distribution archive for details). */ #include <math.h> #include <errno.h> #include <float.h> #include <new> #include <exception> #include <sys/types.h> #include <sys/stat.h> #ifndef WIN32 #include <netinet/in.h> #else #include <winsock2.h> #endif #define LIBRAW_LIBRARY_BUILD #include "libraw/libraw.h" #include "internal/defines.h" #ifdef USE_RAWSPEED #include "../RawSpeed/rawspeed_xmldata.cpp" #include <RawSpeed/StdAfx.h> #include <RawSpeed/FileMap.h> #include <RawSpeed/RawParser.h> #include <RawSpeed/RawDecoder.h> #include <RawSpeed/CameraMetaData.h> #include <RawSpeed/ColorFilterArray.h> #endif #ifdef __cplusplus extern "C" { #endif void default_memory_callback(void *,const char *file,const char *where) { fprintf (stderr,"%s: Out of memory in %s\n", file?file:"unknown file", where); } void default_data_callback(void*,const char *file, const int offset) { if(offset < 0) fprintf (stderr,"%s: Unexpected end of file\n", file?file:"unknown file"); else fprintf (stderr,"%s: data corrupted at %d\n",file?file:"unknown file",offset); } const char *libraw_strerror(int e) { enum LibRaw_errors errorcode = (LibRaw_errors)e; switch(errorcode) { case LIBRAW_SUCCESS: return "No error"; case LIBRAW_UNSPECIFIED_ERROR: return "Unspecified error"; case LIBRAW_FILE_UNSUPPORTED: return "Unsupported file format or not RAW file"; case LIBRAW_REQUEST_FOR_NONEXISTENT_IMAGE: return "Request for nonexisting image number"; case LIBRAW_OUT_OF_ORDER_CALL: return "Out of order call of libraw function"; case LIBRAW_NO_THUMBNAIL: return "No thumbnail in file"; case LIBRAW_UNSUPPORTED_THUMBNAIL: return "Unsupported thumbnail format"; case LIBRAW_INPUT_CLOSED: return "No input stream, or input stream closed"; case LIBRAW_UNSUFFICIENT_MEMORY: return "Unsufficient memory"; case LIBRAW_DATA_ERROR: return "Corrupted data or unexpected EOF"; case LIBRAW_IO_ERROR: return "Input/output error"; case LIBRAW_CANCELLED_BY_CALLBACK: return "Cancelled by user callback"; case LIBRAW_BAD_CROP: return "Bad crop box"; default: return "Unknown error code"; } } #ifdef __cplusplus } #endif const double LibRaw_constants::xyz_rgb[3][3] = { { 0.412453, 0.357580, 0.180423 }, { 0.212671, 0.715160, 0.072169 }, { 0.019334, 0.119193, 0.950227 } }; const float LibRaw_constants::d65_white[3] = { 0.950456f, 1.0f, 1.088754f }; #define P1 imgdata.idata #define S imgdata.sizes #define O imgdata.params #define C imgdata.color #define T imgdata.thumbnail #define IO libraw_internal_data.internal_output_params #define ID libraw_internal_data.internal_data #define EXCEPTION_HANDLER(e) do{ \ /* fprintf(stderr,"Exception %d caught\n",e);*/ \ switch(e) \ { \ case LIBRAW_EXCEPTION_ALLOC: \ recycle(); \ return LIBRAW_UNSUFFICIENT_MEMORY; \ case LIBRAW_EXCEPTION_DECODE_RAW: \ case LIBRAW_EXCEPTION_DECODE_JPEG: \ recycle(); \ return LIBRAW_DATA_ERROR; \ case LIBRAW_EXCEPTION_DECODE_JPEG2000: \ recycle(); \ return LIBRAW_DATA_ERROR; \ case LIBRAW_EXCEPTION_IO_EOF: \ case LIBRAW_EXCEPTION_IO_CORRUPT: \ recycle(); \ return LIBRAW_IO_ERROR; \ case LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK:\ recycle(); \ return LIBRAW_CANCELLED_BY_CALLBACK; \ case LIBRAW_EXCEPTION_BAD_CROP: \ recycle(); \ return LIBRAW_BAD_CROP; \ default: \ return LIBRAW_UNSPECIFIED_ERROR; \ } \ }while(0) const char* LibRaw::version() { return LIBRAW_VERSION_STR;} int LibRaw::versionNumber() { return LIBRAW_VERSION; } const char* LibRaw::strerror(int p) { return libraw_strerror(p);} void LibRaw::derror() { if (!libraw_internal_data.unpacker_data.data_error && libraw_internal_data.internal_data.input) { if (libraw_internal_data.internal_data.input->eof()) { if(callbacks.data_cb)(*callbacks.data_cb)(callbacks.datacb_data, libraw_internal_data.internal_data.input->fname(),-1); throw LIBRAW_EXCEPTION_IO_EOF; } else { if(callbacks.data_cb)(*callbacks.data_cb)(callbacks.datacb_data, libraw_internal_data.internal_data.input->fname(), libraw_internal_data.internal_data.input->tell()); throw LIBRAW_EXCEPTION_IO_CORRUPT; } } libraw_internal_data.unpacker_data.data_error++; } void LibRaw::dcraw_clear_mem(libraw_processed_image_t* p) { if(p) ::free(p); } #ifdef USE_RAWSPEED using namespace RawSpeed; class CameraMetaDataLR : public CameraMetaData { public: CameraMetaDataLR() : CameraMetaData() {} CameraMetaDataLR(char *filename) : CameraMetaData(filename){} CameraMetaDataLR(char *data, int sz); }; CameraMetaDataLR::CameraMetaDataLR(char *data, int sz) : CameraMetaData() { ctxt = xmlNewParserCtxt(); if (ctxt == NULL) { ThrowCME("CameraMetaData:Could not initialize context."); } xmlResetLastError(); doc = xmlCtxtReadMemory(ctxt, data,sz, "", NULL, XML_PARSE_DTDVALID); if (doc == NULL) { ThrowCME("CameraMetaData: XML Document could not be parsed successfully. Error was: %s", ctxt->lastError.message); } if (ctxt->valid == 0) { if (ctxt->lastError.code == 0x5e) { // printf("CameraMetaData: Unable to locate DTD, attempting to ignore."); } else { ThrowCME("CameraMetaData: XML file does not validate. DTD Error was: %s", ctxt->lastError.message); } } xmlNodePtr cur; cur = xmlDocGetRootElement(doc); if (xmlStrcmp(cur->name, (const xmlChar *) "Cameras")) { ThrowCME("CameraMetaData: XML document of the wrong type, root node is not cameras."); return; } cur = cur->xmlChildrenNode; while (cur != NULL) { if ((!xmlStrcmp(cur->name, (const xmlChar *)"Camera"))) { Camera *camera = new Camera(doc, cur); addCamera(camera); // Create cameras for aliases. for (uint32 i = 0; i < camera->aliases.size(); i++) { addCamera(new Camera(camera, i)); } } cur = cur->next; } if (doc) xmlFreeDoc(doc); doc = 0; if (ctxt) xmlFreeParserCtxt(ctxt); ctxt = 0; } #define RAWSPEED_DATA_COUNT (sizeof(_rawspeed_data_xml)/sizeof(_rawspeed_data_xml[0])) static CameraMetaDataLR* make_camera_metadata() { int len = 0,i; for(i=0;i<RAWSPEED_DATA_COUNT;i++) if(_rawspeed_data_xml[i]) { len+=strlen(_rawspeed_data_xml[i]); } char *rawspeed_xml = (char*)calloc(len+1,sizeof(_rawspeed_data_xml[0][0])); if(!rawspeed_xml) return NULL; int offt = 0; for(i=0;i<RAWSPEED_DATA_COUNT;i++) if(_rawspeed_data_xml[i]) { int ll = strlen(_rawspeed_data_xml[i]); if(offt+ll>len) break; memmove(rawspeed_xml+offt,_rawspeed_data_xml[i],ll); offt+=ll; } rawspeed_xml[offt]=0; CameraMetaDataLR *ret=NULL; try { ret = new CameraMetaDataLR(rawspeed_xml,offt); } catch (...) { // Mask all exceptions } free(rawspeed_xml); return ret; } #endif #define ZERO(a) memset(&a,0,sizeof(a)) LibRaw:: LibRaw(unsigned int flags) { double aber[4] = {1,1,1,1}; double gamm[6] = { 0.45,4.5,0,0,0,0 }; unsigned greybox[4] = { 0, 0, UINT_MAX, UINT_MAX }; unsigned cropbox[4] = { 0, 0, UINT_MAX, UINT_MAX }; #ifdef DCRAW_VERBOSE verbose = 1; #else verbose = 0; #endif ZERO(imgdata); ZERO(libraw_internal_data); ZERO(callbacks); _rawspeed_camerameta = _rawspeed_decoder = NULL; #ifdef USE_RAWSPEED CameraMetaDataLR *camerameta = make_camera_metadata(); // May be NULL in case of exception in make_camera_metadata() _rawspeed_camerameta = static_cast<void*>(camerameta); #endif callbacks.mem_cb = (flags & LIBRAW_OPIONS_NO_MEMERR_CALLBACK) ? NULL: &default_memory_callback; callbacks.data_cb = (flags & LIBRAW_OPIONS_NO_DATAERR_CALLBACK)? NULL : &default_data_callback; memmove(&imgdata.params.aber,&aber,sizeof(aber)); memmove(&imgdata.params.gamm,&gamm,sizeof(gamm)); memmove(&imgdata.params.greybox,&greybox,sizeof(greybox)); memmove(&imgdata.params.cropbox,&cropbox,sizeof(cropbox)); imgdata.params.bright=1; imgdata.params.use_camera_matrix=-1; imgdata.params.user_flip=-1; imgdata.params.user_black=-1; imgdata.params.user_cblack[0]=imgdata.params.user_cblack[1]=imgdata.params.user_cblack[2]=imgdata.params.user_cblack[3]=-1000001; imgdata.params.user_sat=-1; imgdata.params.user_qual=-1; imgdata.params.output_color=1; imgdata.params.output_bps=8; imgdata.params.use_fuji_rotate=1; imgdata.params.exp_shift = 1.0; imgdata.params.auto_bright_thr = LIBRAW_DEFAULT_AUTO_BRIGHTNESS_THRESHOLD; imgdata.params.adjust_maximum_thr= LIBRAW_DEFAULT_ADJUST_MAXIMUM_THRESHOLD; imgdata.params.use_rawspeed = 1; imgdata.params.green_matching = 0; imgdata.parent_class = this; imgdata.progress_flags = 0; tls = new LibRaw_TLS; tls->init(); } int LibRaw::set_rawspeed_camerafile(char *filename) { #ifdef USE_RAWSPEED try { CameraMetaDataLR *camerameta = new CameraMetaDataLR(filename); if(_rawspeed_camerameta) { CameraMetaDataLR *d = static_cast<CameraMetaDataLR*>(_rawspeed_camerameta); delete d; } _rawspeed_camerameta = static_cast<void*>(camerameta); } catch (...) { //just return error code return -1; } #endif return 0; } LibRaw::~LibRaw() { recycle(); delete tls; #ifdef USE_RAWSPEED if(_rawspeed_camerameta) { CameraMetaDataLR *cmeta = static_cast<CameraMetaDataLR*>(_rawspeed_camerameta); delete cmeta; _rawspeed_camerameta = NULL; } #endif } void* LibRaw:: malloc(size_t t) { void *p = memmgr.malloc(t); if(!p) throw LIBRAW_EXCEPTION_ALLOC; return p; } void* LibRaw:: realloc(void *q,size_t t) { void *p = memmgr.realloc(q,t); if(!p) throw LIBRAW_EXCEPTION_ALLOC; return p; } void* LibRaw:: calloc(size_t n,size_t t) { void *p = memmgr.calloc(n,t); if(!p) throw LIBRAW_EXCEPTION_ALLOC; return p; } void LibRaw:: free(void *p) { memmgr.free(p); } void LibRaw:: recycle_datastream() { if(libraw_internal_data.internal_data.input && libraw_internal_data.internal_data.input_internal) { delete libraw_internal_data.internal_data.input; libraw_internal_data.internal_data.input = NULL; } libraw_internal_data.internal_data.input_internal = 0; } void LibRaw:: recycle() { recycle_datastream(); #define FREE(a) do { if(a) { free(a); a = NULL;} }while(0) FREE(imgdata.image); FREE(imgdata.thumbnail.thumb); FREE(libraw_internal_data.internal_data.meta_data); FREE(libraw_internal_data.output_data.histogram); FREE(libraw_internal_data.output_data.oprof); FREE(imgdata.color.profile); FREE(imgdata.rawdata.ph1_black); FREE(imgdata.rawdata.raw_alloc); #undef FREE ZERO(imgdata.rawdata); ZERO(imgdata.sizes); ZERO(imgdata.color); ZERO(libraw_internal_data); #ifdef USE_RAWSPEED if(_rawspeed_decoder) { RawDecoder *d = static_cast<RawDecoder*>(_rawspeed_decoder); delete d; } _rawspeed_decoder = 0; #endif memmgr.cleanup(); imgdata.thumbnail.tformat = LIBRAW_THUMBNAIL_UNKNOWN; imgdata.progress_flags = 0; tls->init(); } const char * LibRaw::unpack_function_name() { libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); return decoder_info.decoder_name; } int LibRaw::get_decoder_info(libraw_decoder_info_t* d_info) { if(!d_info) return LIBRAW_UNSPECIFIED_ERROR; if(!load_raw) return LIBRAW_OUT_OF_ORDER_CALL; d_info->decoder_flags = LIBRAW_DECODER_NOTSET; int rawdata = (imgdata.idata.filters || P1.colors == 1); // dcraw.c names order if (load_raw == &LibRaw::canon_600_load_raw) { d_info->decoder_name = "canon_600_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; // WB set within decoder, no need to load raw } else if (load_raw == &LibRaw::canon_load_raw) { d_info->decoder_name = "canon_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::lossless_jpeg_load_raw) { // Check rbayer d_info->decoder_name = "lossless_jpeg_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD | LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::canon_sraw_load_raw) { d_info->decoder_name = "canon_sraw_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY | LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::lossless_dng_load_raw) { // Check rbayer d_info->decoder_name = "lossless_dng_load_raw()"; d_info->decoder_flags = rawdata? LIBRAW_DECODER_FLATFIELD : LIBRAW_DECODER_LEGACY ; d_info->decoder_flags |= LIBRAW_DECODER_HASCURVE; d_info->decoder_flags |= LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::packed_dng_load_raw) { // Check rbayer d_info->decoder_name = "packed_dng_load_raw()"; d_info->decoder_flags = rawdata ? LIBRAW_DECODER_FLATFIELD : LIBRAW_DECODER_LEGACY; d_info->decoder_flags |= LIBRAW_DECODER_HASCURVE; d_info->decoder_flags |= LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::pentax_load_raw ) { d_info->decoder_name = "pentax_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD | LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::nikon_load_raw) { // Check rbayer d_info->decoder_name = "nikon_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD | LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::rollei_load_raw ) { // UNTESTED d_info->decoder_name = "rollei_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::phase_one_load_raw ) { d_info->decoder_name = "phase_one_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::phase_one_load_raw_c ) { d_info->decoder_name = "phase_one_load_raw_c()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::hasselblad_load_raw ) { d_info->decoder_name = "hasselblad_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::leaf_hdr_load_raw ) { d_info->decoder_name = "leaf_hdr_load_raw()"; d_info->decoder_flags = imgdata.idata.filters? LIBRAW_DECODER_FLATFIELD:LIBRAW_DECODER_LEGACY; } else if (load_raw == &LibRaw::unpacked_load_raw ) { d_info->decoder_name = "unpacked_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD | LIBRAW_DECODER_USEBAYER2; } else if (load_raw == &LibRaw::sinar_4shot_load_raw ) { // UNTESTED d_info->decoder_name = "sinar_4shot_load_raw()"; d_info->decoder_flags = (O.shot_select|| O.half_size)?LIBRAW_DECODER_FLATFIELD:LIBRAW_DECODER_LEGACY; } else if (load_raw == &LibRaw::imacon_full_load_raw ) { d_info->decoder_name = "imacon_full_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY; } else if (load_raw == &LibRaw::hasselblad_full_load_raw ) { d_info->decoder_name = "hasselblad_full_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY; } else if (load_raw == &LibRaw::packed_load_raw ) { d_info->decoder_name = "packed_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; d_info->decoder_flags |= LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::nokia_load_raw ) { // UNTESTED d_info->decoder_name = "nokia_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::panasonic_load_raw ) { d_info->decoder_name = "panasonic_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD | LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::olympus_load_raw ) { d_info->decoder_name = "olympus_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD | LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::minolta_rd175_load_raw ) { // UNTESTED d_info->decoder_name = "minolta_rd175_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::quicktake_100_load_raw ) { // UNTESTED d_info->decoder_name = "quicktake_100_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::kodak_radc_load_raw ) { d_info->decoder_name = "kodak_radc_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::kodak_jpeg_load_raw ) { // UNTESTED + RBAYER d_info->decoder_name = "kodak_jpeg_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::lossy_dng_load_raw) { // Check rbayer d_info->decoder_name = "lossy_dng_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY | LIBRAW_DECODER_TRYRAWSPEED; d_info->decoder_flags |= LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::kodak_dc120_load_raw ) { d_info->decoder_name = "kodak_dc120_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::eight_bit_load_raw ) { d_info->decoder_name = "eight_bit_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; d_info->decoder_flags |= LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::kodak_yrgb_load_raw ) { d_info->decoder_name = "kodak_yrgb_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY; d_info->decoder_flags |= LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::kodak_262_load_raw ) { d_info->decoder_name = "kodak_262_load_raw()"; // UNTESTED! d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; d_info->decoder_flags |= LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::kodak_65000_load_raw ) { d_info->decoder_name = "kodak_65000_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; d_info->decoder_flags |= LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::kodak_ycbcr_load_raw ) { // UNTESTED d_info->decoder_name = "kodak_ycbcr_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY; d_info->decoder_flags |= LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::kodak_rgb_load_raw ) { // UNTESTED d_info->decoder_name = "kodak_rgb_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY; } else if (load_raw == &LibRaw::sony_load_raw ) { d_info->decoder_name = "sony_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::sony_arw_load_raw ) { d_info->decoder_name = "sony_arw_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; #ifndef NOSONY_RAWSPEED d_info->decoder_flags |= LIBRAW_DECODER_TRYRAWSPEED; #endif } else if (load_raw == &LibRaw::sony_arw2_load_raw ) { d_info->decoder_name = "sony_arw2_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; d_info->decoder_flags |= LIBRAW_DECODER_HASCURVE; #ifndef NOSONY_RAWSPEED d_info->decoder_flags |= LIBRAW_DECODER_TRYRAWSPEED; #endif d_info->decoder_flags |= LIBRAW_DECODER_ITSASONY; } else if (load_raw == &LibRaw::smal_v6_load_raw ) { // UNTESTED d_info->decoder_name = "smal_v6_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::smal_v9_load_raw ) { // UNTESTED d_info->decoder_name = "smal_v9_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::redcine_load_raw) { d_info->decoder_name = "redcine_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; d_info->decoder_flags |= LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::foveon_sd_load_raw ) { d_info->decoder_name = "foveon_sd_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY; } else if (load_raw == &LibRaw::foveon_dp_load_raw ) { d_info->decoder_name = "foveon_dp_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY; } else { d_info->decoder_name = "Unknown unpack function"; d_info->decoder_flags = LIBRAW_DECODER_NOTSET; } return LIBRAW_SUCCESS; } int LibRaw::adjust_maximum() { ushort real_max; float auto_threshold; if(O.adjust_maximum_thr < 0.00001) return LIBRAW_SUCCESS; else if (O.adjust_maximum_thr > 0.99999) auto_threshold = LIBRAW_DEFAULT_ADJUST_MAXIMUM_THRESHOLD; else auto_threshold = O.adjust_maximum_thr; real_max = C.data_maximum; if (real_max > 0 && real_max < C.maximum && real_max > C.maximum* auto_threshold) { C.maximum = real_max; } return LIBRAW_SUCCESS; } void LibRaw:: merror (void *ptr, const char *where) { if (ptr) return; if(callbacks.mem_cb)(*callbacks.mem_cb)(callbacks.memcb_data, libraw_internal_data.internal_data.input ?libraw_internal_data.internal_data.input->fname() :NULL, where); throw LIBRAW_EXCEPTION_ALLOC; } int LibRaw::open_file(const char *fname, INT64 max_buf_size) { #ifndef WIN32 struct stat st; if(stat(fname,&st)) return LIBRAW_IO_ERROR; int big = (st.st_size > max_buf_size)?1:0; #else struct _stati64 st; if(_stati64(fname,&st)) return LIBRAW_IO_ERROR; int big = (st.st_size > max_buf_size)?1:0; #endif LibRaw_abstract_datastream *stream; try { if(big) stream = new LibRaw_bigfile_datastream(fname); else stream = new LibRaw_file_datastream(fname); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if(!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input_internal = 0; // preserve from deletion on error int ret = open_datastream(stream); if (ret == LIBRAW_SUCCESS) { ID.input_internal =1 ; // flag to delete datastream on recycle } else { delete stream; ID.input_internal = 0; } return ret; } #ifdef WIN32 int LibRaw::open_file(const wchar_t *fname, INT64 max_buf_size) { struct _stati64 st; if(_wstati64(fname,&st)) return LIBRAW_IO_ERROR; int big = (st.st_size > max_buf_size)?1:0; LibRaw_abstract_datastream *stream; try { if(big) stream = new LibRaw_bigfile_datastream(fname); else stream = new LibRaw_file_datastream(fname); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if(!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input_internal = 0; // preserve from deletion on error int ret = open_datastream(stream); if (ret == LIBRAW_SUCCESS) { ID.input_internal =1 ; // flag to delete datastream on recycle } else { delete stream; ID.input_internal = 0; } return ret; } #endif int LibRaw::open_buffer(void *buffer, size_t size) { // this stream will close on recycle() if(!buffer || buffer==(void*)-1) return LIBRAW_IO_ERROR; LibRaw_buffer_datastream *stream; try { stream = new LibRaw_buffer_datastream(buffer,size); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if(!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input_internal = 0; // preserve from deletion on error int ret = open_datastream(stream); if (ret == LIBRAW_SUCCESS) { ID.input_internal =1 ; // flag to delete datastream on recycle } else { delete stream; ID.input_internal = 0; } return ret; } void LibRaw::hasselblad_full_load_raw() { int row, col; for (row=0; row < S.height; row++) for (col=0; col < S.width; col++) { read_shorts (&imgdata.image[row*S.width+col][2], 1); // B read_shorts (&imgdata.image[row*S.width+col][1], 1); // G read_shorts (&imgdata.image[row*S.width+col][0], 1); // R } } int LibRaw::open_datastream(LibRaw_abstract_datastream *stream) { if(!stream) return ENOENT; if(!stream->valid()) return LIBRAW_IO_ERROR; recycle(); try { ID.input = stream; SET_PROC_FLAG(LIBRAW_PROGRESS_OPEN); if (O.use_camera_matrix < 0) O.use_camera_matrix = O.use_camera_wb; identify(); #if 0 size_t bytes = ID.input->size()-libraw_internal_data.unpacker_data.data_offset; float bpp = float(bytes)/float(S.raw_width)/float(S.raw_height); float bpp2 = float(bytes)/float(S.width)/float(S.height); printf("RawSize: %dx%d data offset: %d data size:%d bpp: %g bpp2: %g\n",S.raw_width,S.raw_height,libraw_internal_data.unpacker_data.data_offset,bytes,bpp,bpp2); if(!strcasecmp(imgdata.idata.make,"Hasselblad") && bpp == 6.0f) { load_raw = &LibRaw::hasselblad_full_load_raw; S.width = S.raw_width; S.height = S.raw_height; P1.filters = 0; P1.colors=3; P1.raw_count=1; C.maximum=0xffff; printf("3 channel hassy found\n"); } #endif if(C.profile_length) { if(C.profile) free(C.profile); C.profile = malloc(C.profile_length); merror(C.profile,"LibRaw::open_file()"); ID.input->seek(ID.profile_offset,SEEK_SET); ID.input->read(C.profile,C.profile_length,1); } SET_PROC_FLAG(LIBRAW_PROGRESS_IDENTIFY); } catch ( LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } catch (std::exception ee) { EXCEPTION_HANDLER(LIBRAW_EXCEPTION_IO_CORRUPT); } if(P1.raw_count < 1) return LIBRAW_FILE_UNSUPPORTED; write_fun = &LibRaw::write_ppm_tiff; if (load_raw == &LibRaw::kodak_ycbcr_load_raw) { S.height += S.height & 1; S.width += S.width & 1; } libraw_decoder_info_t dinfo; get_decoder_info(&dinfo); if(dinfo.decoder_flags & LIBRAW_DECODER_LEGACY) { // Adjust sizes according to image buffer size S.raw_width = S.width; S.left_margin = 0; S.raw_height = S.height; S.top_margin = 0; } IO.shrink = P1.filters && (O.half_size || ((O.threshold || O.aber[0] != 1 || O.aber[2] != 1) )); S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; if(imgdata.idata.filters == 303979333U) { //printf("BL=%d [%d,%d,%d,%d]\n",C.black,C.cblack[0],C.cblack[1],C.cblack[2],C.cblack[3]); C.black = C.cblack[0]; C.cblack[0]=C.cblack[1]=C.cblack[2]=C.cblack[3]=0; imgdata.idata.filters = 2; } // X20 if(imgdata.idata.filters == 0x5bb8445b) { C.black = 257; C.cblack[0]=C.cblack[1]=C.cblack[2]=C.cblack[3]=0; imgdata.idata.filters = 2; S.width = 4030; S.height = 3010; S.top_margin = 2; S.left_margin = 2; } // X100S if(imgdata.idata.filters == 0x5145bb84) { C.black = 1024; C.cblack[0]=C.cblack[1]=C.cblack[2]=C.cblack[3]=0; S.left_margin = 2; S.top_margin = 1; S.width = 4934; S.height = 3290; imgdata.idata.filters = 2; } // Save color,sizes and internal data into raw_image fields memmove(&imgdata.rawdata.color,&imgdata.color,sizeof(imgdata.color)); memmove(&imgdata.rawdata.sizes,&imgdata.sizes,sizeof(imgdata.sizes)); memmove(&imgdata.rawdata.iparams,&imgdata.idata,sizeof(imgdata.idata)); memmove(&imgdata.rawdata.ioparams,&libraw_internal_data.internal_output_params,sizeof(libraw_internal_data.internal_output_params)); SET_PROC_FLAG(LIBRAW_PROGRESS_SIZE_ADJUST); return LIBRAW_SUCCESS; } #ifdef USE_RAWSPEED void LibRaw::fix_after_rawspeed(int bl) { if (load_raw == &LibRaw::lossy_dng_load_raw) C.maximum = 0xffff; else if (load_raw == &LibRaw::sony_load_raw) C.maximum = 0x3ff0; else if ( (load_raw == &LibRaw::sony_arw2_load_raw || (load_raw == &LibRaw::packed_load_raw && !strcasecmp(imgdata.idata.make,"Sony"))) && bl >= (C.black+C.cblack[0])*2 ) { C.maximum *=4; C.black *=4; for(int c=0; c< 4; c++) C.cblack[c]*=4; } } #else void LibRaw::fix_after_rawspeed(int) { } #endif int LibRaw::unpack(void) { CHECK_ORDER_HIGH(LIBRAW_PROGRESS_LOAD_RAW); CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); try { if(!libraw_internal_data.internal_data.input) return LIBRAW_INPUT_CLOSED; RUN_CALLBACK(LIBRAW_PROGRESS_LOAD_RAW,0,2); if (O.shot_select >= P1.raw_count) return LIBRAW_REQUEST_FOR_NONEXISTENT_IMAGE; if(!load_raw) return LIBRAW_UNSPECIFIED_ERROR; if (O.use_camera_matrix && C.cmatrix[0][0] > 0.25) { memcpy (C.rgb_cam, C.cmatrix, sizeof (C.cmatrix)); IO.raw_color = 0; } // already allocated ? if(imgdata.image) { free(imgdata.image); imgdata.image = 0; } if(imgdata.rawdata.raw_alloc) { free(imgdata.rawdata.raw_alloc); imgdata.rawdata.raw_alloc = 0; } if (libraw_internal_data.unpacker_data.meta_length) { libraw_internal_data.internal_data.meta_data = (char *) malloc (libraw_internal_data.unpacker_data.meta_length); merror (libraw_internal_data.internal_data.meta_data, "LibRaw::unpack()"); } libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); int save_iwidth = S.iwidth, save_iheight = S.iheight, save_shrink = IO.shrink; int rwidth = S.raw_width, rheight = S.raw_height; if( !IO.fuji_width) { // adjust non-Fuji allocation if(rwidth < S.width + S.left_margin) rwidth = S.width + S.left_margin; if(rheight < S.height + S.top_margin) rheight = S.height + S.top_margin; } S.raw_pitch = S.raw_width*2; imgdata.rawdata.raw_image = 0; imgdata.rawdata.color4_image = 0; imgdata.rawdata.color3_image = 0; #ifdef USE_RAWSPEED // RawSpeed Supported, if(O.use_rawspeed && (decoder_info.decoder_flags & LIBRAW_DECODER_TRYRAWSPEED) && _rawspeed_camerameta) { INT64 spos = ID.input->tell(); try { // printf("Using rawspeed\n"); ID.input->seek(0,SEEK_SET); INT64 _rawspeed_buffer_sz = ID.input->size()+32; void *_rawspeed_buffer = malloc(_rawspeed_buffer_sz); if(!_rawspeed_buffer) throw LIBRAW_EXCEPTION_ALLOC; ID.input->read(_rawspeed_buffer,_rawspeed_buffer_sz,1); FileMap map((uchar8*)_rawspeed_buffer,_rawspeed_buffer_sz); RawParser t(&map); RawDecoder *d = 0; CameraMetaDataLR *meta = static_cast<CameraMetaDataLR*>(_rawspeed_camerameta); d = t.getDecoder(); try { d->checkSupport(meta); } catch (const RawDecoderException& e) { imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_UNSUPPORTED; throw e; } d->decodeRaw(); d->decodeMetaData(meta); RawImage r = d->mRaw; if (r->isCFA) { // Save pointer to decoder _rawspeed_decoder = static_cast<void*>(d); imgdata.rawdata.raw_image = (ushort*) r->getDataUncropped(0,0); S.raw_pitch = r->pitch; fix_after_rawspeed(r->blackLevel); } else if(r->getCpp()==4) { _rawspeed_decoder = static_cast<void*>(d); imgdata.rawdata.color4_image = (ushort(*)[4]) r->getDataUncropped(0,0); S.raw_pitch = r->pitch; C.maximum = r->whitePoint; fix_after_rawspeed(r->blackLevel); } else if(r->getCpp() == 3) { _rawspeed_decoder = static_cast<void*>(d); imgdata.rawdata.color3_image = (ushort(*)[3]) r->getDataUncropped(0,0); S.raw_pitch = r->pitch; C.maximum = r->whitePoint; fix_after_rawspeed(r->blackLevel); } else { delete d; } free(_rawspeed_buffer); imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_PROCESSED; } catch (...) { imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_PROBLEM; // no other actions: if raw_image is not set we'll try usual load_raw call } ID.input->seek(spos,SEEK_SET); } #endif if(!imgdata.rawdata.raw_image && !imgdata.rawdata.color4_image && !imgdata.rawdata.color3_image) // RawSpeed failed! { // Not allocated on RawSpeed call, try call LibRaw if(decoder_info.decoder_flags & LIBRAW_DECODER_FLATFIELD) { imgdata.rawdata.raw_alloc = malloc(rwidth*(rheight+7)*sizeof(imgdata.rawdata.raw_image[0])); imgdata.rawdata.raw_image = (ushort*) imgdata.rawdata.raw_alloc; } else if (decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { // sRAW and Foveon only, so extra buffer size is just 1/4 // Legacy converters does not supports half mode! S.iwidth = S.width; S.iheight= S.height; IO.shrink = 0; S.raw_pitch = S.width*8; // allocate image as temporary buffer, size imgdata.rawdata.raw_alloc = 0; imgdata.image = (ushort (*)[4]) calloc(S.iwidth*S.iheight,sizeof(*imgdata.image)); } ID.input->seek(libraw_internal_data.unpacker_data.data_offset, SEEK_SET); unsigned m_save = C.maximum; if(load_raw == &LibRaw::unpacked_load_raw && !strcasecmp(imgdata.idata.make,"Nikon")) C.maximum=65535; (this->*load_raw)(); if(load_raw == &LibRaw::unpacked_load_raw && !strcasecmp(imgdata.idata.make,"Nikon")) C.maximum = m_save; if (decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { // successfully decoded legacy image, attach image to raw_alloc imgdata.rawdata.raw_alloc = imgdata.image; imgdata.image = 0; } } if(imgdata.rawdata.raw_image) crop_masked_pixels(); // calculate black levels // recover saved if( (decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) && !imgdata.rawdata.color4_image) { imgdata.image = 0; imgdata.rawdata.color4_image = (ushort (*)[4]) imgdata.rawdata.raw_alloc; } // recover image sizes S.iwidth = save_iwidth; S.iheight = save_iheight; IO.shrink = save_shrink; // adjust black to possible maximum unsigned int i = C.cblack[3]; unsigned int c; for(c=0;c<3;c++) if (i > C.cblack[c]) i = C.cblack[c]; for (c=0;c<4;c++) C.cblack[c] -= i; C.black += i; // Save color,sizes and internal data into raw_image fields memmove(&imgdata.rawdata.color,&imgdata.color,sizeof(imgdata.color)); memmove(&imgdata.rawdata.sizes,&imgdata.sizes,sizeof(imgdata.sizes)); memmove(&imgdata.rawdata.iparams,&imgdata.idata,sizeof(imgdata.idata)); memmove(&imgdata.rawdata.ioparams,&libraw_internal_data.internal_output_params,sizeof(libraw_internal_data.internal_output_params)); SET_PROC_FLAG(LIBRAW_PROGRESS_LOAD_RAW); RUN_CALLBACK(LIBRAW_PROGRESS_LOAD_RAW,1,2); return 0; } catch ( LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } catch (std::exception ee) { EXCEPTION_HANDLER(LIBRAW_EXCEPTION_IO_CORRUPT); } } void LibRaw::free_image(void) { if(imgdata.image) { free(imgdata.image); imgdata.image = 0; imgdata.progress_flags = LIBRAW_PROGRESS_START|LIBRAW_PROGRESS_OPEN |LIBRAW_PROGRESS_IDENTIFY|LIBRAW_PROGRESS_SIZE_ADJUST|LIBRAW_PROGRESS_LOAD_RAW; } } void LibRaw::raw2image_start() { // restore color,sizes and internal data into raw_image fields memmove(&imgdata.color,&imgdata.rawdata.color,sizeof(imgdata.color)); memmove(&imgdata.sizes,&imgdata.rawdata.sizes,sizeof(imgdata.sizes)); memmove(&imgdata.idata,&imgdata.rawdata.iparams,sizeof(imgdata.idata)); memmove(&libraw_internal_data.internal_output_params,&imgdata.rawdata.ioparams,sizeof(libraw_internal_data.internal_output_params)); if (O.user_flip >= 0) S.flip = O.user_flip; switch ((S.flip+3600) % 360) { case 270: S.flip = 5; break; case 180: S.flip = 3; break; case 90: S.flip = 6; break; } // adjust for half mode! IO.shrink = P1.filters && (O.half_size || ((O.threshold || O.aber[0] != 1 || O.aber[2] != 1) )); S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; } int LibRaw::is_phaseone_compressed() { return (load_raw == &LibRaw::phase_one_load_raw_c && imgdata.rawdata.ph1_black); } int LibRaw::raw2image(void) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); try { raw2image_start(); if (is_phaseone_compressed()) { phase_one_allocate_tempbuffer(); phase_one_subtract_black((ushort*)imgdata.rawdata.raw_alloc,imgdata.rawdata.raw_image); phase_one_correct(); } // free and re-allocate image bitmap if(imgdata.image) { imgdata.image = (ushort (*)[4]) realloc (imgdata.image,S.iheight*S.iwidth *sizeof (*imgdata.image)); memset(imgdata.image,0,S.iheight*S.iwidth *sizeof (*imgdata.image)); } else imgdata.image = (ushort (*)[4]) calloc (S.iheight*S.iwidth, sizeof (*imgdata.image)); merror (imgdata.image, "raw2image()"); libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); // Move saved bitmap to imgdata.image if(decoder_info.decoder_flags & LIBRAW_DECODER_FLATFIELD) { if (IO.fuji_width) { unsigned r,c; int row,col; for (row=0; row < S.raw_height-S.top_margin*2; row++) { for (col=0; col < IO.fuji_width << !libraw_internal_data.unpacker_data.fuji_layout; col++) { if (libraw_internal_data.unpacker_data.fuji_layout) { r = IO.fuji_width - 1 - col + (row >> 1); c = col + ((row+1) >> 1); } else { r = IO.fuji_width - 1 + row - (col >> 1); c = row + ((col+1) >> 1); } if (r < S.height && c < S.width) imgdata.image[((r)>>IO.shrink)*S.iwidth+((c)>>IO.shrink)][FC(r,c)] = imgdata.rawdata.raw_image[(row+S.top_margin)*S.raw_pitch/2+(col+S.left_margin)]; } } } else { int row,col; for (row=0; row < S.height; row++) for (col=0; col < S.width; col++) imgdata.image[((row) >> IO.shrink)*S.iwidth + ((col) >> IO.shrink)][fcol(row,col)] = imgdata.rawdata.raw_image[(row+S.top_margin)*S.raw_pitch/2+(col+S.left_margin)]; } } else if(decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { if(imgdata.rawdata.color4_image) { if(S.width*8 == S.raw_pitch) memmove(imgdata.image,imgdata.rawdata.color4_image,S.width*S.height*sizeof(*imgdata.image)); else { for(int row = 0; row < S.height; row++) memmove(&imgdata.image[row*S.width], &imgdata.rawdata.color4_image[(row+S.top_margin)*S.raw_pitch/8+S.left_margin], S.width*sizeof(*imgdata.image)); } } else if(imgdata.rawdata.color3_image) { unsigned char *c3image = (unsigned char*) imgdata.rawdata.color3_image; for(int row = 0; row < S.height; row++) { ushort (*srcrow)[3] = (ushort (*)[3]) &c3image[(row+S.top_margin)*S.raw_pitch]; ushort (*dstrow)[4] = (ushort (*)[4]) &imgdata.image[row*S.width]; for(int col=0; col < S.width; col++) { for(int c=0; c< 3; c++) dstrow[col][c] = srcrow[S.left_margin+col][c]; dstrow[col][3]=0; } } } else { // legacy decoder, but no data? throw LIBRAW_EXCEPTION_DECODE_RAW; } } // Free PhaseOne separate copy allocated at function start if (is_phaseone_compressed()) { phase_one_free_tempbuffer(); } // hack - clear later flags! if (load_raw == &CLASS canon_600_load_raw && S.width < S.raw_width) { canon_600_correct(); } imgdata.progress_flags = LIBRAW_PROGRESS_START|LIBRAW_PROGRESS_OPEN | LIBRAW_PROGRESS_RAW2_IMAGE |LIBRAW_PROGRESS_IDENTIFY|LIBRAW_PROGRESS_SIZE_ADJUST|LIBRAW_PROGRESS_LOAD_RAW; return 0; } catch ( LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } void LibRaw::phase_one_allocate_tempbuffer() { // Allocate temp raw_image buffer imgdata.rawdata.raw_image = (ushort*)malloc(S.raw_pitch*S.raw_height); merror (imgdata.rawdata.raw_image, "phase_one_prepare_to_correct()"); } void LibRaw::phase_one_free_tempbuffer() { free(imgdata.rawdata.raw_image); imgdata.rawdata.raw_image = (ushort*) imgdata.rawdata.raw_alloc; } void LibRaw::phase_one_subtract_black(ushort *src, ushort *dest) { // ushort *src = (ushort*)imgdata.rawdata.raw_alloc; if(O.user_black<0 && O.user_cblack[0] <= -1000000 && O.user_cblack[1] <= -1000000 && O.user_cblack[2] <= -1000000 && O.user_cblack[3] <= -1000000) { for(int row = 0; row < S.raw_height; row++) { ushort bl = imgdata.color.phase_one_data.t_black - imgdata.rawdata.ph1_black[row][0]; for(int col=0; col < imgdata.color.phase_one_data.split_col && col < S.raw_width; col++) { int idx = row*S.raw_width + col; ushort val = src[idx]; dest[idx] = val>bl?val-bl:0; } bl = imgdata.color.phase_one_data.t_black - imgdata.rawdata.ph1_black[row][1]; for(int col=imgdata.color.phase_one_data.split_col; col < S.raw_width; col++) { int idx = row*S.raw_width + col; ushort val = src[idx]; dest[idx] = val>bl?val-bl:0; } } } else // black set by user interaction { // Black level in cblack! for(int row = 0; row < S.raw_height; row++) { unsigned short cblk[16]; for(int cc=0; cc<16;cc++) cblk[cc]=C.cblack[fcol(row,cc)]; for(int col = 0; col < S.raw_width; col++) { int idx = row*S.raw_width + col; ushort val = src[idx]; ushort bl = cblk[col&0xf]; dest[idx] = val>bl?val-bl:0; } } } } void LibRaw::copy_fuji_uncropped(unsigned short cblack[4],unsigned short *dmaxp) { int row; #if defined(LIBRAW_USE_OPENMP) #pragma omp parallel for default(shared) #endif for (row=0; row < S.raw_height-S.top_margin*2; row++) { int col; unsigned short ldmax = 0; for (col=0; col < IO.fuji_width << !libraw_internal_data.unpacker_data.fuji_layout; col++) { unsigned r,c; if (libraw_internal_data.unpacker_data.fuji_layout) { r = IO.fuji_width - 1 - col + (row >> 1); c = col + ((row+1) >> 1); } else { r = IO.fuji_width - 1 + row - (col >> 1); c = row + ((col+1) >> 1); } if (r < S.height && c < S.width) { unsigned short val = imgdata.rawdata.raw_image[(row+S.top_margin)*S.raw_pitch/2+(col+S.left_margin)]; int cc = FC(r,c); if(val>cblack[cc]) { val-=cblack[cc]; if(val>ldmax)ldmax = val; } else val = 0; imgdata.image[((r)>>IO.shrink)*S.iwidth+((c)>>IO.shrink)][cc] = val; } } #if defined(LIBRAW_USE_OPENMP) #pragma omp critical(dataupdate) #endif { if(*dmaxp < ldmax) *dmaxp = ldmax; } } } void LibRaw::copy_bayer(unsigned short cblack[4],unsigned short *dmaxp) { // Both cropped and uncropped int row; #if defined(LIBRAW_USE_OPENMP) #pragma omp parallel for default(shared) #endif for (row=0; row < S.height; row++) { int col; unsigned short ldmax = 0; for (col=0; col < S.width; col++) { unsigned short val = imgdata.rawdata.raw_image[(row+S.top_margin)*S.raw_pitch/2+(col+S.left_margin)]; int cc = fcol(row,col); if(val>cblack[cc]) { val-=cblack[cc]; if(val>ldmax)ldmax = val; } else val = 0; imgdata.image[((row) >> IO.shrink)*S.iwidth + ((col) >> IO.shrink)][cc] = val; } #if defined(LIBRAW_USE_OPENMP) #pragma omp critical(dataupdate) #endif { if(*dmaxp < ldmax) *dmaxp = ldmax; } } } int LibRaw::raw2image_ex(int do_subtract_black) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); try { raw2image_start(); // Compressed P1 files with bl data! if (is_phaseone_compressed()) { phase_one_allocate_tempbuffer(); phase_one_subtract_black((ushort*)imgdata.rawdata.raw_alloc,imgdata.rawdata.raw_image); phase_one_correct(); } // process cropping int do_crop = 0; unsigned save_width = S.width; if (~O.cropbox[2] && ~O.cropbox[3] && load_raw != &LibRaw::foveon_sd_load_raw) // Foveon SD to be cropped later { int crop[4],c,filt; for(int c=0;c<4;c++) { crop[c] = O.cropbox[c]; if(crop[c]<0) crop[c]=0; } if(IO.fuji_width && imgdata.idata.filters >= 1000) { crop[0] = (crop[0]/4)*4; crop[1] = (crop[1]/4)*4; if(!libraw_internal_data.unpacker_data.fuji_layout) { crop[2]*=sqrt(2.0); crop[3]/=sqrt(2.0); } crop[2] = (crop[2]/4+1)*4; crop[3] = (crop[3]/4+1)*4; } else if (imgdata.idata.filters == 1) { crop[0] = (crop[0]/16)*16; crop[1] = (crop[1]/16)*16; } else if(imgdata.idata.filters == 2) { crop[0] = (crop[0]/6)*6; crop[1] = (crop[1]/6)*6; } do_crop = 1; crop[2] = MIN (crop[2], (signed) S.width-crop[0]); crop[3] = MIN (crop[3], (signed) S.height-crop[1]); if (crop[2] <= 0 || crop[3] <= 0) throw LIBRAW_EXCEPTION_BAD_CROP; // adjust sizes! S.left_margin+=crop[0]; S.top_margin+=crop[1]; S.width=crop[2]; S.height=crop[3]; S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; if(!IO.fuji_width && imgdata.idata.filters && imgdata.idata.filters >= 1000) { for (filt=c=0; c < 16; c++) filt |= FC((c >> 1)+(crop[1]), (c & 1)+(crop[0])) << c*2; imgdata.idata.filters = filt; } } int alloc_width = S.iwidth; int alloc_height = S.iheight; if(IO.fuji_width && do_crop) { int IO_fw = S.width >> !libraw_internal_data.unpacker_data.fuji_layout; int t_alloc_width = (S.height >> libraw_internal_data.unpacker_data.fuji_layout) + IO_fw; int t_alloc_height = t_alloc_width - 1; alloc_height = (t_alloc_height + IO.shrink) >> IO.shrink; alloc_width = (t_alloc_width + IO.shrink) >> IO.shrink; } int alloc_sz = alloc_width*alloc_height; if(imgdata.image) { imgdata.image = (ushort (*)[4]) realloc (imgdata.image,alloc_sz *sizeof (*imgdata.image)); memset(imgdata.image,0,alloc_sz *sizeof (*imgdata.image)); } else imgdata.image = (ushort (*)[4]) calloc (alloc_sz, sizeof (*imgdata.image)); merror (imgdata.image, "raw2image_ex()"); libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); // Adjust black levels unsigned short cblack[4]={0,0,0,0}; unsigned short dmax = 0; if(do_subtract_black) { adjust_bl(); for(int i=0; i< 4; i++) cblack[i] = (unsigned short)C.cblack[i]; } // Move saved bitmap to imgdata.image if(decoder_info.decoder_flags & LIBRAW_DECODER_FLATFIELD) { if (IO.fuji_width) { if(do_crop) { IO.fuji_width = S.width >> !libraw_internal_data.unpacker_data.fuji_layout; int IO_fwidth = (S.height >> libraw_internal_data.unpacker_data.fuji_layout) + IO.fuji_width; int IO_fheight = IO_fwidth - 1; int row,col; for(row=0;row<S.height;row++) { for(col=0;col<S.width;col++) { int r,c; if (libraw_internal_data.unpacker_data.fuji_layout) { r = IO.fuji_width - 1 - col + (row >> 1); c = col + ((row+1) >> 1); } else { r = IO.fuji_width - 1 + row - (col >> 1); c = row + ((col+1) >> 1); } unsigned short val = imgdata.rawdata.raw_image[(row+S.top_margin)*S.raw_pitch/2 +(col+S.left_margin)]; int cc = FCF(row,col); if(val > cblack[cc]) { val-=cblack[cc]; if(dmax < val) dmax = val; } else val = 0; imgdata.image[((r) >> IO.shrink)*alloc_width + ((c) >> IO.shrink)][cc] = val; } } S.height = IO_fheight; S.width = IO_fwidth; S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; S.raw_height -= 2*S.top_margin; } else { copy_fuji_uncropped(cblack,&dmax); } } // end Fuji else { copy_bayer(cblack,&dmax); } } else if(decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { if(imgdata.rawdata.color4_image) { if(S.raw_pitch != S.width*8) { for(int row = 0; row < S.height; row++) memmove(&imgdata.image[row*S.width], &imgdata.rawdata.color4_image[(row+S.top_margin)*S.raw_pitch/8+S.left_margin], S.width*sizeof(*imgdata.image)); } else { // legacy is always 4channel and not shrinked! memmove(imgdata.image,imgdata.rawdata.color4_image,S.width*S.height*sizeof(*imgdata.image)); } } else if(imgdata.rawdata.color3_image) { unsigned char *c3image = (unsigned char*) imgdata.rawdata.color3_image; for(int row = 0; row < S.height; row++) { ushort (*srcrow)[3] = (ushort (*)[3]) &c3image[(row+S.top_margin)*S.raw_pitch]; ushort (*dstrow)[4] = (ushort (*)[4]) &imgdata.image[row*S.width]; for(int col=0; col < S.width; col++) { for(int c=0; c< 3; c++) dstrow[col][c] = srcrow[S.left_margin+col][c]; dstrow[col][3]=0; } } } else { // legacy decoder, but no data? throw LIBRAW_EXCEPTION_DECODE_RAW; } } // Free PhaseOne separate copy allocated at function start if (is_phaseone_compressed()) { phase_one_free_tempbuffer(); } if (load_raw == &CLASS canon_600_load_raw && S.width < S.raw_width) { canon_600_correct(); } if(do_subtract_black) { C.data_maximum = (int)dmax; C.maximum -= C.black; ZERO(C.cblack); C.black = 0; } // hack - clear later flags! imgdata.progress_flags = LIBRAW_PROGRESS_START|LIBRAW_PROGRESS_OPEN | LIBRAW_PROGRESS_RAW2_IMAGE |LIBRAW_PROGRESS_IDENTIFY|LIBRAW_PROGRESS_SIZE_ADJUST|LIBRAW_PROGRESS_LOAD_RAW; return 0; } catch ( LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } #if 1 libraw_processed_image_t * LibRaw::dcraw_make_mem_thumb(int *errcode) { if(!T.thumb) { if ( !ID.toffset) { if(errcode) *errcode= LIBRAW_NO_THUMBNAIL; } else { if(errcode) *errcode= LIBRAW_OUT_OF_ORDER_CALL; } return NULL; } if (T.tformat == LIBRAW_THUMBNAIL_BITMAP) { libraw_processed_image_t * ret = (libraw_processed_image_t *)::malloc(sizeof(libraw_processed_image_t)+T.tlength); if(!ret) { if(errcode) *errcode= ENOMEM; return NULL; } memset(ret,0,sizeof(libraw_processed_image_t)); ret->type = LIBRAW_IMAGE_BITMAP; ret->height = T.theight; ret->width = T.twidth; ret->colors = 3; ret->bits = 8; ret->data_size = T.tlength; memmove(ret->data,T.thumb,T.tlength); if(errcode) *errcode= 0; return ret; } else if (T.tformat == LIBRAW_THUMBNAIL_JPEG) { ushort exif[5]; int mk_exif = 0; if(strcmp(T.thumb+6,"Exif")) mk_exif = 1; int dsize = T.tlength + mk_exif * (sizeof(exif)+sizeof(tiff_hdr)); libraw_processed_image_t * ret = (libraw_processed_image_t *)::malloc(sizeof(libraw_processed_image_t)+dsize); if(!ret) { if(errcode) *errcode= ENOMEM; return NULL; } memset(ret,0,sizeof(libraw_processed_image_t)); ret->type = LIBRAW_IMAGE_JPEG; ret->data_size = dsize; ret->data[0] = 0xff; ret->data[1] = 0xd8; if(mk_exif) { struct tiff_hdr th; memcpy (exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons (8 + sizeof th); memmove(ret->data+2,exif,sizeof(exif)); tiff_head (&th, 0); memmove(ret->data+(2+sizeof(exif)),&th,sizeof(th)); memmove(ret->data+(2+sizeof(exif)+sizeof(th)),T.thumb+2,T.tlength-2); } else { memmove(ret->data+2,T.thumb+2,T.tlength-2); } if(errcode) *errcode= 0; return ret; } else { if(errcode) *errcode= LIBRAW_UNSUPPORTED_THUMBNAIL; return NULL; } } // jlb // macros for copying pixels to either BGR or RGB formats #define FORBGR for(c=P1.colors-1; c >=0 ; c--) #define FORRGB for(c=0; c < P1.colors ; c++) void LibRaw::get_mem_image_format(int* width, int* height, int* colors, int* bps) const { if (S.flip & 4) { *width = S.height; *height = S.width; } else { *width = S.width; *height = S.height; } *colors = P1.colors; *bps = O.output_bps; } int LibRaw::copy_mem_image(void* scan0, int stride, int bgr) { // the image memory pointed to by scan0 is assumed to be in the format returned by get_mem_image_format if((imgdata.progress_flags & LIBRAW_PROGRESS_THUMB_MASK) < LIBRAW_PROGRESS_PRE_INTERPOLATE) return LIBRAW_OUT_OF_ORDER_CALL; if(libraw_internal_data.output_data.histogram) { int perc, val, total, t_white=0x2000,c; perc = S.width * S.height * 0.01; /* 99th percentile white level */ if (IO.fuji_width) perc /= 2; if (!((O.highlight & ~2) || O.no_auto_bright)) for (t_white=c=0; c < P1.colors; c++) { for (val=0x2000, total=0; --val > 32; ) if ((total += libraw_internal_data.output_data.histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve (O.gamm[0], O.gamm[1], 2, (t_white << 3)/O.bright); } int s_iheight = S.iheight; int s_iwidth = S.iwidth; int s_width = S.width; int s_hwight = S.height; S.iheight = S.height; S.iwidth = S.width; if (S.flip & 4) SWAP(S.height,S.width); uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; soff = flip_index (0, 0); cstep = flip_index (0, 1) - soff; rstep = flip_index (1, 0) - flip_index (0, S.width); for (row=0; row < S.height; row++, soff += rstep) { uchar *bufp = ((uchar*)scan0)+row*stride; ppm2 = (ushort*) (ppm = bufp); // keep trivial decisions in the outer loop for speed if (bgr) { if (O.output_bps == 8) { for (col=0; col < S.width; col++, soff += cstep) FORBGR *ppm++ = imgdata.color.curve[imgdata.image[soff][c]]>>8; } else { for (col=0; col < S.width; col++, soff += cstep) FORBGR *ppm2++ = imgdata.color.curve[imgdata.image[soff][c]]; } } else { if (O.output_bps == 8) { for (col=0; col < S.width; col++, soff += cstep) FORRGB *ppm++ = imgdata.color.curve[imgdata.image[soff][c]]>>8; } else { for (col=0; col < S.width; col++, soff += cstep) FORRGB *ppm2++ = imgdata.color.curve[imgdata.image[soff][c]]; } } // bufp += stride; // go to the next line } S.iheight = s_iheight; S.iwidth = s_iwidth; S.width = s_width; S.height = s_hwight; return 0; } #undef FORBGR #undef FORRGB libraw_processed_image_t *LibRaw::dcraw_make_mem_image(int *errcode) { int width, height, colors, bps; get_mem_image_format(&width, &height, &colors, &bps); int stride = width * (bps/8) * colors; unsigned ds = height * stride; libraw_processed_image_t *ret = (libraw_processed_image_t*)::malloc(sizeof(libraw_processed_image_t)+ds); if(!ret) { if(errcode) *errcode= ENOMEM; return NULL; } memset(ret,0,sizeof(libraw_processed_image_t)); // metadata init ret->type = LIBRAW_IMAGE_BITMAP; ret->height = height; ret->width = width; ret->colors = colors; ret->bits = bps; ret->data_size = ds; copy_mem_image(ret->data, stride, 0); return ret; } #undef FORC #undef FORCC #undef SWAP #endif int LibRaw::dcraw_ppm_tiff_writer(const char *filename) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); if(!imgdata.image) return LIBRAW_OUT_OF_ORDER_CALL; if(!filename) return ENOENT; FILE *f = fopen(filename,"wb"); if(!f) return errno; try { if(!libraw_internal_data.output_data.histogram) { libraw_internal_data.output_data.histogram = (int (*)[LIBRAW_HISTOGRAM_SIZE]) malloc(sizeof(*libraw_internal_data.output_data.histogram)*4); merror(libraw_internal_data.output_data.histogram,"LibRaw::dcraw_ppm_tiff_writer()"); } libraw_internal_data.internal_data.output = f; write_ppm_tiff(); SET_PROC_FLAG(LIBRAW_PROGRESS_FLIP); libraw_internal_data.internal_data.output = NULL; fclose(f); return 0; } catch ( LibRaw_exceptions err) { fclose(f); EXCEPTION_HANDLER(err); } } void LibRaw::kodak_thumb_loader() { // some kodak cameras ushort s_height = S.height, s_width = S.width,s_iwidth = S.iwidth,s_iheight=S.iheight; int s_colors = P1.colors; unsigned s_filters = P1.filters; ushort (*s_image)[4] = imgdata.image; S.height = T.theight; S.width = T.twidth; P1.filters = 0; if (thumb_load_raw == &CLASS kodak_ycbcr_load_raw) { S.height += S.height & 1; S.width += S.width & 1; } imgdata.image = (ushort (*)[4]) calloc (S.iheight*S.iwidth, sizeof (*imgdata.image)); merror (imgdata.image, "LibRaw::kodak_thumb_loader()"); ID.input->seek(ID.toffset, SEEK_SET); // read kodak thumbnail into T.image[] (this->*thumb_load_raw)(); // copy-n-paste from image pipe #define MIN(a,b) ((a) < (b) ? (a) : (b)) #define MAX(a,b) ((a) > (b) ? (a) : (b)) #define LIM(x,min,max) MAX(min,MIN(x,max)) #define CLIP(x) LIM(x,0,65535) #define SWAP(a,b) { a ^= b; a ^= (b ^= a); } // from scale_colors { double dmax; float scale_mul[4]; int c,val; for (dmax=DBL_MAX, c=0; c < 3; c++) if (dmax > C.pre_mul[c]) dmax = C.pre_mul[c]; for( c=0; c< 3; c++) scale_mul[c] = (C.pre_mul[c] / dmax) * 65535.0 / C.maximum; scale_mul[3] = scale_mul[1]; size_t size = S.height * S.width; for (unsigned i=0; i < size*4 ; i++) { val = imgdata.image[0][i]; if(!val) continue; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } // from convert_to_rgb ushort *img; int row,col; int (*t_hist)[LIBRAW_HISTOGRAM_SIZE] = (int (*)[LIBRAW_HISTOGRAM_SIZE]) calloc(sizeof(*t_hist),4); merror (t_hist, "LibRaw::kodak_thumb_loader()"); float out[3], out_cam[3][4] = { {2.81761312, -1.98369181, 0.166078627, 0}, {-0.111855984, 1.73688626, -0.625030339, 0}, {-0.0379119813, -0.891268849, 1.92918086, 0} }; for (img=imgdata.image[0], row=0; row < S.height; row++) for (col=0; col < S.width; col++, img+=4) { out[0] = out[1] = out[2] = 0; int c; for(c=0;c<3;c++) { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } for(c=0; c<3; c++) img[c] = CLIP((int) out[c]); for(c=0; c<P1.colors;c++) t_hist[c][img[c] >> 3]++; } // from gamma_lut int (*save_hist)[LIBRAW_HISTOGRAM_SIZE] = libraw_internal_data.output_data.histogram; libraw_internal_data.output_data.histogram = t_hist; // make curve output curve! ushort (*t_curve) = (ushort*) calloc(sizeof(C.curve),1); merror (t_curve, "LibRaw::kodak_thumb_loader()"); memmove(t_curve,C.curve,sizeof(C.curve)); memset(C.curve,0,sizeof(C.curve)); { int perc, val, total, t_white=0x2000,c; perc = S.width * S.height * 0.01; /* 99th percentile white level */ if (IO.fuji_width) perc /= 2; if (!((O.highlight & ~2) || O.no_auto_bright)) for (t_white=c=0; c < P1.colors; c++) { for (val=0x2000, total=0; --val > 32; ) if ((total += libraw_internal_data.output_data.histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve (O.gamm[0], O.gamm[1], 2, (t_white << 3)/O.bright); } libraw_internal_data.output_data.histogram = save_hist; free(t_hist); // from write_ppm_tiff - copy pixels into bitmap S.iheight = S.height; S.iwidth = S.width; if (S.flip & 4) SWAP(S.height,S.width); if(T.thumb) free(T.thumb); T.thumb = (char*) calloc (S.width * S.height, P1.colors); merror (T.thumb, "LibRaw::kodak_thumb_loader()"); T.tlength = S.width * S.height * P1.colors; // from write_tiff_ppm { int soff = flip_index (0, 0); int cstep = flip_index (0, 1) - soff; int rstep = flip_index (1, 0) - flip_index (0, S.width); for (int row=0; row < S.height; row++, soff += rstep) { char *ppm = T.thumb + row*S.width*P1.colors; for (int col=0; col < S.width; col++, soff += cstep) for(int c = 0; c < P1.colors; c++) ppm [col*P1.colors+c] = imgdata.color.curve[imgdata.image[soff][c]]>>8; } } memmove(C.curve,t_curve,sizeof(C.curve)); free(t_curve); // restore variables free(imgdata.image); imgdata.image = s_image; T.twidth = S.width; S.width = s_width; S.iwidth = s_iwidth; S.iheight = s_iheight; T.theight = S.height; S.height = s_height; T.tcolors = P1.colors; P1.colors = s_colors; P1.filters = s_filters; } #undef MIN #undef MAX #undef LIM #undef CLIP #undef SWAP // ������� thumbnail �� �����, ������ thumb_format � ������������ � �������� int LibRaw::unpack_thumb(void) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); CHECK_ORDER_BIT(LIBRAW_PROGRESS_THUMB_LOAD); try { if(!libraw_internal_data.internal_data.input) return LIBRAW_INPUT_CLOSED; if ( !ID.toffset) { return LIBRAW_NO_THUMBNAIL; } else if (thumb_load_raw) { kodak_thumb_loader(); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else { ID.input->seek(ID.toffset, SEEK_SET); if ( write_thumb == &LibRaw::jpeg_thumb) { if(T.thumb) free(T.thumb); T.thumb = (char *) malloc (T.tlength); merror (T.thumb, "jpeg_thumb()"); ID.input->read (T.thumb, 1, T.tlength); T.tcolors = 3; T.tformat = LIBRAW_THUMBNAIL_JPEG; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::ppm_thumb) { T.tlength = T.twidth * T.theight*3; if(T.thumb) free(T.thumb); T.thumb = (char *) malloc (T.tlength); merror (T.thumb, "ppm_thumb()"); ID.input->read(T.thumb, 1, T.tlength); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::ppm16_thumb) { T.tlength = T.twidth * T.theight*3; ushort *t_thumb = (ushort*)calloc(T.tlength,2); ID.input->read(t_thumb,2,T.tlength); if ((libraw_internal_data.unpacker_data.order= 0x4949) == (ntohs(0x1234) == 0x1234)) swab ((char*)t_thumb, (char*)t_thumb, T.tlength*2); if(T.thumb) free(T.thumb); T.thumb = (char *) malloc (T.tlength); merror (T.thumb, "ppm_thumb()"); for (int i=0; i < T.tlength; i++) T.thumb[i] = t_thumb[i] >> 8; free(t_thumb); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::foveon_thumb) { foveon_thumb_loader(); // may return with error, so format is set in // foveon thumb loader itself SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } // else if -- all other write_thumb cases! else { return LIBRAW_UNSUPPORTED_THUMBNAIL; } } // last resort return LIBRAW_UNSUPPORTED_THUMBNAIL; } catch ( LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } int LibRaw::dcraw_thumb_writer(const char *fname) { // CHECK_ORDER_LOW(LIBRAW_PROGRESS_THUMB_LOAD); if(!fname) return ENOENT; FILE *tfp = fopen(fname,"wb"); if(!tfp) return errno; if(!T.thumb) { fclose(tfp); return LIBRAW_OUT_OF_ORDER_CALL; } try { switch (T.tformat) { case LIBRAW_THUMBNAIL_JPEG: jpeg_thumb_writer (tfp,T.thumb,T.tlength); break; case LIBRAW_THUMBNAIL_BITMAP: fprintf (tfp, "P6\n%d %d\n255\n", T.twidth, T.theight); fwrite (T.thumb, 1, T.tlength, tfp); break; default: fclose(tfp); return LIBRAW_UNSUPPORTED_THUMBNAIL; } fclose(tfp); return 0; } catch ( LibRaw_exceptions err) { fclose(tfp); EXCEPTION_HANDLER(err); } } int LibRaw::adjust_sizes_info_only(void) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); raw2image_start(); if (O.use_fuji_rotate) { if (IO.fuji_width) { IO.fuji_width = (IO.fuji_width - 1 + IO.shrink) >> IO.shrink; S.iwidth = (ushort)(IO.fuji_width / sqrt(0.5)); S.iheight = (ushort)( (S.iheight - IO.fuji_width) / sqrt(0.5)); } else { if (S.pixel_aspect < 1) S.iheight = (ushort)( S.iheight / S.pixel_aspect + 0.5); if (S.pixel_aspect > 1) S.iwidth = (ushort) (S.iwidth * S.pixel_aspect + 0.5); } } SET_PROC_FLAG(LIBRAW_PROGRESS_FUJI_ROTATE); if ( S.flip & 4) { unsigned short t = S.iheight; S.iheight=S.iwidth; S.iwidth = t; SET_PROC_FLAG(LIBRAW_PROGRESS_FLIP); } return 0; } int LibRaw::subtract_black() { CHECK_ORDER_LOW(LIBRAW_PROGRESS_RAW2_IMAGE); try { if(!is_phaseone_compressed() && (C.cblack[0] || C.cblack[1] || C.cblack[2] || C.cblack[3])) { #define BAYERC(row,col,c) imgdata.image[((row) >> IO.shrink)*S.iwidth + ((col) >> IO.shrink)][c] int cblk[4],i; for(i=0;i<4;i++) cblk[i] = C.cblack[i]; int size = S.iheight * S.iwidth; #define MIN(a,b) ((a) < (b) ? (a) : (b)) #define MAX(a,b) ((a) > (b) ? (a) : (b)) #define LIM(x,min,max) MAX(min,MIN(x,max)) #define CLIP(x) LIM(x,0,65535) int dmax = 0; for(i=0; i< size*4; i++) { int val = imgdata.image[0][i]; val -= cblk[i & 3]; imgdata.image[0][i] = CLIP(val); if(dmax < val) dmax = val; } C.data_maximum = dmax & 0xffff; #undef MIN #undef MAX #undef LIM #undef CLIP C.maximum -= C.black; ZERO(C.cblack); C.black = 0; #undef BAYERC } else { // Nothing to Do, maximum is already calculated, black level is 0, so no change // only calculate channel maximum; int idx; ushort *p = (ushort*)imgdata.image; int dmax = 0; for(idx=0;idx<S.iheight*S.iwidth*4;idx++) if(dmax < p[idx]) dmax = p[idx]; C.data_maximum = dmax; } return 0; } catch ( LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } #define TBLN 65535 void LibRaw::exp_bef(float shift, float smooth) { // params limits if(shift>8) shift = 8; if(shift<0.25) shift = 0.25; if(smooth < 0.0) smooth = 0.0; if(smooth > 1.0) smooth = 1.0; unsigned short *lut = (ushort*)malloc((TBLN+1)*sizeof(unsigned short)); if(shift <=1.0) { for(int i=0;i<=TBLN;i++) lut[i] = (unsigned short)((float)i*shift); } else { float x1,x2,y1,y2; float cstops = log(shift)/log(2.0f); float room = cstops*2; float roomlin = powf(2.0f,room); x2 = (float)TBLN; x1 = (x2+1)/roomlin-1; y1 = x1*shift; y2 = x2*(1+(1-smooth)*(shift-1)); float sq3x=powf(x1*x1*x2,1.0f/3.0f); float B = (y2-y1+shift*(3*x1-3.0f*sq3x)) / (x2+2.0f*x1-3.0f*sq3x); float A = (shift - B)*3.0f*powf(x1*x1,1.0f/3.0f); float CC = y2 - A*powf(x2,1.0f/3.0f)-B*x2; for(int i=0;i<=TBLN;i++) { float X = (float)i; float Y = A*powf(X,1.0f/3.0f)+B*X+CC; if(i<x1) lut[i] = (unsigned short)((float)i*shift); else lut[i] = Y<0?0:(Y>TBLN?TBLN:(unsigned short)(Y)); } } for(int i=0; i< S.height*S.width; i++) { imgdata.image[i][0] = lut[imgdata.image[i][0]]; imgdata.image[i][1] = lut[imgdata.image[i][1]]; imgdata.image[i][2] = lut[imgdata.image[i][2]]; imgdata.image[i][3] = lut[imgdata.image[i][3]]; } if(C.data_maximum <=TBLN) C.data_maximum = lut[C.data_maximum]; if(C.maximum <= TBLN) C.maximum = lut[C.maximum]; // no need to adjust the minumum, black is already subtracted free(lut); } #define MIN(a,b) ((a) < (b) ? (a) : (b)) #define MAX(a,b) ((a) > (b) ? (a) : (b)) #define LIM(x,min,max) MAX(min,MIN(x,max)) #define ULIM(x,y,z) ((y) < (z) ? LIM(x,y,z) : LIM(x,z,y)) #define CLIP(x) LIM(x,0,65535) void LibRaw::convert_to_rgb_loop(float out_cam[3][4]) { int row,col,c; float out[3]; ushort *img; memset(libraw_internal_data.output_data.histogram,0,sizeof(int)*LIBRAW_HISTOGRAM_SIZE*4); for (img=imgdata.image[0], row=0; row < S.height; row++) for (col=0; col < S.width; col++, img+=4) { if (!libraw_internal_data.internal_output_params.raw_color) { out[0] = out[1] = out[2] = 0; for(c=0; c< imgdata.idata.colors; c++) { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } for(c=0;c<3;c++) img[c] = CLIP((int) out[c]); } for(c=0; c< imgdata.idata.colors; c++) libraw_internal_data.output_data.histogram[c][img[c] >> 3]++; } } void LibRaw::scale_colors_loop(float scale_mul[4]) { unsigned size = S.iheight*S.iwidth; if(C.cblack[0]||C.cblack[1]||C.cblack[2]||C.cblack[3]) { for (unsigned i=0; i < size*4; i++) { int val = imgdata.image[0][i]; if (!val) continue; val -= C.cblack[i & 3]; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } else // BL is zero { for (unsigned i=0; i < size*4; i++) { int val = imgdata.image[0][i]; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } } void LibRaw::adjust_bl() { if (O.user_black >= 0) C.black = O.user_black; for(int i=0; i<4; i++) if(O.user_cblack[i]>-1000000) C.cblack[i] = O.user_cblack[i]; // remove common part from C.cblack[] int i = C.cblack[3]; int c; for(c=0;c<3;c++) if (i > C.cblack[c]) i = C.cblack[c]; for(c=0;c<4;c++) C.cblack[c] -= i; C.black += i; for(c=0;c<4;c++) C.cblack[c] += C.black; } int LibRaw::dcraw_process(void) { int quality,i; int iterations=-1, dcb_enhance=1, noiserd=0; int eeci_refine_fl=0, es_med_passes_fl=0; float cared=0,cablue=0; float linenoise=0; float lclean=0,cclean=0; float thresh=0; float preser=0; float expos=1.0; CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); // CHECK_ORDER_HIGH(LIBRAW_PROGRESS_PRE_INTERPOLATE); try { int no_crop = 1; if (~O.cropbox[2] && ~O.cropbox[3]) no_crop=0; libraw_decoder_info_t di; get_decoder_info(&di); int subtract_inline = !O.bad_pixels && !O.dark_frame && !O.wf_debanding && !(di.decoder_flags & LIBRAW_DECODER_LEGACY) && !IO.zero_is_bad; raw2image_ex(subtract_inline); // allocate imgdata.image and copy data! int save_4color = O.four_color_rgb; if (IO.zero_is_bad) { remove_zeroes(); SET_PROC_FLAG(LIBRAW_PROGRESS_REMOVE_ZEROES); } if(O.half_size) O.four_color_rgb = 1; if(O.bad_pixels && no_crop) { bad_pixels(O.bad_pixels); SET_PROC_FLAG(LIBRAW_PROGRESS_BAD_PIXELS); } if (O.dark_frame && no_crop) { subtract (O.dark_frame); SET_PROC_FLAG(LIBRAW_PROGRESS_DARK_FRAME); } if (O.wf_debanding) { wf_remove_banding(); } quality = 2 + !IO.fuji_width; if (O.user_qual >= 0) quality = O.user_qual; if(!subtract_inline || !C.data_maximum) { adjust_bl(); subtract_black(); } adjust_maximum(); if (O.user_sat > 0) C.maximum = O.user_sat; if (P1.is_foveon) { if(load_raw == &LibRaw::foveon_dp_load_raw) { for (int i=0; i < S.height*S.width*4; i++) if ((short) imgdata.image[0][i] < 0) imgdata.image[0][i] = 0; } else foveon_interpolate(); SET_PROC_FLAG(LIBRAW_PROGRESS_FOVEON_INTERPOLATE); } if (O.green_matching && !O.half_size) { green_matching(); } if (!P1.is_foveon) { scale_colors(); SET_PROC_FLAG(LIBRAW_PROGRESS_SCALE_COLORS); } pre_interpolate(); SET_PROC_FLAG(LIBRAW_PROGRESS_PRE_INTERPOLATE); if (O.dcb_iterations >= 0) iterations = O.dcb_iterations; if (O.dcb_enhance_fl >=0 ) dcb_enhance = O.dcb_enhance_fl; if (O.fbdd_noiserd >=0 ) noiserd = O.fbdd_noiserd; if (O.eeci_refine >=0 ) eeci_refine_fl = O.eeci_refine; if (O.es_med_passes >0 ) es_med_passes_fl = O.es_med_passes; // LIBRAW_DEMOSAIC_PACK_GPL3 if (!O.half_size && O.cfa_green >0) {thresh=O.green_thresh ;green_equilibrate(thresh);} if (O.exp_correc >0) {expos=O.exp_shift ; preser=O.exp_preser; exp_bef(expos,preser);} if (O.ca_correc >0 ) {cablue=O.cablue; cared=O.cared; CA_correct_RT(cablue, cared);} if (O.cfaline >0 ) {linenoise=O.linenoise; cfa_linedn(linenoise);} if (O.cfa_clean >0 ) {lclean=O.lclean; cclean=O.cclean; cfa_impulse_gauss(lclean,cclean);} if (P1.filters) { if (noiserd>0 && P1.colors==3 && P1.filters) fbdd(noiserd); if (quality == 0) lin_interpolate(); else if (quality == 1 || P1.colors > 3 || P1.filters < 1000) vng_interpolate(); else if (quality == 2) ppg_interpolate(); else if (quality == 3) ahd_interpolate(); // really don't need it here due to fallback op else if (quality == 4) dcb(iterations, dcb_enhance); // LIBRAW_DEMOSAIC_PACK_GPL2 else if (quality == 5) ahd_interpolate_mod(); else if (quality == 6) afd_interpolate_pl(2,1); else if (quality == 7) vcd_interpolate(0); else if (quality == 8) vcd_interpolate(12); else if (quality == 9) lmmse_interpolate(1); // LIBRAW_DEMOSAIC_PACK_GPL3 else if (quality == 10) amaze_demosaic_RT(); // LGPL2 else if (quality == 11) dht_interpolate(); else if (quality == 12) aahd_interpolate(); // fallback to AHD else ahd_interpolate(); SET_PROC_FLAG(LIBRAW_PROGRESS_INTERPOLATE); } if (IO.mix_green) { for (P1.colors=3, i=0; i < S.height * S.width; i++) imgdata.image[i][1] = (imgdata.image[i][1] + imgdata.image[i][3]) >> 1; SET_PROC_FLAG(LIBRAW_PROGRESS_MIX_GREEN); } if(!P1.is_foveon) { if (P1.colors == 3) { if (quality == 8) { if (eeci_refine_fl == 1) refinement(); if (O.med_passes > 0) median_filter_new(); if (es_med_passes_fl > 0) es_median_filter(); } else { median_filter(); } SET_PROC_FLAG(LIBRAW_PROGRESS_MEDIAN_FILTER); } } if (O.highlight == 2) { blend_highlights(); SET_PROC_FLAG(LIBRAW_PROGRESS_HIGHLIGHTS); } if (O.highlight > 2) { recover_highlights(); SET_PROC_FLAG(LIBRAW_PROGRESS_HIGHLIGHTS); } if (O.use_fuji_rotate) { fuji_rotate(); SET_PROC_FLAG(LIBRAW_PROGRESS_FUJI_ROTATE); } if(!libraw_internal_data.output_data.histogram) { libraw_internal_data.output_data.histogram = (int (*)[LIBRAW_HISTOGRAM_SIZE]) malloc(sizeof(*libraw_internal_data.output_data.histogram)*4); merror(libraw_internal_data.output_data.histogram,"LibRaw::dcraw_process()"); } #ifndef NO_LCMS if(O.camera_profile) { apply_profile(O.camera_profile,O.output_profile); SET_PROC_FLAG(LIBRAW_PROGRESS_APPLY_PROFILE); } #endif convert_to_rgb(); SET_PROC_FLAG(LIBRAW_PROGRESS_CONVERT_RGB); if (O.use_fuji_rotate) { stretch(); SET_PROC_FLAG(LIBRAW_PROGRESS_STRETCH); } O.four_color_rgb = save_4color; // also, restore return 0; } catch ( LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } // Supported cameras: static const char *static_camera_list[] = { "Adobe Digital Negative (DNG)", "AgfaPhoto DC-833m", "Apple QuickTake 100", "Apple QuickTake 150", "Apple QuickTake 200", "ARRIRAW format", "AVT F-080C", "AVT F-145C", "AVT F-201C", "AVT F-510C", "AVT F-810C", "Canon PowerShot 600", "Canon PowerShot A5", "Canon PowerShot A5 Zoom", "Canon PowerShot A50", "Canon PowerShot A460 (CHDK hack)", "Canon PowerShot A470 (CHDK hack)", "Canon PowerShot A530 (CHDK hack)", "Canon PowerShot A570 (CHDK hack)", "Canon PowerShot A590 (CHDK hack)", "Canon PowerShot A610 (CHDK hack)", "Canon PowerShot A620 (CHDK hack)", "Canon PowerShot A630 (CHDK hack)", "Canon PowerShot A640 (CHDK hack)", "Canon PowerShot A650 (CHDK hack)", "Canon PowerShot A710 IS (CHDK hack)", "Canon PowerShot A720 IS (CHDK hack)", "Canon PowerShot Pro70", "Canon PowerShot Pro90 IS", "Canon PowerShot Pro1", "Canon PowerShot G1", "Canon PowerShot G1 X", "Canon PowerShot G2", "Canon PowerShot G3", "Canon PowerShot G5", "Canon PowerShot G6", "Canon PowerShot G7 (CHDK hack)", "Canon PowerShot G9", "Canon PowerShot G10", "Canon PowerShot G11", "Canon PowerShot G12", "Canon PowerShot G15", "Canon PowerShot S2 IS (CHDK hack)", "Canon PowerShot S3 IS (CHDK hack)", "Canon PowerShot S5 IS (CHDK hack)", "Canon PowerShot SD300 (CHDK hack)", "Canon PowerShot S30", "Canon PowerShot S40", "Canon PowerShot S45", "Canon PowerShot S50", "Canon PowerShot S60", "Canon PowerShot S70", "Canon PowerShot S90", "Canon PowerShot S95", "Canon PowerShot S100", "Canon PowerShot S110", "Canon PowerShot SX1 IS", "Canon PowerShot SX50 HS", "Canon PowerShot SX110 IS (CHDK hack)", "Canon PowerShot SX120 IS (CHDK hack)", "Canon PowerShot SX220 HS (CHDK hack)", "Canon PowerShot SX20 IS (CHDK hack)", "Canon PowerShot SX30 IS (CHDK hack)", "Canon EOS D30", "Canon EOS D60", "Canon EOS 5D", "Canon EOS 5D Mark II", "Canon EOS 5D Mark III", "Canon EOS 6D", "Canon EOS 7D", "Canon EOS 10D", "Canon EOS 20D", "Canon EOS 30D", "Canon EOS 40D", "Canon EOS 50D", "Canon EOS 60D", "Canon EOS 100D/ Digital Rebel SL1", "Canon EOS 300D / Digital Rebel / Kiss Digital", "Canon EOS 350D / Digital Rebel XT / Kiss Digital N", "Canon EOS 400D / Digital Rebel XTi / Kiss Digital X", "Canon EOS 450D / Digital Rebel XSi / Kiss Digital X2", "Canon EOS 500D / Digital Rebel T1i / Kiss Digital X3", "Canon EOS 550D / Digital Rebel T2i / Kiss Digital X4", "Canon EOS 600D / Digital Rebel T3i / Kiss Digital X5", "Canon EOS 650D / Digital Rebel T4i / Kiss Digital X6i", "Canon EOS 700D / Digital Rebel T54i", "Canon EOS 1000D / Digital Rebel XS / Kiss Digital F", "Canon EOS 1100D / Digital Rebel T3 / Kiss Digital X50", "Canon EOS D2000C", "Canon EOS M", "Canon EOS-1D", "Canon EOS-1DS", "Canon EOS-1D X", "Canon EOS-1D Mark II", "Canon EOS-1D Mark II N", "Canon EOS-1D Mark III", "Canon EOS-1D Mark IV", "Canon EOS-1Ds Mark II", "Canon EOS-1Ds Mark III", "Casio QV-2000UX", "Casio QV-3000EX", "Casio QV-3500EX", "Casio QV-4000", "Casio QV-5700", "Casio QV-R41", "Casio QV-R51", "Casio QV-R61", "Casio EX-S20", "Casio EX-S100", "Casio EX-Z4", "Casio EX-Z50", "Casio EX-Z500", "Casio EX-Z55", "Casio EX-Z60", "Casio EX-Z75", "Casio EX-Z750", "Casio EX-Z8", "Casio EX-Z850", "Casio EX-Z1050", "Casio EX-Z1080", "Casio EX-ZR100", "Casio Exlim Pro 505", "Casio Exlim Pro 600", "Casio Exlim Pro 700", "Contax N Digital", "Creative PC-CAM 600", "Epson R-D1", "Foculus 531C", "Fuji E550", "Fuji E900", "Fuji F700", "Fuji F710", "Fuji F800", "Fuji F810", "Fuji S2Pro", "Fuji S3Pro", "Fuji S5Pro", "Fuji S20Pro", "Fuji S100FS", "Fuji S5000", "Fuji S5100/S5500", "Fuji S5200/S5600", "Fuji S6000fd", "Fuji S7000", "Fuji S9000/S9500", "Fuji S9100/S9600", "Fuji S200EXR", "Fuji SL1000", "Fuji HS10/HS11", "Fuji HS20EXR", "Fuji HS30EXR", "Fuji HS50EXR", "Fuji F550EXR", "Fuji F600EXR", "Fuji F770EXR", "Fuji F800EXR", "Fuji X-Pro1", "Fuji X-S1", "Fuji X100", "Fuji X100S", "Fuji X10", "Fuji X20", "Fuji X-E1", "Fuji XF1", "Fuji IS-1", "Hasselblad CFV", "Hasselblad H3D", "Hasselblad H4D", "Hasselblad V96C", "Imacon Ixpress 16-megapixel", "Imacon Ixpress 22-megapixel", "Imacon Ixpress 39-megapixel", "ISG 2020x1520", "Kodak DC20", "Kodak DC25", "Kodak DC40", "Kodak DC50", "Kodak DC120 (also try kdc2tiff)", "Kodak DCS200", "Kodak DCS315C", "Kodak DCS330C", "Kodak DCS420", "Kodak DCS460", "Kodak DCS460A", "Kodak DCS520C", "Kodak DCS560C", "Kodak DCS620C", "Kodak DCS620X", "Kodak DCS660C", "Kodak DCS660M", "Kodak DCS720X", "Kodak DCS760C", "Kodak DCS760M", "Kodak EOSDCS1", "Kodak EOSDCS3B", "Kodak NC2000F", "Kodak ProBack", "Kodak PB645C", "Kodak PB645H", "Kodak PB645M", "Kodak DCS Pro 14n", "Kodak DCS Pro 14nx", "Kodak DCS Pro SLR/c", "Kodak DCS Pro SLR/n", "Kodak C330", "Kodak C603", "Kodak P850", "Kodak P880", "Kodak Z980", "Kodak Z981", "Kodak Z990", "Kodak Z1015", "Kodak KAI-0340", "Konica KD-400Z", "Konica KD-510Z", "Leaf AFi 7", "Leaf AFi-II 5", "Leaf AFi-II 6", "Leaf AFi-II 7", "Leaf AFi-II 8", "Leaf AFi-II 10", "Leaf AFi-II 10R", "Leaf AFi-II 12", "Leaf AFi-II 12R", "Leaf Aptus 17", "Leaf Aptus 22", "Leaf Aptus 54S", "Leaf Aptus 65", "Leaf Aptus 75", "Leaf Aptus 75S", "Leaf Cantare", "Leaf CatchLight", "Leaf CMost", "Leaf DCB2", "Leaf Valeo 6", "Leaf Valeo 11", "Leaf Valeo 17", "Leaf Valeo 22", "Leaf Volare", "Leica Digilux 2", "Leica Digilux 3", "Leica D-LUX2", "Leica D-LUX3", "Leica D-LUX4", "Leica D-LUX5", "Leica D-LUX6", "Leica V-LUX1", "Leica V-LUX2", "Leica V-LUX3", "Leica V-LUX4", "Logitech Fotoman Pixtura", "Mamiya ZD", "Micron 2010", "Minolta RD175", "Minolta DiMAGE 5", "Minolta DiMAGE 7", "Minolta DiMAGE 7i", "Minolta DiMAGE 7Hi", "Minolta DiMAGE A1", "Minolta DiMAGE A2", "Minolta DiMAGE A200", "Minolta DiMAGE G400", "Minolta DiMAGE G500", "Minolta DiMAGE G530", "Minolta DiMAGE G600", "Minolta DiMAGE Z2", "Minolta Alpha/Dynax/Maxxum 5D", "Minolta Alpha/Dynax/Maxxum 7D", "Motorola PIXL", "Nikon D1", "Nikon D1H", "Nikon D1X", "Nikon D2H", "Nikon D2Hs", "Nikon D2X", "Nikon D2Xs", "Nikon D3", "Nikon D3s", "Nikon D3X", "Nikon D4", "Nikon D40", "Nikon D40X", "Nikon D50", "Nikon D60", "Nikon D600", "Nikon D70", "Nikon D70s", "Nikon D80", "Nikon D90", "Nikon D100", "Nikon D200", "Nikon D300", "Nikon D300s", "Nikon D700", "Nikon D3000", "Nikon D3100", "Nikon D3200", "Nikon D5000", "Nikon D5100", "Nikon D7000", "Nikon D800", "Nikon D800E", "Nikon 1 J1", "Nikon 1 S1", "Nikon 1 V1", "Nikon 1 J2", "Nikon 1 V2", "Nikon 1 J3", "Nikon E700 (\"DIAG RAW\" hack)", "Nikon E800 (\"DIAG RAW\" hack)", "Nikon E880 (\"DIAG RAW\" hack)", "Nikon E900 (\"DIAG RAW\" hack)", "Nikon E950 (\"DIAG RAW\" hack)", "Nikon E990 (\"DIAG RAW\" hack)", "Nikon E995 (\"DIAG RAW\" hack)", "Nikon E2100 (\"DIAG RAW\" hack)", "Nikon E2500 (\"DIAG RAW\" hack)", "Nikon E3200 (\"DIAG RAW\" hack)", "Nikon E3700 (\"DIAG RAW\" hack)", "Nikon E4300 (\"DIAG RAW\" hack)", "Nikon E4500 (\"DIAG RAW\" hack)", "Nikon E5000", "Nikon E5400", "Nikon E5700", "Nikon E8400", "Nikon E8700", "Nikon E8800", "Nikon Coolpix A", "Nikon Coolpix P330", "Nikon Coolpix P6000", "Nikon Coolpix P7000", "Nikon Coolpix P7100", "Nikon Coolpix P7700", "Nikon Coolpix S6 (\"DIAG RAW\" hack)", "Nokia N95", "Nokia X2", "Olympus C3030Z", "Olympus C5050Z", "Olympus C5060WZ", "Olympus C7070WZ", "Olympus C70Z,C7000Z", "Olympus C740UZ", "Olympus C770UZ", "Olympus C8080WZ", "Olympus X200,D560Z,C350Z", "Olympus E-1", "Olympus E-3", "Olympus E-5", "Olympus E-10", "Olympus E-20", "Olympus E-30", "Olympus E-300", "Olympus E-330", "Olympus E-400", "Olympus E-410", "Olympus E-420", "Olympus E-500", "Olympus E-510", "Olympus E-520", "Olympus E-620", "Olympus E-P1", "Olympus E-P2", "Olympus E-P3", "Olympus E-PL1", "Olympus E-PL1s", "Olympus E-PL2", "Olympus E-PL3", "Olympus E-PL5", "Olympus E-PM1", "Olympus E-PM2", "Olympus E-M5", "Olympus SP310", "Olympus SP320", "Olympus SP350", "Olympus SP500UZ", "Olympus SP510UZ", "Olympus SP550UZ", "Olympus SP560UZ", "Olympus SP570UZ", "Olympus XZ-1", "Olympus XZ-10", "Olympus XZ-2", "Panasonic DMC-FZ8", "Panasonic DMC-FZ18", "Panasonic DMC-FZ28", "Panasonic DMC-FZ30", "Panasonic DMC-FZ35/FZ38", "Panasonic DMC-FZ40", "Panasonic DMC-FZ50", "Panasonic DMC-FZ100", "Panasonic DMC-FZ150", "Panasonic DMC-FZ200", "Panasonic DMC-FX150", "Panasonic DMC-G1", "Panasonic DMC-G10", "Panasonic DMC-G2", "Panasonic DMC-G3", "Panasonic DMC-G5", "Panasonic DMC-G6", "Panasonic DMC-GF1", "Panasonic DMC-GF2", "Panasonic DMC-GF3", "Panasonic DMC-GF5", "Panasonic DMC-GH1", "Panasonic DMC-GH2", "Panasonic DMC-GH3", "Panasonic DMC-GX1", "Panasonic DMC-L1", "Panasonic DMC-L10", "Panasonic DMC-LC1", "Panasonic DMC-LX1", "Panasonic DMC-LX2", "Panasonic DMC-LX3", "Panasonic DMC-LX5", "Panasonic DMC-LX7", "Pentax *ist D", "Pentax *ist DL", "Pentax *ist DL2", "Pentax *ist DS", "Pentax *ist DS2", "Pentax K10D", "Pentax K20D", "Pentax K100D", "Pentax K100D Super", "Pentax K200D", "Pentax K2000/K-m", "Pentax K-x", "Pentax K-r", "Pentax K-30", "Pentax K-5", "Pentax K-5 II", "Pentax K-5 IIs", "Pentax K-7", "Pentax MX-1", "Pentax Q10", "Pentax Optio S", "Pentax Optio S4", "Pentax Optio 33WR", "Pentax Optio 750Z", "Pentax 645D", "Phase One LightPhase", "Phase One H 10", "Phase One H 20", "Phase One H 25", "Phase One P 20", "Phase One P 25", "Phase One P 30", "Phase One P 45", "Phase One P 45+", "Phase One P 65", "Pixelink A782", #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 "Polaroid x530", #endif #ifndef NO_JASPER "Redcode R3D format", #endif "Rollei d530flex", "RoverShot 3320af", "Samsung EX1", "Samsung EX2F", "Samsung GX-1S", "Samsung GX10", "Samsung GX20", "Samsung NX10", "Samsung NX11", "Samsung NX100", "Samsung NX20", "Samsung NX200", "Samsung NX210", "Samsung NX1000", "Samsung WB550", "Samsung WB2000", "Samsung S85 (hacked)", "Samsung S850 (hacked)", "Sarnoff 4096x5440", #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 "Sigma SD9", "Sigma SD10", "Sigma SD14", "Sigma SD15", "Sigma SD1", "Sigma SD1 Merill", "Sigma DP1", "Sigma DP1 Merill", "Sigma DP1S", "Sigma DP1X", "Sigma DP2", "Sigma DP2 Merill", "Sigma DP2S", "Sigma DP2X", #endif "Sinar 3072x2048", "Sinar 4080x4080", "Sinar 4080x5440", "Sinar STI format", "SMaL Ultra-Pocket 3", "SMaL Ultra-Pocket 4", "SMaL Ultra-Pocket 5", "Sony DSC-F828", "Sony DSC-R1", "Sony DSC-RX1", "Sony DSC-RX100", "Sony DSC-V3", "Sony DSLR-A100", "Sony DSLR-A200", "Sony DSLR-A230", "Sony DSLR-A290", "Sony DSLR-A300", "Sony DSLR-A330", "Sony DSLR-A350", "Sony DSLR-A380", "Sony DSLR-A390", "Sony DSLR-A450", "Sony DSLR-A500", "Sony DSLR-A550", "Sony DSLR-A580", "Sony DSLR-A700", "Sony DSLR-A850", "Sony DSLR-A900", "Sony NEX-3", "Sony NEX-5", "Sony NEX-5N", "Sony NEX-5R", "Sony NEX-6", "Sony NEX-7", "Sony NEX-C3", "Sony NEX-F3", "Sony SLT-A33", "Sony SLT-A35", "Sony SLT-A37", "Sony SLT-A55V", "Sony SLT-A57", "Sony SLT-A58", "Sony SLT-A65V", "Sony SLT-A77V", "Sony SLT-A99V", "Sony XCD-SX910CR", "STV680 VGA", "ptGrey GRAS-50S5C", "JaiPulnix BB-500CL", "JaiPulnix BB-500GE", "SVS SVS625CL", NULL }; const char** LibRaw::cameraList() { return static_camera_list;} int LibRaw::cameraCount() { return (sizeof(static_camera_list)/sizeof(static_camera_list[0]))-1; } const char * LibRaw::strprogress(enum LibRaw_progress p) { switch(p) { case LIBRAW_PROGRESS_START: return "Starting"; case LIBRAW_PROGRESS_OPEN : return "Opening file"; case LIBRAW_PROGRESS_IDENTIFY : return "Reading metadata"; case LIBRAW_PROGRESS_SIZE_ADJUST: return "Adjusting size"; case LIBRAW_PROGRESS_LOAD_RAW: return "Reading RAW data"; case LIBRAW_PROGRESS_REMOVE_ZEROES: return "Clearing zero values"; case LIBRAW_PROGRESS_BAD_PIXELS : return "Removing dead pixels"; case LIBRAW_PROGRESS_DARK_FRAME: return "Subtracting dark frame data"; case LIBRAW_PROGRESS_FOVEON_INTERPOLATE: return "Interpolating Foveon sensor data"; case LIBRAW_PROGRESS_SCALE_COLORS: return "Scaling colors"; case LIBRAW_PROGRESS_PRE_INTERPOLATE: return "Pre-interpolating"; case LIBRAW_PROGRESS_INTERPOLATE: return "Interpolating"; case LIBRAW_PROGRESS_MIX_GREEN : return "Mixing green channels"; case LIBRAW_PROGRESS_MEDIAN_FILTER : return "Median filter"; case LIBRAW_PROGRESS_HIGHLIGHTS: return "Highlight recovery"; case LIBRAW_PROGRESS_FUJI_ROTATE : return "Rotating Fuji diagonal data"; case LIBRAW_PROGRESS_FLIP : return "Flipping image"; case LIBRAW_PROGRESS_APPLY_PROFILE: return "ICC conversion"; case LIBRAW_PROGRESS_CONVERT_RGB: return "Converting to RGB"; case LIBRAW_PROGRESS_STRETCH: return "Stretching image"; case LIBRAW_PROGRESS_THUMB_LOAD: return "Loading thumbnail"; default: return "Some strange things"; } }
./CrossVul/dataset_final_sorted/CWE-399/cpp/good_5642_0
crossvul-cpp_data_bad_1539_2
/*************************************************************************** * Copyright (C) 2005-2015 by the Quassel Project * * devel@quassel-irc.org * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) version 3. * * * * 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 <QHostInfo> #include "corenetwork.h" #include "core.h" #include "coreidentity.h" #include "corenetworkconfig.h" #include "coresession.h" #include "coreuserinputhandler.h" #include "networkevent.h" INIT_SYNCABLE_OBJECT(CoreNetwork) CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session) : Network(networkid, session), _coreSession(session), _userInputHandler(new CoreUserInputHandler(this)), _autoReconnectCount(0), _quitRequested(false), _previousConnectionAttemptFailed(false), _lastUsedServerIndex(0), _lastPingTime(0), _pingCount(0), _sendPings(false), _requestedUserModes('-') { _autoReconnectTimer.setSingleShot(true); connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout())); setPingInterval(networkConfig()->pingInterval()); connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing())); setAutoWhoDelay(networkConfig()->autoWhoDelay()); setAutoWhoInterval(networkConfig()->autoWhoInterval()); QHash<QString, QString> channels = coreSession()->persistentChannels(networkId()); foreach(QString chan, channels.keys()) { _channelKeys[chan.toLower()] = channels[chan]; } connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool))); connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int))); connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool))); connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int))); connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int))); connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect())); connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho())); connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle())); connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue())); connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized())); connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected())); connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError))); connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState))); connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData())); #ifdef HAVE_SSL connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized())); connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &))); #endif connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *))); if (Quassel::isOptionSet("oidentd")) { connect(this, SIGNAL(socketOpen(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Qt::BlockingQueuedConnection); connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16))); } } CoreNetwork::~CoreNetwork() { if (connectionState() != Disconnected && connectionState() != Network::Reconnecting) disconnectFromIrc(false); // clean up, but this does not count as requested disconnect! disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up delete _userInputHandler; } QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const { if (!bufferName.isEmpty()) { IrcChannel *channel = ircChannel(bufferName); if (channel) return channel->decodeString(string); } return decodeString(string); } QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const { IrcUser *user = ircUser(userNick); if (user) return user->decodeString(string); return decodeString(string); } QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const { if (!bufferName.isEmpty()) { IrcChannel *channel = ircChannel(bufferName); if (channel) return channel->encodeString(string); } return encodeString(string); } QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const { IrcUser *user = ircUser(userNick); if (user) return user->encodeString(string); return encodeString(string); } void CoreNetwork::connectToIrc(bool reconnecting) { if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) { _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000); if (unlimitedReconnectRetries()) _autoReconnectCount = -1; else _autoReconnectCount = autoReconnectRetries(); } if (serverList().isEmpty()) { qWarning() << "Server list empty, ignoring connect request!"; return; } CoreIdentity *identity = identityPtr(); if (!identity) { qWarning() << "Invalid identity configures, ignoring connect request!"; return; } // cleaning up old quit reason _quitReason.clear(); // use a random server? if (useRandomServer()) { _lastUsedServerIndex = qrand() % serverList().size(); } else if (_previousConnectionAttemptFailed) { // cycle to next server if previous connection attempt failed displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server")); if (++_lastUsedServerIndex >= serverList().size()) { _lastUsedServerIndex = 0; } } _previousConnectionAttemptFailed = false; Server server = usedServer(); displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port)); displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port)); if (server.useProxy) { QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass); socket.setProxy(proxy); } else { socket.setProxy(QNetworkProxy::NoProxy); } enablePingTimeout(); // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry. QHostInfo::fromName(server.host); #ifdef HAVE_SSL if (server.useSsl) { CoreIdentity *identity = identityPtr(); if (identity) { socket.setLocalCertificate(identity->sslCert()); socket.setPrivateKey(identity->sslKey()); } socket.connectToHostEncrypted(server.host, server.port); } else { socket.connectToHost(server.host, server.port); } #else socket.connectToHost(server.host, server.port); #endif } void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect) { _quitRequested = requested; // see socketDisconnected(); if (!withReconnect) { _autoReconnectTimer.stop(); _autoReconnectCount = 0; // prohibiting auto reconnect } disablePingTimeout(); _msgQueue.clear(); IrcUser *me_ = me(); if (me_) { QString awayMsg; if (me_->isAway()) awayMsg = me_->awayMessage(); Core::setAwayMessage(userId(), networkId(), awayMsg); } if (reason.isEmpty() && identityPtr()) _quitReason = identityPtr()->quitReason(); else _quitReason = reason; displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason)); if (socket.state() == QAbstractSocket::UnconnectedState) { socketDisconnected(); } else { if (socket.state() == QAbstractSocket::ConnectedState) { userInputHandler()->issueQuit(_quitReason); } else { socket.close(); } if (requested || withReconnect) { // the irc server has 10 seconds to close the socket _socketCloseTimer.start(10000); } } } void CoreNetwork::userInput(BufferInfo buf, QString msg) { userInputHandler()->handleUserInput(buf, msg); } void CoreNetwork::putRawLine(QByteArray s) { if (_tokenBucket > 0) writeToSocket(s); else _msgQueue.append(s); } void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix) { QByteArray msg; if (!prefix.isEmpty()) msg += ":" + prefix + " "; msg += cmd.toUpper().toLatin1(); for (int i = 0; i < params.size(); i++) { msg += " "; if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':'))) msg += ":"; msg += params[i]; } putRawLine(msg); } void CoreNetwork::setChannelJoined(const QString &channel) { _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked Core::setChannelPersistent(userId(), networkId(), channel, true); Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]); } void CoreNetwork::setChannelParted(const QString &channel) { removeChannelKey(channel); _autoWhoQueue.removeAll(channel.toLower()); _autoWhoPending.remove(channel.toLower()); Core::setChannelPersistent(userId(), networkId(), channel, false); } void CoreNetwork::addChannelKey(const QString &channel, const QString &key) { if (key.isEmpty()) { removeChannelKey(channel); } else { _channelKeys[channel.toLower()] = key; } } void CoreNetwork::removeChannelKey(const QString &channel) { _channelKeys.remove(channel.toLower()); } #ifdef HAVE_QCA2 Cipher *CoreNetwork::cipher(const QString &target) { if (target.isEmpty()) return 0; if (!Cipher::neededFeaturesAvailable()) return 0; CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target)); if (channel) { return channel->cipher(); } CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target)); if (user) { return user->cipher(); } else if (!isChannelName(target)) { return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher(); } return 0; } QByteArray CoreNetwork::cipherKey(const QString &target) const { CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target)); if (c) return c->cipher()->key(); CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target)); if (u) return u->cipher()->key(); return QByteArray(); } void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key) { CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target)); if (c) { c->setEncrypted(c->cipher()->setKey(key)); return; } CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target)); if (!u && !isChannelName(target)) u = qobject_cast<CoreIrcUser*>(newIrcUser(target)); if (u) { u->setEncrypted(u->cipher()->setKey(key)); return; } } bool CoreNetwork::cipherUsesCBC(const QString &target) { CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target)); if (c) return c->cipher()->usesCBC(); CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target)); if (u) return u->cipher()->usesCBC(); return false; } #endif /* HAVE_QCA2 */ bool CoreNetwork::setAutoWhoDone(const QString &channel) { QString chan = channel.toLower(); if (_autoWhoPending.value(chan, 0) <= 0) return false; if (--_autoWhoPending[chan] <= 0) _autoWhoPending.remove(chan); return true; } void CoreNetwork::setMyNick(const QString &mynick) { Network::setMyNick(mynick); if (connectionState() == Network::Initializing) networkInitialized(); } void CoreNetwork::socketHasData() { while (socket.canReadLine()) { QByteArray s = socket.readLine(); if (s.endsWith("\r\n")) s.chop(2); else if (s.endsWith("\n")) s.chop(1); NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s); event->setTimestamp(QDateTime::currentDateTimeUtc()); emit newEvent(event); } } void CoreNetwork::socketError(QAbstractSocket::SocketError error) { if (_quitRequested && error == QAbstractSocket::RemoteHostClosedError) return; _previousConnectionAttemptFailed = true; qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString())); emit connectionError(socket.errorString()); displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString())); emitConnectionError(socket.errorString()); if (socket.state() < QAbstractSocket::ConnectedState) { socketDisconnected(); } } void CoreNetwork::socketInitialized() { CoreIdentity *identity = identityPtr(); if (!identity) { qCritical() << "Identity invalid!"; disconnectFromIrc(); return; } emit socketOpen(identity, localAddress(), localPort(), peerAddress(), peerPort()); Server server = usedServer(); #ifdef HAVE_SSL if (server.useSsl && !socket.isEncrypted()) return; #endif socket.setSocketOption(QAbstractSocket::KeepAliveOption, true); emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort()); // TokenBucket to avoid sending too much at once _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay) _burstSize = 5; _tokenBucket = _burstSize; // init with a full bucket _tokenBucketTimer.start(_messageDelay); if (networkInfo().useSasl) { putRawLine(serverEncode(QString("CAP REQ :sasl"))); } if (!server.password.isEmpty()) { putRawLine(serverEncode(QString("PASS %1").arg(server.password))); } QString nick; if (identity->nicks().isEmpty()) { nick = "quassel"; qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id(); } else { nick = identity->nicks()[0]; } putRawLine(serverEncode(QString("NICK :%1").arg(nick))); putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName()))); } void CoreNetwork::socketDisconnected() { disablePingTimeout(); _msgQueue.clear(); _autoWhoCycleTimer.stop(); _autoWhoTimer.stop(); _autoWhoQueue.clear(); _autoWhoPending.clear(); _socketCloseTimer.stop(); _tokenBucketTimer.stop(); IrcUser *me_ = me(); if (me_) { foreach(QString channel, me_->channels()) displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask()); } setConnected(false); emit disconnected(networkId()); emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort()); if (_quitRequested) { _quitRequested = false; setConnectionState(Network::Disconnected); Core::setNetworkConnected(userId(), networkId(), false); } else if (_autoReconnectCount != 0) { setConnectionState(Network::Reconnecting); if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries()) doAutoReconnect(); // first try is immediate else _autoReconnectTimer.start(); } } void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) { Network::ConnectionState state; switch (socketState) { case QAbstractSocket::UnconnectedState: state = Network::Disconnected; break; case QAbstractSocket::HostLookupState: case QAbstractSocket::ConnectingState: state = Network::Connecting; break; case QAbstractSocket::ConnectedState: state = Network::Initializing; break; case QAbstractSocket::ClosingState: state = Network::Disconnecting; break; default: state = Network::Disconnected; } setConnectionState(state); } void CoreNetwork::networkInitialized() { setConnectionState(Network::Initialized); setConnected(true); _quitRequested = false; if (useAutoReconnect()) { // reset counter _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries(); } // restore away state QString awayMsg = Core::awayMessage(userId(), networkId()); if (!awayMsg.isEmpty()) userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId())); sendPerform(); _sendPings = true; if (networkConfig()->autoWhoEnabled()) { _autoWhoCycleTimer.start(); _autoWhoTimer.start(); startAutoWhoCycle(); // FIXME wait for autojoin to be completed } Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer Core::setNetworkConnected(userId(), networkId(), true); } void CoreNetwork::sendPerform() { BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId()); // do auto identify if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) { userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword())); } // restore old user modes if server default mode is set. IrcUser *me_ = me(); if (me_) { if (!me_->userModes().isEmpty()) { restoreUserModes(); } else { connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes())); connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes())); } } // send perform list foreach(QString line, perform()) { if (!line.isEmpty()) userInput(statusBuf, line); } // rejoin channels we've been in if (rejoinChannels()) { QStringList channels, keys; foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) { QString key = channelKey(chan); if (!key.isEmpty()) { channels.prepend(chan); keys.prepend(key); } else { channels.append(chan); } } QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed(); if (!joinString.isEmpty()) userInputHandler()->handleJoin(statusBuf, joinString); } } void CoreNetwork::restoreUserModes() { IrcUser *me_ = me(); Q_ASSERT(me_); disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes())); disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes())); QString modesDelta = Core::userModes(userId(), networkId()); QString currentModes = me_->userModes(); QString addModes, removeModes; if (modesDelta.contains('-')) { addModes = modesDelta.section('-', 0, 0); removeModes = modesDelta.section('-', 1); } else { addModes = modesDelta; } addModes.remove(QRegExp(QString("[%1]").arg(currentModes))); if (currentModes.isEmpty()) removeModes = QString(); else removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes))); if (addModes.isEmpty() && removeModes.isEmpty()) return; if (!addModes.isEmpty()) addModes = '+' + addModes; if (!removeModes.isEmpty()) removeModes = '-' + removeModes; // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes))); } void CoreNetwork::updateIssuedModes(const QString &requestedModes) { QString addModes; QString removeModes; bool addMode = true; for (int i = 0; i < requestedModes.length(); i++) { if (requestedModes[i] == '+') { addMode = true; continue; } if (requestedModes[i] == '-') { addMode = false; continue; } if (addMode) { addModes += requestedModes[i]; } else { removeModes += requestedModes[i]; } } QString addModesOld = _requestedUserModes.section('-', 0, 0); QString removeModesOld = _requestedUserModes.section('-', 1); addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update addModes += addModesOld; removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update removeModes += removeModesOld; _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes); } void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes) { QString persistentUserModes = Core::userModes(userId(), networkId()); QString requestedAdd = _requestedUserModes.section('-', 0, 0); QString requestedRemove = _requestedUserModes.section('-', 1); QString persistentAdd, persistentRemove; if (persistentUserModes.contains('-')) { persistentAdd = persistentUserModes.section('-', 0, 0); persistentRemove = persistentUserModes.section('-', 1); } else { persistentAdd = persistentUserModes; } // remove modes we didn't issue if (requestedAdd.isEmpty()) addModes = QString(); else addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd))); if (requestedRemove.isEmpty()) removeModes = QString(); else removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove))); // deduplicate persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes))); persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes))); // update persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes))); persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes))); // update issued mode list requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes))); requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes))); _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove); persistentAdd += addModes; persistentRemove += removeModes; Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove)); } void CoreNetwork::resetPersistentModes() { _requestedUserModes = QString('-'); Core::setUserModes(userId(), networkId(), QString()); } void CoreNetwork::setUseAutoReconnect(bool use) { Network::setUseAutoReconnect(use); if (!use) _autoReconnectTimer.stop(); } void CoreNetwork::setAutoReconnectInterval(quint32 interval) { Network::setAutoReconnectInterval(interval); _autoReconnectTimer.setInterval(interval * 1000); } void CoreNetwork::setAutoReconnectRetries(quint16 retries) { Network::setAutoReconnectRetries(retries); if (_autoReconnectCount != 0) { if (unlimitedReconnectRetries()) _autoReconnectCount = -1; else _autoReconnectCount = autoReconnectRetries(); } } void CoreNetwork::doAutoReconnect() { if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) { qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!"; return; } if (_autoReconnectCount > 0 || _autoReconnectCount == -1) _autoReconnectCount--; // -2 means we delay the next reconnect connectToIrc(true); } void CoreNetwork::sendPing() { uint now = QDateTime::currentDateTime().toTime_t(); if (_pingCount != 0) { qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings." << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite(); } if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) { // the second check compares the actual elapsed time since the last ping and the pingTimer interval // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked // and unable to even handle a ping answer. So we ignore those misses. disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */); } else { _lastPingTime = now; _pingCount++; // Don't send pings until the network is initialized if(_sendPings) userInputHandler()->handlePing(BufferInfo(), QString()); } } void CoreNetwork::enablePingTimeout(bool enable) { if (!enable) disablePingTimeout(); else { resetPingTimeout(); if (networkConfig()->pingTimeoutEnabled()) _pingTimer.start(); } } void CoreNetwork::disablePingTimeout() { _pingTimer.stop(); _sendPings = false; resetPingTimeout(); } void CoreNetwork::setPingInterval(int interval) { _pingTimer.setInterval(interval * 1000); } /******** AutoWHO ********/ void CoreNetwork::startAutoWhoCycle() { if (!_autoWhoQueue.isEmpty()) { _autoWhoCycleTimer.stop(); return; } _autoWhoQueue = channels(); } void CoreNetwork::setAutoWhoDelay(int delay) { _autoWhoTimer.setInterval(delay * 1000); } void CoreNetwork::setAutoWhoInterval(int interval) { _autoWhoCycleTimer.setInterval(interval * 1000); } void CoreNetwork::setAutoWhoEnabled(bool enabled) { if (enabled && isConnected() && !_autoWhoTimer.isActive()) _autoWhoTimer.start(); else if (!enabled) { _autoWhoTimer.stop(); _autoWhoCycleTimer.stop(); } } void CoreNetwork::sendAutoWho() { // Don't send autowho if there are still some pending if (_autoWhoPending.count()) return; while (!_autoWhoQueue.isEmpty()) { QString chan = _autoWhoQueue.takeFirst(); IrcChannel *ircchan = ircChannel(chan); if (!ircchan) continue; if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()) continue; _autoWhoPending[chan]++; putRawLine("WHO " + serverEncode(chan)); break; } if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) { // Timer was stopped, means a new cycle is due immediately _autoWhoCycleTimer.start(); startAutoWhoCycle(); } } #ifdef HAVE_SSL void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) { Q_UNUSED(sslErrors) socket.ignoreSslErrors(); // TODO errorhandling } #endif // HAVE_SSL void CoreNetwork::fillBucketAndProcessQueue() { if (_tokenBucket < _burstSize) { _tokenBucket++; } while (_msgQueue.size() > 0 && _tokenBucket > 0) { writeToSocket(_msgQueue.takeFirst()); } } void CoreNetwork::writeToSocket(const QByteArray &data) { socket.write(data); socket.write("\r\n"); _tokenBucket--; } Network::Server CoreNetwork::usedServer() const { if (_lastUsedServerIndex < serverList().count()) return serverList()[_lastUsedServerIndex]; if (!serverList().isEmpty()) return serverList()[0]; return Network::Server(); } void CoreNetwork::requestConnect() const { if (connectionState() != Disconnected) { qWarning() << "Requesting connect while already being connected!"; return; } QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection); } void CoreNetwork::requestDisconnect() const { if (connectionState() == Disconnected) { qWarning() << "Requesting disconnect while not being connected!"; return; } userInputHandler()->handleQuit(BufferInfo(), QString()); } void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) { Network::Server currentServer = usedServer(); setNetworkInfo(info); Core::updateNetwork(coreSession()->user(), info); // the order of the servers might have changed, // so we try to find the previously used server _lastUsedServerIndex = 0; for (int i = 0; i < serverList().count(); i++) { Network::Server server = serverList()[i]; if (server.host == currentServer.host && server.port == currentServer.port) { _lastUsedServerIndex = i; break; } } }
./CrossVul/dataset_final_sorted/CWE-399/cpp/bad_1539_2
crossvul-cpp_data_bad_1539_6
/*************************************************************************** * Copyright (C) 2005-2015 by the Quassel Project * * devel@quassel-irc.org * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) version 3. * * * * 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 "ctcpparser.h" #include "corenetworkconfig.h" #include "coresession.h" #include "ctcpevent.h" #include "messageevent.h" #include "coreuserinputhandler.h" const QByteArray XDELIM = "\001"; CtcpParser::CtcpParser(CoreSession *coreSession, QObject *parent) : QObject(parent), _coreSession(coreSession) { QByteArray MQUOTE = QByteArray("\020"); _ctcpMDequoteHash[MQUOTE + '0'] = QByteArray(1, '\000'); _ctcpMDequoteHash[MQUOTE + 'n'] = QByteArray(1, '\n'); _ctcpMDequoteHash[MQUOTE + 'r'] = QByteArray(1, '\r'); _ctcpMDequoteHash[MQUOTE + MQUOTE] = MQUOTE; setStandardCtcp(_coreSession->networkConfig()->standardCtcp()); connect(_coreSession->networkConfig(), SIGNAL(standardCtcpSet(bool)), this, SLOT(setStandardCtcp(bool))); connect(this, SIGNAL(newEvent(Event *)), _coreSession->eventManager(), SLOT(postEvent(Event *))); } void CtcpParser::setStandardCtcp(bool enabled) { QByteArray XQUOTE = QByteArray("\134"); if (enabled) _ctcpXDelimDequoteHash[XQUOTE + XQUOTE] = XQUOTE; else _ctcpXDelimDequoteHash.remove(XQUOTE + XQUOTE); _ctcpXDelimDequoteHash[XQUOTE + QByteArray("a")] = XDELIM; } void CtcpParser::displayMsg(NetworkEvent *event, Message::Type msgType, const QString &msg, const QString &sender, const QString &target, Message::Flags msgFlags) { if (event->testFlag(EventManager::Silent)) return; MessageEvent *msgEvent = new MessageEvent(msgType, event->network(), msg, sender, target, msgFlags); msgEvent->setTimestamp(event->timestamp()); emit newEvent(msgEvent); } QByteArray CtcpParser::lowLevelQuote(const QByteArray &message) { QByteArray quotedMessage = message; QHash<QByteArray, QByteArray> quoteHash = _ctcpMDequoteHash; QByteArray MQUOTE = QByteArray("\020"); quoteHash.remove(MQUOTE + MQUOTE); quotedMessage.replace(MQUOTE, MQUOTE + MQUOTE); QHash<QByteArray, QByteArray>::const_iterator quoteIter = quoteHash.constBegin(); while (quoteIter != quoteHash.constEnd()) { quotedMessage.replace(quoteIter.value(), quoteIter.key()); quoteIter++; } return quotedMessage; } QByteArray CtcpParser::lowLevelDequote(const QByteArray &message) { QByteArray dequotedMessage; QByteArray messagepart; QHash<QByteArray, QByteArray>::iterator ctcpquote; // copy dequote Message for (int i = 0; i < message.size(); i++) { messagepart = message.mid(i, 1); if (i+1 < message.size()) { for (ctcpquote = _ctcpMDequoteHash.begin(); ctcpquote != _ctcpMDequoteHash.end(); ++ctcpquote) { if (message.mid(i, 2) == ctcpquote.key()) { messagepart = ctcpquote.value(); ++i; break; } } } dequotedMessage += messagepart; } return dequotedMessage; } QByteArray CtcpParser::xdelimQuote(const QByteArray &message) { QByteArray quotedMessage = message; QHash<QByteArray, QByteArray>::const_iterator quoteIter = _ctcpXDelimDequoteHash.constBegin(); while (quoteIter != _ctcpXDelimDequoteHash.constEnd()) { quotedMessage.replace(quoteIter.value(), quoteIter.key()); quoteIter++; } return quotedMessage; } QByteArray CtcpParser::xdelimDequote(const QByteArray &message) { QByteArray dequotedMessage; QByteArray messagepart; QHash<QByteArray, QByteArray>::iterator xdelimquote; for (int i = 0; i < message.size(); i++) { messagepart = message.mid(i, 1); if (i+1 < message.size()) { for (xdelimquote = _ctcpXDelimDequoteHash.begin(); xdelimquote != _ctcpXDelimDequoteHash.end(); ++xdelimquote) { if (message.mid(i, 2) == xdelimquote.key()) { messagepart = xdelimquote.value(); i++; break; } } } dequotedMessage += messagepart; } return dequotedMessage; } void CtcpParser::processIrcEventRawNotice(IrcEventRawMessage *event) { parse(event, Message::Notice); } void CtcpParser::processIrcEventRawPrivmsg(IrcEventRawMessage *event) { parse(event, Message::Plain); } void CtcpParser::parse(IrcEventRawMessage *e, Message::Type messagetype) { //lowlevel message dequote QByteArray dequotedMessage = lowLevelDequote(e->rawMessage()); CtcpEvent::CtcpType ctcptype = e->type() == EventManager::IrcEventRawNotice ? CtcpEvent::Reply : CtcpEvent::Query; Message::Flags flags = (ctcptype == CtcpEvent::Reply && !e->network()->isChannelName(e->target())) ? Message::Redirected : Message::None; if (coreSession()->networkConfig()->standardCtcp()) parseStandard(e, messagetype, dequotedMessage, ctcptype, flags); else parseSimple(e, messagetype, dequotedMessage, ctcptype, flags); } // only accept CTCPs in their simplest form, i.e. one ctcp, from start to // end, no text around it; not as per the 'specs', but makes people happier void CtcpParser::parseSimple(IrcEventRawMessage *e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags) { if (dequotedMessage.count(XDELIM) != 2 || dequotedMessage[0] != '\001' || dequotedMessage[dequotedMessage.count() -1] != '\001') { displayMsg(e, messagetype, targetDecode(e, dequotedMessage), e->prefix(), e->target(), flags); } else { int spacePos = -1; QString ctcpcmd, ctcpparam; QByteArray ctcp = xdelimDequote(dequotedMessage.mid(1, dequotedMessage.count() - 2)); spacePos = ctcp.indexOf(' '); if (spacePos != -1) { ctcpcmd = targetDecode(e, ctcp.left(spacePos)); ctcpparam = targetDecode(e, ctcp.mid(spacePos + 1)); } else { ctcpcmd = targetDecode(e, ctcp); ctcpparam = QString(); } ctcpcmd = ctcpcmd.toUpper(); // we don't want to block /me messages by the CTCP ignore list if (ctcpcmd == QLatin1String("ACTION") || !coreSession()->ignoreListManager()->ctcpMatch(e->prefix(), e->network()->networkName(), ctcpcmd)) { QUuid uuid = QUuid::createUuid(); _replies.insert(uuid, CtcpReply(coreNetwork(e), nickFromMask(e->prefix()))); CtcpEvent *event = new CtcpEvent(EventManager::CtcpEvent, e->network(), e->prefix(), e->target(), ctcptype, ctcpcmd, ctcpparam, e->timestamp(), uuid); emit newEvent(event); CtcpEvent *flushEvent = new CtcpEvent(EventManager::CtcpEventFlush, e->network(), e->prefix(), e->target(), ctcptype, "INVALID", QString(), e->timestamp(), uuid); emit newEvent(flushEvent); } } } void CtcpParser::parseStandard(IrcEventRawMessage *e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags) { QByteArray ctcp; QList<CtcpEvent *> ctcpEvents; QUuid uuid; // needed to group all replies together // extract tagged / extended data int xdelimPos = -1; int xdelimEndPos = -1; int spacePos = -1; while ((xdelimPos = dequotedMessage.indexOf(XDELIM)) != -1) { if (xdelimPos > 0) displayMsg(e, messagetype, targetDecode(e, dequotedMessage.left(xdelimPos)), e->prefix(), e->target(), flags); xdelimEndPos = dequotedMessage.indexOf(XDELIM, xdelimPos + 1); if (xdelimEndPos == -1) { // no matching end delimiter found... treat rest of the message as ctcp xdelimEndPos = dequotedMessage.count(); } ctcp = xdelimDequote(dequotedMessage.mid(xdelimPos + 1, xdelimEndPos - xdelimPos - 1)); dequotedMessage = dequotedMessage.mid(xdelimEndPos + 1); //dispatch the ctcp command QString ctcpcmd = targetDecode(e, ctcp.left(spacePos)); QString ctcpparam = targetDecode(e, ctcp.mid(spacePos + 1)); spacePos = ctcp.indexOf(' '); if (spacePos != -1) { ctcpcmd = targetDecode(e, ctcp.left(spacePos)); ctcpparam = targetDecode(e, ctcp.mid(spacePos + 1)); } else { ctcpcmd = targetDecode(e, ctcp); ctcpparam = QString(); } ctcpcmd = ctcpcmd.toUpper(); // we don't want to block /me messages by the CTCP ignore list if (ctcpcmd == QLatin1String("ACTION") || !coreSession()->ignoreListManager()->ctcpMatch(e->prefix(), e->network()->networkName(), ctcpcmd)) { if (uuid.isNull()) uuid = QUuid::createUuid(); CtcpEvent *event = new CtcpEvent(EventManager::CtcpEvent, e->network(), e->prefix(), e->target(), ctcptype, ctcpcmd, ctcpparam, e->timestamp(), uuid); ctcpEvents << event; } } if (!ctcpEvents.isEmpty()) { _replies.insert(uuid, CtcpReply(coreNetwork(e), nickFromMask(e->prefix()))); CtcpEvent *flushEvent = new CtcpEvent(EventManager::CtcpEventFlush, e->network(), e->prefix(), e->target(), ctcptype, "INVALID", QString(), e->timestamp(), uuid); ctcpEvents << flushEvent; foreach(CtcpEvent *event, ctcpEvents) { emit newEvent(event); } } if (!dequotedMessage.isEmpty()) displayMsg(e, messagetype, targetDecode(e, dequotedMessage), e->prefix(), e->target(), flags); } void CtcpParser::sendCtcpEvent(CtcpEvent *e) { CoreNetwork *net = coreNetwork(e); if (e->type() == EventManager::CtcpEvent) { QByteArray quotedReply; QString bufname = nickFromMask(e->prefix()); if (e->ctcpType() == CtcpEvent::Query && !e->reply().isNull()) { if (_replies.contains(e->uuid())) _replies[e->uuid()].replies << lowLevelQuote(pack(net->serverEncode(e->ctcpCmd()), net->userEncode(bufname, e->reply()))); else // reply not caused by a request processed in here, so send it off immediately reply(net, bufname, e->ctcpCmd(), e->reply()); } } else if (e->type() == EventManager::CtcpEventFlush && _replies.contains(e->uuid())) { CtcpReply reply = _replies.take(e->uuid()); if (reply.replies.count()) packedReply(net, reply.bufferName, reply.replies); } } QByteArray CtcpParser::pack(const QByteArray &ctcpTag, const QByteArray &message) { if (message.isEmpty()) return XDELIM + ctcpTag + XDELIM; return XDELIM + ctcpTag + ' ' + xdelimQuote(message) + XDELIM; } void CtcpParser::query(CoreNetwork *net, const QString &bufname, const QString &ctcpTag, const QString &message) { QList<QByteArray> params; params << net->serverEncode(bufname) << lowLevelQuote(pack(net->serverEncode(ctcpTag), net->userEncode(bufname, message))); static const char *splitter = " .,-!?"; int maxSplitPos = message.count(); int splitPos = maxSplitPos; int overrun = net->userInputHandler()->lastParamOverrun("PRIVMSG", params); if (overrun) { maxSplitPos = message.count() - overrun -2; splitPos = -1; for (const char *splitChar = splitter; *splitChar != 0; splitChar++) { splitPos = qMax(splitPos, message.lastIndexOf(*splitChar, maxSplitPos) + 1); // keep split char on old line } if (splitPos <= 0 || splitPos > maxSplitPos) splitPos = maxSplitPos; params = params.mid(0, 1) << lowLevelQuote(pack(net->serverEncode(ctcpTag), net->userEncode(bufname, message.left(splitPos)))); } net->putCmd("PRIVMSG", params); if (splitPos < message.count()) query(net, bufname, ctcpTag, message.mid(splitPos)); } void CtcpParser::reply(CoreNetwork *net, const QString &bufname, const QString &ctcpTag, const QString &message) { QList<QByteArray> params; params << net->serverEncode(bufname) << lowLevelQuote(pack(net->serverEncode(ctcpTag), net->userEncode(bufname, message))); net->putCmd("NOTICE", params); } void CtcpParser::packedReply(CoreNetwork *net, const QString &bufname, const QList<QByteArray> &replies) { QList<QByteArray> params; int answerSize = 0; for (int i = 0; i < replies.count(); i++) { answerSize += replies.at(i).size(); } QByteArray quotedReply; quotedReply.reserve(answerSize); for (int i = 0; i < replies.count(); i++) { quotedReply.append(replies.at(i)); } params << net->serverEncode(bufname) << quotedReply; // FIXME user proper event net->putCmd("NOTICE", params); }
./CrossVul/dataset_final_sorted/CWE-399/cpp/bad_1539_6
crossvul-cpp_data_good_3854_0
/* +------------------------------------+ * | Inspire Internet Relay Chat Daemon | * +------------------------------------+ * * InspIRCd: (C) 2002-2010 InspIRCd Development Team * See: http://wiki.inspircd.org/Credits * * This program is free but copyrighted software; see * the file COPYING for details. * * --------------------------------------------------- */ /* $Core */ /* dns.cpp - Nonblocking DNS functions. Very very loosely based on the firedns library, Copyright (C) 2002 Ian Gulliver. This file is no longer anything like firedns, there are many major differences between this code and the original. Please do not assume that firedns works like this, looks like this, walks like this or tastes like this. */ #ifndef WIN32 #include <sys/types.h> #include <sys/socket.h> #include <errno.h> #include <netinet/in.h> #include <arpa/inet.h> #else #include "inspircd_win32wrapper.h" #endif #include "inspircd.h" #include "socketengine.h" #include "configreader.h" #include "socket.h" #define DN_COMP_BITMASK 0xC000 /* highest 6 bits in a DN label header */ /** Masks to mask off the responses we get from the DNSRequest methods */ enum QueryInfo { ERROR_MASK = 0x10000 /* Result is an error */ }; /** Flags which can be ORed into a request or reply for different meanings */ enum QueryFlags { FLAGS_MASK_RD = 0x01, /* Recursive */ FLAGS_MASK_TC = 0x02, FLAGS_MASK_AA = 0x04, /* Authoritative */ FLAGS_MASK_OPCODE = 0x78, FLAGS_MASK_QR = 0x80, FLAGS_MASK_RCODE = 0x0F, /* Request */ FLAGS_MASK_Z = 0x70, FLAGS_MASK_RA = 0x80 }; /** Represents a dns resource record (rr) */ struct ResourceRecord { QueryType type; /* Record type */ unsigned int rr_class; /* Record class */ unsigned long ttl; /* Time to live */ unsigned int rdlength; /* Record length */ }; /** Represents a dns request/reply header, and its payload as opaque data. */ class DNSHeader { public: unsigned char id[2]; /* Request id */ unsigned int flags1; /* Flags */ unsigned int flags2; /* Flags */ unsigned int qdcount; unsigned int ancount; /* Answer count */ unsigned int nscount; /* Nameserver count */ unsigned int arcount; unsigned char payload[512]; /* Packet payload */ }; class DNSRequest { public: unsigned char id[2]; /* Request id */ unsigned char* res; /* Result processing buffer */ unsigned int rr_class; /* Request class */ QueryType type; /* Request type */ DNS* dnsobj; /* DNS caller (where we get our FD from) */ unsigned long ttl; /* Time to live */ std::string orig; /* Original requested name/ip */ DNSRequest(DNS* dns, int id, const std::string &original); ~DNSRequest(); DNSInfo ResultIsReady(DNSHeader &h, unsigned length); int SendRequests(const DNSHeader *header, const int length, QueryType qt); }; class CacheTimer : public Timer { private: DNS* dns; public: CacheTimer(DNS* thisdns) : Timer(3600, ServerInstance->Time(), true), dns(thisdns) { } virtual void Tick(time_t) { dns->PruneCache(); } }; class RequestTimeout : public Timer { DNSRequest* watch; int watchid; public: RequestTimeout(unsigned long n, DNSRequest* watching, int id) : Timer(n, ServerInstance->Time()), watch(watching), watchid(id) { } ~RequestTimeout() { if (ServerInstance->Res) Tick(0); } void Tick(time_t) { if (ServerInstance->Res->requests[watchid] == watch) { /* Still exists, whack it */ if (ServerInstance->Res->Classes[watchid]) { ServerInstance->Res->Classes[watchid]->OnError(RESOLVER_TIMEOUT, "Request timed out"); delete ServerInstance->Res->Classes[watchid]; ServerInstance->Res->Classes[watchid] = NULL; } ServerInstance->Res->requests[watchid] = NULL; delete watch; } } }; CachedQuery::CachedQuery(const std::string &res, unsigned int ttl) : data(res) { expires = ServerInstance->Time() + ttl; } int CachedQuery::CalcTTLRemaining() { int n = expires - ServerInstance->Time(); return (n < 0 ? 0 : n); } /* Allocate the processing buffer */ DNSRequest::DNSRequest(DNS* dns, int rid, const std::string &original) : dnsobj(dns) { /* hardening against overflow here: make our work buffer twice the theoretical * maximum size so that hostile input doesn't screw us over. */ res = new unsigned char[sizeof(DNSHeader) * 2]; *res = 0; orig = original; RequestTimeout* RT = new RequestTimeout(ServerInstance->Config->dns_timeout ? ServerInstance->Config->dns_timeout : 5, this, rid); ServerInstance->Timers->AddTimer(RT); /* The timer manager frees this */ } /* Deallocate the processing buffer */ DNSRequest::~DNSRequest() { delete[] res; } /** Fill a ResourceRecord class based on raw data input */ inline void DNS::FillResourceRecord(ResourceRecord* rr, const unsigned char *input) { rr->type = (QueryType)((input[0] << 8) + input[1]); rr->rr_class = (input[2] << 8) + input[3]; rr->ttl = (input[4] << 24) + (input[5] << 16) + (input[6] << 8) + input[7]; rr->rdlength = (input[8] << 8) + input[9]; } /** Fill a DNSHeader class based on raw data input of a given length */ inline void DNS::FillHeader(DNSHeader *header, const unsigned char *input, const int length) { header->id[0] = input[0]; header->id[1] = input[1]; header->flags1 = input[2]; header->flags2 = input[3]; header->qdcount = (input[4] << 8) + input[5]; header->ancount = (input[6] << 8) + input[7]; header->nscount = (input[8] << 8) + input[9]; header->arcount = (input[10] << 8) + input[11]; memcpy(header->payload,&input[12],length); } /** Empty a DNSHeader class out into raw data, ready for transmission */ inline void DNS::EmptyHeader(unsigned char *output, const DNSHeader *header, const int length) { output[0] = header->id[0]; output[1] = header->id[1]; output[2] = header->flags1; output[3] = header->flags2; output[4] = header->qdcount >> 8; output[5] = header->qdcount & 0xFF; output[6] = header->ancount >> 8; output[7] = header->ancount & 0xFF; output[8] = header->nscount >> 8; output[9] = header->nscount & 0xFF; output[10] = header->arcount >> 8; output[11] = header->arcount & 0xFF; memcpy(&output[12],header->payload,length); } /** Send requests we have previously built down the UDP socket */ int DNSRequest::SendRequests(const DNSHeader *header, const int length, QueryType qt) { ServerInstance->Logs->Log("RESOLVER", DEBUG,"DNSRequest::SendRequests"); unsigned char payload[sizeof(DNSHeader)]; this->rr_class = 1; this->type = qt; DNS::EmptyHeader(payload,header,length); if (ServerInstance->SE->SendTo(dnsobj, payload, length + 12, 0, &(dnsobj->myserver.sa), sa_size(dnsobj->myserver)) != length+12) return -1; ServerInstance->Logs->Log("RESOLVER",DEBUG,"Sent OK"); return 0; } /** Add a query with a predefined header, and allocate an ID for it. */ DNSRequest* DNS::AddQuery(DNSHeader *header, int &id, const char* original) { /* Is the DNS connection down? */ if (this->GetFd() == -1) return NULL; /* Create an id */ do { id = ServerInstance->GenRandomInt(DNS::MAX_REQUEST_ID); } while (requests[id]); DNSRequest* req = new DNSRequest(this, id, original); header->id[0] = req->id[0] = id >> 8; header->id[1] = req->id[1] = id & 0xFF; header->flags1 = FLAGS_MASK_RD; header->flags2 = 0; header->qdcount = 1; header->ancount = 0; header->nscount = 0; header->arcount = 0; /* At this point we already know the id doesnt exist, * so there needs to be no second check for the ::end() */ requests[id] = req; /* According to the C++ spec, new never returns NULL. */ return req; } int DNS::ClearCache() { /* This ensures the buckets are reset to sane levels */ int rv = this->cache->size(); delete this->cache; this->cache = new dnscache(); return rv; } int DNS::PruneCache() { int n = 0; dnscache* newcache = new dnscache(); for (dnscache::iterator i = this->cache->begin(); i != this->cache->end(); i++) /* Dont include expired items (theres no point) */ if (i->second.CalcTTLRemaining()) newcache->insert(*i); else n++; delete this->cache; this->cache = newcache; return n; } void DNS::Rehash() { if (this->GetFd() > -1) { ServerInstance->SE->DelFd(this); ServerInstance->SE->Shutdown(this, 2); ServerInstance->SE->Close(this); this->SetFd(-1); /* Rehash the cache */ this->PruneCache(); } else { /* Create initial dns cache */ this->cache = new dnscache(); } irc::sockets::aptosa(ServerInstance->Config->DNSServer, DNS::QUERY_PORT, myserver); /* Initialize mastersocket */ int s = socket(myserver.sa.sa_family, SOCK_DGRAM, 0); this->SetFd(s); /* Have we got a socket and is it nonblocking? */ if (this->GetFd() != -1) { ServerInstance->SE->SetReuse(s); ServerInstance->SE->NonBlocking(s); irc::sockets::sockaddrs bindto; memset(&bindto, 0, sizeof(bindto)); bindto.sa.sa_family = myserver.sa.sa_family; if (ServerInstance->SE->Bind(this->GetFd(), bindto) < 0) { /* Failed to bind */ ServerInstance->Logs->Log("RESOLVER",SPARSE,"Error binding dns socket - hostnames will NOT resolve"); ServerInstance->SE->Shutdown(this, 2); ServerInstance->SE->Close(this); this->SetFd(-1); } else if (!ServerInstance->SE->AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE)) { ServerInstance->Logs->Log("RESOLVER",SPARSE,"Internal error starting DNS - hostnames will NOT resolve."); ServerInstance->SE->Shutdown(this, 2); ServerInstance->SE->Close(this); this->SetFd(-1); } } else { ServerInstance->Logs->Log("RESOLVER",SPARSE,"Error creating DNS socket - hostnames will NOT resolve"); } } /** Initialise the DNS UDP socket so that we can send requests */ DNS::DNS() { ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::DNS"); /* Clear the Resolver class table */ memset(Classes,0,sizeof(Classes)); /* Clear the requests class table */ memset(requests,0,sizeof(requests)); /* Set the id of the next request to 0 */ currid = 0; /* DNS::Rehash() sets this to a valid ptr */ this->cache = NULL; /* Again, DNS::Rehash() sets this to a * valid value */ this->SetFd(-1); /* Actually read the settings */ this->Rehash(); this->PruneTimer = new CacheTimer(this); ServerInstance->Timers->AddTimer(this->PruneTimer); } /** Build a payload to be placed after the header, based upon input data, a resource type, a class and a pointer to a buffer */ int DNS::MakePayload(const char * const name, const QueryType rr, const unsigned short rr_class, unsigned char * const payload) { short payloadpos = 0; const char* tempchr, *tempchr2 = name; unsigned short length; /* split name up into labels, create query */ while ((tempchr = strchr(tempchr2,'.')) != NULL) { length = tempchr - tempchr2; if (payloadpos + length + 1 > 507) return -1; payload[payloadpos++] = length; memcpy(&payload[payloadpos],tempchr2,length); payloadpos += length; tempchr2 = &tempchr[1]; } length = strlen(tempchr2); if (length) { if (payloadpos + length + 2 > 507) return -1; payload[payloadpos++] = length; memcpy(&payload[payloadpos],tempchr2,length); payloadpos += length; payload[payloadpos++] = 0; } if (payloadpos > 508) return -1; length = htons(rr); memcpy(&payload[payloadpos],&length,2); length = htons(rr_class); memcpy(&payload[payloadpos + 2],&length,2); return payloadpos + 4; } /** Start lookup of an hostname to an IP address */ int DNS::GetIP(const char *name) { DNSHeader h; int id; int length; if ((length = this->MakePayload(name, DNS_QUERY_A, 1, (unsigned char*)&h.payload)) == -1) return -1; DNSRequest* req = this->AddQuery(&h, id, name); if ((!req) || (req->SendRequests(&h, length, DNS_QUERY_A) == -1)) return -1; return id; } /** Start lookup of an hostname to an IPv6 address */ int DNS::GetIP6(const char *name) { DNSHeader h; int id; int length; if ((length = this->MakePayload(name, DNS_QUERY_AAAA, 1, (unsigned char*)&h.payload)) == -1) return -1; DNSRequest* req = this->AddQuery(&h, id, name); if ((!req) || (req->SendRequests(&h, length, DNS_QUERY_AAAA) == -1)) return -1; return id; } /** Start lookup of a cname to another name */ int DNS::GetCName(const char *alias) { DNSHeader h; int id; int length; if ((length = this->MakePayload(alias, DNS_QUERY_CNAME, 1, (unsigned char*)&h.payload)) == -1) return -1; DNSRequest* req = this->AddQuery(&h, id, alias); if ((!req) || (req->SendRequests(&h, length, DNS_QUERY_CNAME) == -1)) return -1; return id; } /** Start lookup of an IP address to a hostname */ int DNS::GetNameForce(const char *ip, ForceProtocol fp) { char query[128]; DNSHeader h; int id; int length; if (fp == PROTOCOL_IPV6) { in6_addr i; if (inet_pton(AF_INET6, ip, &i) > 0) { DNS::MakeIP6Int(query, &i); } else { ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce IPv6 bad format for '%s'", ip); /* Invalid IP address */ return -1; } } else { in_addr i; if (inet_aton(ip, &i)) { unsigned char* c = (unsigned char*)&i.s_addr; sprintf(query,"%d.%d.%d.%d.in-addr.arpa",c[3],c[2],c[1],c[0]); } else { ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce IPv4 bad format for '%s'", ip); /* Invalid IP address */ return -1; } } length = this->MakePayload(query, DNS_QUERY_PTR, 1, (unsigned char*)&h.payload); if (length == -1) { ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce can't query '%s' using '%s' because it's too long", ip, query); return -1; } DNSRequest* req = this->AddQuery(&h, id, ip); if (!req) { ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce can't add query (resolver down?)"); return -1; } if (req->SendRequests(&h, length, DNS_QUERY_PTR) == -1) { ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS::GetNameForce can't send (firewall?)"); return -1; } return id; } /** Build an ipv6 reverse domain from an in6_addr */ void DNS::MakeIP6Int(char* query, const in6_addr *ip) { const char* hex = "0123456789abcdef"; for (int index = 31; index >= 0; index--) /* for() loop steps twice per byte */ { if (index % 2) /* low nibble */ *query++ = hex[ip->s6_addr[index / 2] & 0x0F]; else /* high nibble */ *query++ = hex[(ip->s6_addr[index / 2] & 0xF0) >> 4]; *query++ = '.'; /* Seperator */ } strcpy(query,"ip6.arpa"); /* Suffix the string */ } /** Return the next id which is ready, and the result attached to it */ DNSResult DNS::GetResult() { /* Fetch dns query response and decide where it belongs */ DNSHeader header; DNSRequest *req; unsigned char buffer[sizeof(DNSHeader)]; irc::sockets::sockaddrs from; memset(&from, 0, sizeof(from)); socklen_t x = sizeof(from); int length = ServerInstance->SE->RecvFrom(this, (char*)buffer, sizeof(DNSHeader), 0, &from.sa, &x); /* Did we get the whole header? */ if (length < 12) { ServerInstance->Logs->Log("RESOLVER",DEBUG,"GetResult didn't get a full packet (len=%d)", length); /* Nope - something screwed up. */ return DNSResult(-1,"",0,""); } /* Check wether the reply came from a different DNS * server to the one we sent it to, or the source-port * is not 53. * A user could in theory still spoof dns packets anyway * but this is less trivial than just sending garbage * to the server, which is possible without this check. * * -- Thanks jilles for pointing this one out. */ if (from != myserver) { ServerInstance->Logs->Log("RESOLVER",DEBUG,"Got a result from the wrong server! Bad NAT or DNS forging attempt? '%s' != '%s'", from.str().c_str(), myserver.str().c_str()); return DNSResult(-1,"",0,""); } /* Put the read header info into a header class */ DNS::FillHeader(&header,buffer,length - 12); /* Get the id of this request. * Its a 16 bit value stored in two char's, * so we use logic shifts to create the value. */ unsigned long this_id = header.id[1] + (header.id[0] << 8); /* Do we have a pending request matching this id? */ if (!requests[this_id]) { /* Somehow we got a DNS response for a request we never made... */ ServerInstance->Logs->Log("RESOLVER",DEBUG,"Hmm, got a result that we didn't ask for (id=%lx). Ignoring.", this_id); return DNSResult(-1,"",0,""); } else { /* Remove the query from the list of pending queries */ req = requests[this_id]; requests[this_id] = NULL; } /* Inform the DNSRequest class that it has a result to be read. * When its finished it will return a DNSInfo which is a pair of * unsigned char* resource record data, and an error message. */ DNSInfo data = req->ResultIsReady(header, length); std::string resultstr; /* Check if we got a result, if we didnt, its an error */ if (data.first == NULL) { /* An error. * Mask the ID with the value of ERROR_MASK, so that * the dns_deal_with_classes() function knows that its * an error response and needs to be treated uniquely. * Put the error message in the second field. */ std::string ro = req->orig; delete req; return DNSResult(this_id | ERROR_MASK, data.second, 0, ro); } else { unsigned long ttl = req->ttl; char formatted[128]; /* Forward lookups come back as binary data. We must format them into ascii */ switch (req->type) { case DNS_QUERY_A: snprintf(formatted,16,"%u.%u.%u.%u",data.first[0],data.first[1],data.first[2],data.first[3]); resultstr = formatted; break; case DNS_QUERY_AAAA: { inet_ntop(AF_INET6, data.first, formatted, sizeof(formatted)); char* c = strstr(formatted,":0:"); if (c != NULL) { memmove(c+1,c+2,strlen(c+2) + 1); c += 2; while (memcmp(c,"0:",2) == 0) memmove(c,c+2,strlen(c+2) + 1); if (memcmp(c,"0",2) == 0) *c = 0; if (memcmp(formatted,"0::",3) == 0) memmove(formatted,formatted + 1, strlen(formatted + 1) + 1); } resultstr = formatted; /* Special case. Sending ::1 around between servers * and to clients is dangerous, because the : on the * start makes the client or server interpret the IP * as the last parameter on the line with a value ":1". */ if (*formatted == ':') resultstr.insert(0, "0"); } break; case DNS_QUERY_CNAME: /* Identical handling to PTR */ case DNS_QUERY_PTR: /* Reverse lookups just come back as char* */ resultstr = std::string((const char*)data.first); break; default: break; } /* Build the reply with the id and hostname/ip in it */ std::string ro = req->orig; delete req; return DNSResult(this_id,resultstr,ttl,ro); } } /** A result is ready, process it */ DNSInfo DNSRequest::ResultIsReady(DNSHeader &header, unsigned length) { unsigned i = 0, o; int q = 0; int curanswer; ResourceRecord rr; unsigned short ptr; /* This is just to keep _FORTIFY_SOURCE happy */ rr.type = DNS_QUERY_NONE; rr.rdlength = 0; rr.ttl = 1; /* GCC is a whiney bastard -- see the XXX below. */ rr.rr_class = 0; /* Same for VC++ */ if (!(header.flags1 & FLAGS_MASK_QR)) return std::make_pair((unsigned char*)NULL,"Not a query result"); if (header.flags1 & FLAGS_MASK_OPCODE) return std::make_pair((unsigned char*)NULL,"Unexpected value in DNS reply packet"); if (header.flags2 & FLAGS_MASK_RCODE) return std::make_pair((unsigned char*)NULL,"Domain name not found"); if (header.ancount < 1) return std::make_pair((unsigned char*)NULL,"No resource records returned"); /* Subtract the length of the header from the length of the packet */ length -= 12; while ((unsigned int)q < header.qdcount && i < length) { if (header.payload[i] > 63) { i += 6; q++; } else { if (header.payload[i] == 0) { q++; i += 5; } else i += header.payload[i] + 1; } } curanswer = 0; while ((unsigned)curanswer < header.ancount) { q = 0; while (q == 0 && i < length) { if (header.payload[i] > 63) { i += 2; q = 1; } else { if (header.payload[i] == 0) { i++; q = 1; } else i += header.payload[i] + 1; /* skip length and label */ } } if (static_cast<int>(length - i) < 10) return std::make_pair((unsigned char*)NULL,"Incorrectly sized DNS reply"); /* XXX: We actually initialise 'rr' here including its ttl field */ DNS::FillResourceRecord(&rr,&header.payload[i]); i += 10; ServerInstance->Logs->Log("RESOLVER",DEBUG,"Resolver: rr.type is %d and this.type is %d rr.class %d this.class %d", rr.type, this->type, rr.rr_class, this->rr_class); if (rr.type != this->type) { curanswer++; i += rr.rdlength; continue; } if (rr.rr_class != this->rr_class) { curanswer++; i += rr.rdlength; continue; } break; } if ((unsigned int)curanswer == header.ancount) return std::make_pair((unsigned char*)NULL,"No A, AAAA or PTR type answers (" + ConvToStr(header.ancount) + " answers)"); if (i + rr.rdlength > (unsigned int)length) return std::make_pair((unsigned char*)NULL,"Resource record larger than stated"); if (rr.rdlength > 1023) return std::make_pair((unsigned char*)NULL,"Resource record too large"); this->ttl = rr.ttl; switch (rr.type) { /* * CNAME and PTR are compressed. We need to decompress them. */ case DNS_QUERY_CNAME: case DNS_QUERY_PTR: { unsigned short lowest_pos = length; o = 0; q = 0; while (q == 0 && i < length && o + 256 < 1023) { /* DN label found (byte over 63) */ if (header.payload[i] > 63) { memcpy(&ptr,&header.payload[i],2); i = ntohs(ptr); /* check that highest two bits are set. if not, we've been had */ if ((i & DN_COMP_BITMASK) != DN_COMP_BITMASK) return std::make_pair((unsigned char *) NULL, "DN label decompression header is bogus"); /* mask away the two highest bits. */ i &= ~DN_COMP_BITMASK; /* and decrease length by 12 bytes. */ i -= 12; if (i >= lowest_pos) return std::make_pair((unsigned char *) NULL, "Invalid decompression pointer"); lowest_pos = i; } else { if (header.payload[i] == 0) { q = 1; } else { res[o] = 0; if (o != 0) res[o++] = '.'; if (o + header.payload[i] > sizeof(DNSHeader)) return std::make_pair((unsigned char *) NULL, "DN label decompression is impossible -- malformed/hostile packet?"); memcpy(&res[o], &header.payload[i + 1], header.payload[i]); o += header.payload[i]; i += header.payload[i] + 1; } } } res[o] = 0; } break; case DNS_QUERY_AAAA: if (rr.rdlength != sizeof(struct in6_addr)) return std::make_pair((unsigned char *) NULL, "rr.rdlength is larger than 16 bytes for an ipv6 entry -- malformed/hostile packet?"); memcpy(res,&header.payload[i],rr.rdlength); res[rr.rdlength] = 0; break; case DNS_QUERY_A: if (rr.rdlength != sizeof(struct in_addr)) return std::make_pair((unsigned char *) NULL, "rr.rdlength is larger than 4 bytes for an ipv4 entry -- malformed/hostile packet?"); memcpy(res,&header.payload[i],rr.rdlength); res[rr.rdlength] = 0; break; default: return std::make_pair((unsigned char *) NULL, "don't know how to handle undefined type (" + ConvToStr(rr.type) + ") -- rejecting"); break; } return std::make_pair(res,"No error"); } /** Close the master socket */ DNS::~DNS() { ServerInstance->SE->Shutdown(this, 2); ServerInstance->SE->Close(this); ServerInstance->Timers->DelTimer(this->PruneTimer); if (cache) delete cache; } CachedQuery* DNS::GetCache(const std::string &source) { dnscache::iterator x = cache->find(source.c_str()); if (x != cache->end()) return &(x->second); else return NULL; } void DNS::DelCache(const std::string &source) { cache->erase(source.c_str()); } void Resolver::TriggerCachedResult() { if (CQ) OnLookupComplete(CQ->data, time_left, true); } /** High level abstraction of dns used by application at large */ Resolver::Resolver(const std::string &source, QueryType qt, bool &cached, Module* creator) : Creator(creator), input(source), querytype(qt) { ServerInstance->Logs->Log("RESOLVER",DEBUG,"Resolver::Resolver"); cached = false; CQ = ServerInstance->Res->GetCache(source); if (CQ) { time_left = CQ->CalcTTLRemaining(); if (!time_left) { ServerInstance->Res->DelCache(source); } else { cached = true; return; } } switch (querytype) { case DNS_QUERY_A: this->myid = ServerInstance->Res->GetIP(source.c_str()); break; case DNS_QUERY_PTR4: querytype = DNS_QUERY_PTR; this->myid = ServerInstance->Res->GetNameForce(source.c_str(), PROTOCOL_IPV4); break; case DNS_QUERY_PTR6: querytype = DNS_QUERY_PTR; this->myid = ServerInstance->Res->GetNameForce(source.c_str(), PROTOCOL_IPV6); break; case DNS_QUERY_AAAA: this->myid = ServerInstance->Res->GetIP6(source.c_str()); break; case DNS_QUERY_CNAME: this->myid = ServerInstance->Res->GetCName(source.c_str()); break; default: ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS request with unknown query type %d", querytype); this->myid = -1; break; } if (this->myid == -1) { throw ModuleException("Resolver: Couldn't get an id to make a request"); } else { ServerInstance->Logs->Log("RESOLVER",DEBUG,"DNS request id %d", this->myid); } } /** Called when an error occurs */ void Resolver::OnError(ResolverError, const std::string&) { /* Nothing in here */ } /** Destroy a resolver */ Resolver::~Resolver() { /* Nothing here (yet) either */ } /** Get the request id associated with this class */ int Resolver::GetId() { return this->myid; } Module* Resolver::GetCreator() { return this->Creator; } /** Process a socket read event */ void DNS::HandleEvent(EventType, int) { /* Fetch the id and result of the next available packet */ DNSResult res(0,"",0,""); res.id = 0; ServerInstance->Logs->Log("RESOLVER",DEBUG,"Handle DNS event"); res = this->GetResult(); ServerInstance->Logs->Log("RESOLVER",DEBUG,"Result id %d", res.id); /* Is there a usable request id? */ if (res.id != -1) { /* Its an error reply */ if (res.id & ERROR_MASK) { /* Mask off the error bit */ res.id -= ERROR_MASK; /* Marshall the error to the correct class */ if (Classes[res.id]) { if (ServerInstance && ServerInstance->stats) ServerInstance->stats->statsDnsBad++; Classes[res.id]->OnError(RESOLVER_NXDOMAIN, res.result); delete Classes[res.id]; Classes[res.id] = NULL; } return; } else { /* It is a non-error result, marshall the result to the correct class */ if (Classes[res.id]) { if (ServerInstance && ServerInstance->stats) ServerInstance->stats->statsDnsGood++; if (!this->GetCache(res.original.c_str())) this->cache->insert(std::make_pair(res.original.c_str(), CachedQuery(res.result, res.ttl))); Classes[res.id]->OnLookupComplete(res.result, res.ttl, false); delete Classes[res.id]; Classes[res.id] = NULL; } } if (ServerInstance && ServerInstance->stats) ServerInstance->stats->statsDns++; } } /** Add a derived Resolver to the working set */ bool DNS::AddResolverClass(Resolver* r) { ServerInstance->Logs->Log("RESOLVER",DEBUG,"AddResolverClass 0x%08lx", (unsigned long)r); /* Check the pointers validity and the id's validity */ if ((r) && (r->GetId() > -1)) { /* Check the slot isnt already occupied - * This should NEVER happen unless we have * a severely broken DNS server somewhere */ if (!Classes[r->GetId()]) { /* Set up the pointer to the class */ Classes[r->GetId()] = r; return true; } else /* Duplicate id */ return false; } else { /* Pointer or id not valid. * Free the item and return */ if (r) delete r; return false; } } void DNS::CleanResolvers(Module* module) { for (int i = 0; i < MAX_REQUEST_ID; i++) { if (Classes[i]) { if (Classes[i]->GetCreator() == module) { Classes[i]->OnError(RESOLVER_FORCEUNLOAD, "Parent module is unloading"); delete Classes[i]; Classes[i] = NULL; } } } }
./CrossVul/dataset_final_sorted/CWE-399/cpp/good_3854_0
crossvul-cpp_data_bad_1539_4
/*************************************************************************** * Copyright (C) 2005-2015 by the Quassel Project * * devel@quassel-irc.org * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) version 3. * * * * 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 "coreuserinputhandler.h" #include "util.h" #include "ctcpparser.h" #include <QRegExp> #ifdef HAVE_QCA2 # include "cipher.h" #endif CoreUserInputHandler::CoreUserInputHandler(CoreNetwork *parent) : CoreBasicHandler(parent) { } void CoreUserInputHandler::handleUserInput(const BufferInfo &bufferInfo, const QString &msg) { if (msg.isEmpty()) return; AliasManager::CommandList list = coreSession()->aliasManager().processInput(bufferInfo, msg); for (int i = 0; i < list.count(); i++) { QString cmd = list.at(i).second.section(' ', 0, 0).remove(0, 1).toUpper(); QString payload = list.at(i).second.section(' ', 1); handle(cmd, Q_ARG(BufferInfo, list.at(i).first), Q_ARG(QString, payload)); } } // ==================== // Public Slots // ==================== void CoreUserInputHandler::handleAway(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) if (msg.startsWith("-all")) { if (msg.length() == 4) { coreSession()->globalAway(); return; } Q_ASSERT(msg.length() > 4); if (msg[4] == ' ') { coreSession()->globalAway(msg.mid(5)); return; } } issueAway(msg); } void CoreUserInputHandler::issueAway(const QString &msg, bool autoCheck) { QString awayMsg = msg; IrcUser *me = network()->me(); // if there is no message supplied we have to check if we are already away or not if (autoCheck && msg.isEmpty()) { if (me && !me->isAway()) { Identity *identity = network()->identityPtr(); if (identity) { awayMsg = identity->awayReason(); } if (awayMsg.isEmpty()) { awayMsg = tr("away"); } } } if (me) me->setAwayMessage(awayMsg); putCmd("AWAY", serverEncode(awayMsg)); } void CoreUserInputHandler::handleBan(const BufferInfo &bufferInfo, const QString &msg) { banOrUnban(bufferInfo, msg, true); } void CoreUserInputHandler::handleUnban(const BufferInfo &bufferInfo, const QString &msg) { banOrUnban(bufferInfo, msg, false); } void CoreUserInputHandler::banOrUnban(const BufferInfo &bufferInfo, const QString &msg, bool ban) { QString banChannel; QString banUser; QStringList params = msg.split(" "); if (!params.isEmpty() && isChannelName(params[0])) { banChannel = params.takeFirst(); } else if (bufferInfo.type() == BufferInfo::ChannelBuffer) { banChannel = bufferInfo.bufferName(); } else { emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: channel unknown in command: /BAN %1").arg(msg)); return; } if (!params.isEmpty() && !params.contains("!") && network()->ircUser(params[0])) { IrcUser *ircuser = network()->ircUser(params[0]); // generalizedHost changes <nick> to *!ident@*.sld.tld. QString generalizedHost = ircuser->host(); if (generalizedHost.isEmpty()) { emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: host unknown in command: /BAN %1").arg(msg)); return; } static QRegExp ipAddress("\\d+\\.\\d+\\.\\d+\\.\\d+"); if (ipAddress.exactMatch(generalizedHost)) { int lastDotPos = generalizedHost.lastIndexOf('.') + 1; generalizedHost.replace(lastDotPos, generalizedHost.length() - lastDotPos, '*'); } else if (generalizedHost.lastIndexOf(".") != -1 && generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1) != -1) { int secondLastPeriodPosition = generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1); generalizedHost.replace(0, secondLastPeriodPosition, "*"); } banUser = QString("*!%1@%2").arg(ircuser->user(), generalizedHost); } else { banUser = params.join(" "); } QString banMode = ban ? "+b" : "-b"; QString banMsg = QString("MODE %1 %2 %3").arg(banChannel, banMode, banUser); emit putRawLine(serverEncode(banMsg)); } void CoreUserInputHandler::handleCtcp(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) QString nick = msg.section(' ', 0, 0); QString ctcpTag = msg.section(' ', 1, 1).toUpper(); if (ctcpTag.isEmpty()) return; QString message = msg.section(' ', 2); QString verboseMessage = tr("sending CTCP-%1 request to %2").arg(ctcpTag).arg(nick); if (ctcpTag == "PING") { message = QString::number(QDateTime::currentMSecsSinceEpoch()); } // FIXME make this a proper event coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), nick, ctcpTag, message); emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage, network()->myNick()); } void CoreUserInputHandler::handleDelkey(const BufferInfo &bufferInfo, const QString &msg) { QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName(); #ifdef HAVE_QCA2 if (!bufferInfo.isValid()) return; if (!Cipher::neededFeaturesAvailable()) { emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")); return; } QStringList parms = msg.split(' ', QString::SkipEmptyParts); if (parms.isEmpty() && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages()) parms.prepend(bufferInfo.bufferName()); if (parms.isEmpty()) { emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("[usage] /delkey <nick|channel> deletes the encryption key for nick or channel or just /delkey when in a channel or query.")); return; } QString target = parms.at(0); if (network()->cipherKey(target).isEmpty()) { emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("No key has been set for %1.").arg(target)); return; } network()->setCipherKey(target, QByteArray()); emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 has been deleted.").arg(target)); #else Q_UNUSED(msg) emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built " "with support for the Qt Cryptographic Architecture (QCA2) library. " "Contact your distributor about a Quassel package with QCA2 " "support, or rebuild Quassel with QCA2 present.")); #endif } void CoreUserInputHandler::doMode(const BufferInfo &bufferInfo, const QChar& addOrRemove, const QChar& mode, const QString &nicks) { QString m; bool isNumber; int maxModes = network()->support("MODES").toInt(&isNumber); if (!isNumber || maxModes == 0) maxModes = 1; QStringList nickList; if (nicks == "*") { // All users in channel const QList<IrcUser*> users = network()->ircChannel(bufferInfo.bufferName())->ircUsers(); foreach(IrcUser *user, users) { if ((addOrRemove == '+' && !network()->ircChannel(bufferInfo.bufferName())->userModes(user).contains(mode)) || (addOrRemove == '-' && network()->ircChannel(bufferInfo.bufferName())->userModes(user).contains(mode))) nickList.append(user->nick()); } } else { nickList = nicks.split(' ', QString::SkipEmptyParts); } if (nickList.count() == 0) return; while (!nickList.isEmpty()) { int amount = qMin(nickList.count(), maxModes); QString m = addOrRemove; for(int i = 0; i < amount; i++) m += mode; QStringList params; params << bufferInfo.bufferName() << m; for(int i = 0; i < amount; i++) params << nickList.takeFirst(); emit putCmd("MODE", serverEncode(params)); } } void CoreUserInputHandler::handleDeop(const BufferInfo &bufferInfo, const QString &nicks) { doMode(bufferInfo, '-', 'o', nicks); } void CoreUserInputHandler::handleDehalfop(const BufferInfo &bufferInfo, const QString &nicks) { doMode(bufferInfo, '-', 'h', nicks); } void CoreUserInputHandler::handleDevoice(const BufferInfo &bufferInfo, const QString &nicks) { doMode(bufferInfo, '-', 'v', nicks); } void CoreUserInputHandler::handleHalfop(const BufferInfo &bufferInfo, const QString &nicks) { doMode(bufferInfo, '+', 'h', nicks); } void CoreUserInputHandler::handleOp(const BufferInfo &bufferInfo, const QString &nicks) { doMode(bufferInfo, '+', 'o', nicks); } void CoreUserInputHandler::handleInvite(const BufferInfo &bufferInfo, const QString &msg) { QStringList params; params << msg << bufferInfo.bufferName(); emit putCmd("INVITE", serverEncode(params)); } void CoreUserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo); // trim spaces before chans or keys QString sane_msg = msg; sane_msg.replace(QRegExp(", +"), ","); QStringList params = sane_msg.trimmed().split(" "); QStringList chans = params[0].split(",", QString::SkipEmptyParts); QStringList keys; if (params.count() > 1) keys = params[1].split(","); int i; for (i = 0; i < chans.count(); i++) { if (!network()->isChannelName(chans[i])) chans[i].prepend('#'); if (i < keys.count()) { network()->addChannelKey(chans[i], keys[i]); } else { network()->removeChannelKey(chans[i]); } } static const char *cmd = "JOIN"; i = 0; QStringList joinChans, joinKeys; int slicesize = chans.count(); QList<QByteArray> encodedParams; // go through all to-be-joined channels and (re)build the join list while (i < chans.count()) { joinChans.append(chans.at(i)); if (i < keys.count()) joinKeys.append(keys.at(i)); // if the channel list we built so far either contains all requested channels or exceeds // the desired amount of channels in this slice, try to send what we have so far if (++i == chans.count() || joinChans.count() >= slicesize) { params.clear(); params.append(joinChans.join(",")); params.append(joinKeys.join(",")); encodedParams = serverEncode(params); // check if it fits in one command if (lastParamOverrun(cmd, encodedParams) == 0) { emit putCmd(cmd, encodedParams); } else if (slicesize > 1) { // back to start of slice, try again with half the amount of channels i -= slicesize; slicesize /= 2; } joinChans.clear(); joinKeys.clear(); } } } void CoreUserInputHandler::handleKeyx(const BufferInfo &bufferInfo, const QString &msg) { QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName(); #ifdef HAVE_QCA2 if (!bufferInfo.isValid()) return; if (!Cipher::neededFeaturesAvailable()) { emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")); return; } QStringList parms = msg.split(' ', QString::SkipEmptyParts); if (parms.count() == 0 && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages()) parms.prepend(bufferInfo.bufferName()); else if (parms.count() != 1) { emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("[usage] /keyx [<nick>] Initiates a DH1080 key exchange with the target.")); return; } QString target = parms.at(0); if (network()->isChannelName(target)) { emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("It is only possible to exchange keys in a query buffer.")); return; } Cipher *cipher = network()->cipher(target); if (!cipher) // happens when there is no CoreIrcChannel for the target return; QByteArray pubKey = cipher->initKeyExchange(); if (pubKey.isEmpty()) emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Failed to initiate key exchange with %1.").arg(target)); else { QList<QByteArray> params; params << serverEncode(target) << serverEncode("DH1080_INIT ") + pubKey; emit putCmd("NOTICE", params); emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("Initiated key exchange with %1.").arg(target)); } #else Q_UNUSED(msg) emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built " "with support for the Qt Cryptographic Architecture (QCA) library. " "Contact your distributor about a Quassel package with QCA " "support, or rebuild Quassel with QCA present.")); #endif } void CoreUserInputHandler::handleKick(const BufferInfo &bufferInfo, const QString &msg) { QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty); QString reason = msg.section(' ', 1, -1, QString::SectionSkipEmpty).trimmed(); if (reason.isEmpty()) reason = network()->identityPtr()->kickReason(); QList<QByteArray> params; params << serverEncode(bufferInfo.bufferName()) << serverEncode(nick) << channelEncode(bufferInfo.bufferName(), reason); emit putCmd("KICK", params); } void CoreUserInputHandler::handleKill(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty); QString pass = msg.section(' ', 1, -1, QString::SectionSkipEmpty); QList<QByteArray> params; params << serverEncode(nick) << serverEncode(pass); emit putCmd("KILL", params); } void CoreUserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts))); } void CoreUserInputHandler::handleMe(const BufferInfo &bufferInfo, const QString &msg) { if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages()) return; // server buffer // FIXME make this a proper event coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), bufferInfo.bufferName(), "ACTION", msg); emit displayMsg(Message::Action, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self); } void CoreUserInputHandler::handleMode(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) QStringList params = msg.split(' ', QString::SkipEmptyParts); // if the first argument is neither a channel nor us (user modes are only to oneself) the current buffer is assumed to be the target if (!params.isEmpty()) { if (!network()->isChannelName(params[0]) && !network()->isMyNick(params[0])) params.prepend(bufferInfo.bufferName()); if (network()->isMyNick(params[0]) && params.count() == 2) network()->updateIssuedModes(params[1]); if (params[0] == "-reset" && params.count() == 1) { // FIXME: give feedback to the user (I don't want to add new strings right now) network()->resetPersistentModes(); return; } } // TODO handle correct encoding for buffer modes (channelEncode()) emit putCmd("MODE", serverEncode(params)); } // TODO: show privmsgs void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo); if (!msg.contains(' ')) return; QString target = msg.section(' ', 0, 0); QByteArray encMsg = userEncode(target, msg.section(' ', 1)); #ifdef HAVE_QCA2 putPrivmsg(serverEncode(target), encMsg, network()->cipher(target)); #else putPrivmsg(serverEncode(target), encMsg); #endif } void CoreUserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) QString nick = msg.section(' ', 0, 0); emit putCmd("NICK", serverEncode(nick)); } void CoreUserInputHandler::handleNotice(const BufferInfo &bufferInfo, const QString &msg) { QString bufferName = msg.section(' ', 0, 0); QString payload = msg.section(' ', 1); QList<QByteArray> params; params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), payload); emit putCmd("NOTICE", params); emit displayMsg(Message::Notice, typeByTarget(bufferName), bufferName, payload, network()->myNick(), Message::Self); } void CoreUserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) emit putRawLine(serverEncode(QString("OPER %1").arg(msg))); } void CoreUserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg) { QList<QByteArray> params; QString partReason; // msg might contain either a channel name and/or a reaon, so we have to check if the first word is a known channel QString channelName = msg.section(' ', 0, 0); if (channelName.isEmpty() || !network()->ircChannel(channelName)) { channelName = bufferInfo.bufferName(); partReason = msg; } else { partReason = msg.mid(channelName.length() + 1); } if (partReason.isEmpty()) partReason = network()->identityPtr()->partReason(); params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason); emit putCmd("PART", params); } void CoreUserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) QString param = msg; if (param.isEmpty()) param = QTime::currentTime().toString("hh:mm:ss.zzz"); putCmd("PING", serverEncode(param)); } void CoreUserInputHandler::handlePrint(const BufferInfo &bufferInfo, const QString &msg) { if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages()) return; // server buffer QByteArray encMsg = channelEncode(bufferInfo.bufferName(), msg); emit displayMsg(Message::Info, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self); } // TODO: implement queries void CoreUserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) QString target = msg.section(' ', 0, 0); QString message = msg.section(' ', 1); if (message.isEmpty()) emit displayMsg(Message::Server, BufferInfo::QueryBuffer, target, tr("Starting query with %1").arg(target), network()->myNick(), Message::Self); else emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message, network()->myNick(), Message::Self); handleMsg(bufferInfo, msg); } void CoreUserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) network()->disconnectFromIrc(true, msg); } void CoreUserInputHandler::issueQuit(const QString &reason) { emit putCmd("QUIT", serverEncode(reason)); } void CoreUserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) emit putRawLine(serverEncode(msg)); } void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg) { if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages()) return; // server buffer QByteArray encMsg = channelEncode(bufferInfo.bufferName(), msg); #ifdef HAVE_QCA2 putPrivmsg(serverEncode(bufferInfo.bufferName()), encMsg, network()->cipher(bufferInfo.bufferName())); #else putPrivmsg(serverEncode(bufferInfo.bufferName()), encMsg); #endif emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self); } void CoreUserInputHandler::handleSetkey(const BufferInfo &bufferInfo, const QString &msg) { QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName(); #ifdef HAVE_QCA2 if (!bufferInfo.isValid()) return; if (!Cipher::neededFeaturesAvailable()) { emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")); return; } QStringList parms = msg.split(' ', QString::SkipEmptyParts); if (parms.count() == 1 && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages()) parms.prepend(bufferInfo.bufferName()); else if (parms.count() != 2) { emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("[usage] /setkey <nick|channel> <key> sets the encryption key for nick or channel. " "/setkey <key> when in a channel or query buffer sets the key for it.")); return; } QString target = parms.at(0); QByteArray key = parms.at(1).toLocal8Bit(); network()->setCipherKey(target, key); emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 has been set.").arg(target)); #else Q_UNUSED(msg) emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built " "with support for the Qt Cryptographic Architecture (QCA) library. " "Contact your distributor about a Quassel package with QCA " "support, or rebuild Quassel with QCA present.")); #endif } void CoreUserInputHandler::handleShowkey(const BufferInfo &bufferInfo, const QString &msg) { QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName(); #ifdef HAVE_QCA2 if (!bufferInfo.isValid()) return; if (!Cipher::neededFeaturesAvailable()) { emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")); return; } QStringList parms = msg.split(' ', QString::SkipEmptyParts); if (parms.isEmpty() && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages()) parms.prepend(bufferInfo.bufferName()); if (parms.isEmpty()) { emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("[usage] /showkey <nick|channel> shows the encryption key for nick or channel or just /showkey when in a channel or query.")); return; } QString target = parms.at(0); QByteArray key = network()->cipherKey(target); if (key.isEmpty()) { emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("No key has been set for %1.").arg(target)); return; } emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 is %2:%3").arg(target, network()->cipherUsesCBC(target) ? "CBC" : "ECB", QString(key))); #else Q_UNUSED(msg) emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built " "with support for the Qt Cryptographic Architecture (QCA2) library. " "Contact your distributor about a Quassel package with QCA2 " "support, or rebuild Quassel with QCA2 present.")); #endif } void CoreUserInputHandler::handleTopic(const BufferInfo &bufferInfo, const QString &msg) { if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages()) return; QList<QByteArray> params; params << serverEncode(bufferInfo.bufferName()); if (!msg.isEmpty()) { # ifdef HAVE_QCA2 params << encrypt(bufferInfo.bufferName(), channelEncode(bufferInfo.bufferName(), msg)); # else params << channelEncode(bufferInfo.bufferName(), msg); # endif } emit putCmd("TOPIC", params); } void CoreUserInputHandler::handleVoice(const BufferInfo &bufferInfo, const QString &msg) { QStringList nicks = msg.split(' ', QString::SkipEmptyParts); QString m = "+"; for (int i = 0; i < nicks.count(); i++) m += 'v'; QStringList params; params << bufferInfo.bufferName() << m << nicks; emit putCmd("MODE", serverEncode(params)); } void CoreUserInputHandler::handleWait(const BufferInfo &bufferInfo, const QString &msg) { int splitPos = msg.indexOf(';'); if (splitPos <= 0) return; bool ok; int delay = msg.left(splitPos).trimmed().toInt(&ok); if (!ok) return; delay *= 1000; QString command = msg.mid(splitPos + 1).trimmed(); if (command.isEmpty()) return; _delayedCommands[startTimer(delay)] = Command(bufferInfo, command); } void CoreUserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) emit putCmd("WHO", serverEncode(msg.split(' '))); } void CoreUserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) emit putCmd("WHOIS", serverEncode(msg.split(' '))); } void CoreUserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) emit putCmd("WHOWAS", serverEncode(msg.split(' '))); } void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo); emit putCmd(serverEncode(cmd.toUpper()), serverEncode(msg.split(" "))); } void CoreUserInputHandler::putPrivmsg(const QByteArray &target, const QByteArray &message, Cipher *cipher) { // Encrypted messages need special care. There's no clear relation between cleartext and encrypted message length, // so we can't just compute the maxSplitPos. Instead, we need to loop through the splitpoints until the crypted // version is short enough... // TODO: check out how the various possible encryption methods behave length-wise and make // this clean by predicting the length of the crypted msg. // For example, blowfish-ebc seems to create 8-char chunks. static const char *cmd = "PRIVMSG"; static const char *splitter = " .,-!?"; int maxSplitPos = message.count(); int splitPos = maxSplitPos; forever { QByteArray crypted = message.left(splitPos); bool isEncrypted = false; #ifdef HAVE_QCA2 if (cipher && !cipher->key().isEmpty() && !message.isEmpty()) { isEncrypted = cipher->encrypt(crypted); } #endif int overrun = lastParamOverrun(cmd, QList<QByteArray>() << target << crypted); if (overrun) { // In case this is not an encrypted msg, we can just cut off at the end if (!isEncrypted) maxSplitPos = message.count() - overrun; splitPos = -1; for (const char *splitChar = splitter; *splitChar != 0; splitChar++) { splitPos = qMax(splitPos, message.lastIndexOf(*splitChar, maxSplitPos) + 1); // keep split char on old line } if (splitPos <= 0 || splitPos > maxSplitPos) splitPos = maxSplitPos; maxSplitPos = splitPos - 1; if (maxSplitPos <= 0) { // this should never happen, but who knows... qWarning() << tr("[Error] Could not encrypt your message: %1").arg(message.data()); return; } continue; // we never come back here for !encrypted! } // now we have found a valid splitpos (or didn't need to split to begin with) putCmd(cmd, QList<QByteArray>() << target << crypted); if (splitPos < message.count()) putPrivmsg(target, message.mid(splitPos), cipher); return; } } // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long int CoreUserInputHandler::lastParamOverrun(const QString &cmd, const QList<QByteArray> &params) { // the server will pass our message truncated to 512 bytes including CRLF with the following format: // ":prefix COMMAND param0 param1 :lastparam" // where prefix = "nickname!user@host" // that means that the last message can be as long as: // 512 - nicklen - userlen - hostlen - commandlen - sum(param[0]..param[n-1])) - 2 (for CRLF) - 4 (":!@" + 1space between prefix and command) - max(paramcount - 1, 0) (space for simple params) - 2 (space and colon for last param) IrcUser *me = network()->me(); int maxLen = 480 - cmd.toLatin1().count(); // educated guess in case we don't know us (yet?) if (me) maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toLatin1().count() - 6; if (!params.isEmpty()) { for (int i = 0; i < params.count() - 1; i++) { maxLen -= (params[i].count() + 1); } maxLen -= 2; // " :" last param separator; if (params.last().count() > maxLen) { return params.last().count() - maxLen; } else { return 0; } } else { return 0; } } #ifdef HAVE_QCA2 QByteArray CoreUserInputHandler::encrypt(const QString &target, const QByteArray &message_, bool *didEncrypt) const { if (didEncrypt) *didEncrypt = false; if (message_.isEmpty()) return message_; if (!Cipher::neededFeaturesAvailable()) return message_; Cipher *cipher = network()->cipher(target); if (!cipher || cipher->key().isEmpty()) return message_; QByteArray message = message_; bool result = cipher->encrypt(message); if (didEncrypt) *didEncrypt = result; return message; } #endif void CoreUserInputHandler::timerEvent(QTimerEvent *event) { if (!_delayedCommands.contains(event->timerId())) { QObject::timerEvent(event); return; } BufferInfo bufferInfo = _delayedCommands[event->timerId()].bufferInfo; QString rawCommand = _delayedCommands[event->timerId()].command; _delayedCommands.remove(event->timerId()); event->accept(); // the stored command might be the result of an alias expansion, so we need to split it up again QStringList commands = rawCommand.split(QRegExp("; ?")); foreach(QString command, commands) { handleUserInput(bufferInfo, command); } }
./CrossVul/dataset_final_sorted/CWE-399/cpp/bad_1539_4
crossvul-cpp_data_good_3566_0
/* * Copyright (C) 2004-2011 See the AUTHORS file for details. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include "zncconfig.h" #include "znc.h" #include "User.h" #include "Modules.h" #include "Socket.h" #include "FileUtils.h" class CBounceDCCMod; class CDCCBounce : public CSocket { public: CDCCBounce(CBounceDCCMod* pMod, unsigned long uLongIP, unsigned short uPort, const CString& sFileName, const CString& sRemoteNick, const CString& sRemoteIP, bool bIsChat = false); CDCCBounce(CBounceDCCMod* pMod, const CString& sHostname, unsigned short uPort, const CString& sRemoteNick, const CString& sRemoteIP, const CString& sFileName, int iTimeout = 60, bool bIsChat = false); virtual ~CDCCBounce(); static unsigned short DCCRequest(const CString& sNick, unsigned long uLongIP, unsigned short uPort, const CString& sFileName, bool bIsChat, CBounceDCCMod* pMod, const CString& sRemoteIP); void ReadLine(const CString& sData); virtual void ReadData(const char* data, size_t len); virtual void ReadPaused(); virtual void Timeout(); virtual void ConnectionRefused(); virtual void ReachedMaxBuffer(); virtual void SockError(int iErrno); virtual void Connected(); virtual void Disconnected(); virtual Csock* GetSockObj(const CString& sHost, unsigned short uPort); void Shutdown(); void PutServ(const CString& sLine); void PutPeer(const CString& sLine); bool IsPeerConnected() { return (m_pPeer) ? m_pPeer->IsConnected() : false; } // Setters void SetPeer(CDCCBounce* p) { m_pPeer = p; } void SetRemoteIP(const CString& s) { m_sRemoteIP = s; } void SetRemoteNick(const CString& s) { m_sRemoteNick = s; } void SetRemote(bool b) { m_bIsRemote = b; } // !Setters // Getters unsigned short GetUserPort() const { return m_uRemotePort; } const CString& GetRemoteIP() const { return m_sRemoteIP; } const CString& GetRemoteNick() const { return m_sRemoteNick; } const CString& GetFileName() const { return m_sFileName; } CDCCBounce* GetPeer() const { return m_pPeer; } bool IsRemote() { return m_bIsRemote; } bool IsChat() { return m_bIsChat; } // !Getters private: protected: CString m_sRemoteNick; CString m_sRemoteIP; CString m_sConnectIP; CString m_sLocalIP; CString m_sFileName; CBounceDCCMod* m_pModule; CDCCBounce* m_pPeer; unsigned short m_uRemotePort; bool m_bIsChat; bool m_bIsRemote; static const unsigned int m_uiMaxDCCBuffer; static const unsigned int m_uiMinDCCBuffer; }; // If we buffer more than this in memory, we will throttle the receiving side const unsigned int CDCCBounce::m_uiMaxDCCBuffer = 10 * 1024; // If less than this is in the buffer, the receiving side continues const unsigned int CDCCBounce::m_uiMinDCCBuffer = 2 * 1024; class CBounceDCCMod : public CModule { public: void ListDCCsCommand(const CString& sLine) { CTable Table; Table.AddColumn("Type"); Table.AddColumn("State"); Table.AddColumn("Speed"); Table.AddColumn("Nick"); Table.AddColumn("IP"); Table.AddColumn("File"); set<CSocket*>::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { CDCCBounce* pSock = (CDCCBounce*) *it; CString sSockName = pSock->GetSockName(); if (!(pSock->IsRemote())) { Table.AddRow(); Table.SetCell("Nick", pSock->GetRemoteNick()); Table.SetCell("IP", pSock->GetRemoteIP()); if (pSock->IsChat()) { Table.SetCell("Type", "Chat"); } else { Table.SetCell("Type", "Xfer"); Table.SetCell("File", pSock->GetFileName()); } CString sState = "Waiting"; if ((pSock->IsConnected()) || (pSock->IsPeerConnected())) { sState = "Halfway"; if ((pSock->IsPeerConnected()) && (pSock->IsPeerConnected())) { sState = "Connected"; } } Table.SetCell("State", sState); } } if (PutModule(Table) == 0) { PutModule("You have no active DCCs."); } } void UseClientIPCommand(const CString& sLine) { CString sValue = sLine.Token(1, true); if (!sValue.empty()) { SetNV("UseClientIP", sValue); } PutModule("UseClientIP: " + CString(GetNV("UseClientIP").ToBool())); } MODCONSTRUCTOR(CBounceDCCMod) { AddHelpCommand(); AddCommand("ListDCCs", static_cast<CModCommand::ModCmdFunc>(&CBounceDCCMod::ListDCCsCommand), "", "List all active DCCs"); AddCommand("UseClientIP", static_cast<CModCommand::ModCmdFunc>(&CBounceDCCMod::UseClientIPCommand), "<true|false>"); } virtual ~CBounceDCCMod() {} CString GetLocalDCCIP() { return m_pUser->GetLocalDCCIP(); } bool UseClientIP() { return GetNV("UseClientIP").ToBool(); } virtual EModRet OnUserCTCP(CString& sTarget, CString& sMessage) { if (sMessage.Equals("DCC ", false, 4)) { CString sType = sMessage.Token(1); CString sFile = sMessage.Token(2); unsigned long uLongIP = sMessage.Token(3).ToULong(); unsigned short uPort = sMessage.Token(4).ToUShort(); unsigned long uFileSize = sMessage.Token(5).ToULong(); CString sIP = GetLocalDCCIP(); if (!UseClientIP()) { uLongIP = CUtils::GetLongIP(m_pClient->GetRemoteIP()); } if (sType.Equals("CHAT")) { unsigned short uBNCPort = CDCCBounce::DCCRequest(sTarget, uLongIP, uPort, "", true, this, ""); if (uBNCPort) { PutIRC("PRIVMSG " + sTarget + " :\001DCC CHAT chat " + CString(CUtils::GetLongIP(sIP)) + " " + CString(uBNCPort) + "\001"); } } else if (sType.Equals("SEND")) { // DCC SEND readme.txt 403120438 5550 1104 unsigned short uBNCPort = CDCCBounce::DCCRequest(sTarget, uLongIP, uPort, sFile, false, this, ""); if (uBNCPort) { PutIRC("PRIVMSG " + sTarget + " :\001DCC SEND " + sFile + " " + CString(CUtils::GetLongIP(sIP)) + " " + CString(uBNCPort) + " " + CString(uFileSize) + "\001"); } } else if (sType.Equals("RESUME")) { // PRIVMSG user :DCC RESUME "znc.o" 58810 151552 unsigned short uResumePort = sMessage.Token(3).ToUShort(); set<CSocket*>::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { CDCCBounce* pSock = (CDCCBounce*) *it; if (pSock->GetLocalPort() == uResumePort) { PutIRC("PRIVMSG " + sTarget + " :\001DCC " + sType + " " + sFile + " " + CString(pSock->GetUserPort()) + " " + sMessage.Token(4) + "\001"); } } } else if (sType.Equals("ACCEPT")) { // Need to lookup the connection by port, filter the port, and forward to the user set<CSocket*>::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { CDCCBounce* pSock = (CDCCBounce*) *it; if (pSock->GetUserPort() == sMessage.Token(3).ToUShort()) { PutIRC("PRIVMSG " + sTarget + " :\001DCC " + sType + " " + sFile + " " + CString(pSock->GetLocalPort()) + " " + sMessage.Token(4) + "\001"); } } } return HALTCORE; } return CONTINUE; } virtual EModRet OnPrivCTCP(CNick& Nick, CString& sMessage) { if (sMessage.Equals("DCC ", false, 4) && m_pUser->IsUserAttached()) { // DCC CHAT chat 2453612361 44592 CString sType = sMessage.Token(1); CString sFile = sMessage.Token(2); unsigned long uLongIP = sMessage.Token(3).ToULong(); unsigned short uPort = sMessage.Token(4).ToUShort(); unsigned long uFileSize = sMessage.Token(5).ToULong(); if (sType.Equals("CHAT")) { CNick FromNick(Nick.GetNickMask()); unsigned short uBNCPort = CDCCBounce::DCCRequest(FromNick.GetNick(), uLongIP, uPort, "", true, this, CUtils::GetIP(uLongIP)); if (uBNCPort) { CString sIP = GetLocalDCCIP(); m_pUser->PutUser(":" + Nick.GetNickMask() + " PRIVMSG " + m_pUser->GetNick() + " :\001DCC CHAT chat " + CString(CUtils::GetLongIP(sIP)) + " " + CString(uBNCPort) + "\001"); } } else if (sType.Equals("SEND")) { // DCC SEND readme.txt 403120438 5550 1104 unsigned short uBNCPort = CDCCBounce::DCCRequest(Nick.GetNick(), uLongIP, uPort, sFile, false, this, CUtils::GetIP(uLongIP)); if (uBNCPort) { CString sIP = GetLocalDCCIP(); m_pUser->PutUser(":" + Nick.GetNickMask() + " PRIVMSG " + m_pUser->GetNick() + " :\001DCC SEND " + sFile + " " + CString(CUtils::GetLongIP(sIP)) + " " + CString(uBNCPort) + " " + CString(uFileSize) + "\001"); } } else if (sType.Equals("RESUME")) { // Need to lookup the connection by port, filter the port, and forward to the user unsigned short uResumePort = sMessage.Token(3).ToUShort(); set<CSocket*>::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { CDCCBounce* pSock = (CDCCBounce*) *it; if (pSock->GetLocalPort() == uResumePort) { m_pUser->PutUser(":" + Nick.GetNickMask() + " PRIVMSG " + m_pUser->GetNick() + " :\001DCC " + sType + " " + sFile + " " + CString(pSock->GetUserPort()) + " " + sMessage.Token(4) + "\001"); } } } else if (sType.Equals("ACCEPT")) { // Need to lookup the connection by port, filter the port, and forward to the user set<CSocket*>::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { CDCCBounce* pSock = (CDCCBounce*) *it; if (pSock->GetUserPort() == sMessage.Token(3).ToUShort()) { m_pUser->PutUser(":" + Nick.GetNickMask() + " PRIVMSG " + m_pUser->GetNick() + " :\001DCC " + sType + " " + sFile + " " + CString(pSock->GetLocalPort()) + " " + sMessage.Token(4) + "\001"); } } } return HALTCORE; } return CONTINUE; } }; CDCCBounce::CDCCBounce(CBounceDCCMod* pMod, unsigned long uLongIP, unsigned short uPort, const CString& sFileName, const CString& sRemoteNick, const CString& sRemoteIP, bool bIsChat) : CSocket(pMod) { m_uRemotePort = uPort; m_sConnectIP = CUtils::GetIP(uLongIP); m_sRemoteIP = sRemoteIP; m_sFileName = sFileName; m_sRemoteNick = sRemoteNick; m_pModule = pMod; m_bIsChat = bIsChat; m_sLocalIP = pMod->GetLocalDCCIP(); m_pPeer = NULL; m_bIsRemote = false; if (bIsChat) { EnableReadLine(); } else { DisableReadLine(); } } CDCCBounce::CDCCBounce(CBounceDCCMod* pMod, const CString& sHostname, unsigned short uPort, const CString& sRemoteNick, const CString& sRemoteIP, const CString& sFileName, int iTimeout, bool bIsChat) : CSocket(pMod, sHostname, uPort, iTimeout) { m_uRemotePort = 0; m_bIsChat = bIsChat; m_pModule = pMod; m_pPeer = NULL; m_sRemoteNick = sRemoteNick; m_sFileName = sFileName; m_sRemoteIP = sRemoteIP; m_bIsRemote = false; SetMaxBufferThreshold(10240); if (bIsChat) { EnableReadLine(); } else { DisableReadLine(); } } CDCCBounce::~CDCCBounce() { if (m_pPeer) { m_pPeer->Shutdown(); m_pPeer = NULL; } } void CDCCBounce::ReadLine(const CString& sData) { CString sLine = sData.TrimRight_n("\r\n"); DEBUG(GetSockName() << " <- [" << sLine << "]"); PutPeer(sLine); } void CDCCBounce::ReachedMaxBuffer() { DEBUG(GetSockName() << " == ReachedMaxBuffer()"); CString sType = (m_bIsChat) ? "Chat" : "Xfer"; m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + "): Too long line received"); Close(); } void CDCCBounce::ReadData(const char* data, size_t len) { if (m_pPeer) { m_pPeer->Write(data, len); size_t BufLen = m_pPeer->GetInternalWriteBuffer().length(); if (BufLen >= m_uiMaxDCCBuffer) { DEBUG(GetSockName() << " The send buffer is over the " "limit (" << BufLen <<"), throttling"); PauseRead(); } } } void CDCCBounce::ReadPaused() { if (!m_pPeer || m_pPeer->GetInternalWriteBuffer().length() <= m_uiMinDCCBuffer) UnPauseRead(); } void CDCCBounce::Timeout() { DEBUG(GetSockName() << " == Timeout()"); CString sType = (m_bIsChat) ? "Chat" : "Xfer"; if (IsRemote()) { CString sHost = Csock::GetHostName(); if (!sHost.empty()) { sHost = " to [" + sHost + " " + CString(Csock::GetPort()) + "]"; } else { sHost = "."; } m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + "): Timeout while connecting" + sHost); } else { m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + "): Timeout waiting for incoming connection [" + Csock::GetLocalIP() + ":" + CString(Csock::GetLocalPort()) + "]"); } } void CDCCBounce::ConnectionRefused() { DEBUG(GetSockName() << " == ConnectionRefused()"); CString sType = (m_bIsChat) ? "Chat" : "Xfer"; CString sHost = Csock::GetHostName(); if (!sHost.empty()) { sHost = " to [" + sHost + " " + CString(Csock::GetPort()) + "]"; } else { sHost = "."; } m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + "): Connection Refused while connecting" + sHost); } void CDCCBounce::SockError(int iErrno) { DEBUG(GetSockName() << " == SockError(" << iErrno << ")"); CString sType = (m_bIsChat) ? "Chat" : "Xfer"; if (IsRemote()) { CString sHost = Csock::GetHostName(); if (!sHost.empty()) { sHost = "[" + sHost + " " + CString(Csock::GetPort()) + "]"; } m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + "): Socket error [" + CString(strerror(iErrno)) + "]" + sHost); } else { m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + "): Socket error [" + CString(strerror(iErrno)) + "] [" + Csock::GetLocalIP() + ":" + CString(Csock::GetLocalPort()) + "]"); } } void CDCCBounce::Connected() { SetTimeout(0); DEBUG(GetSockName() << " == Connected()"); } void CDCCBounce::Disconnected() { DEBUG(GetSockName() << " == Disconnected()"); } void CDCCBounce::Shutdown() { m_pPeer = NULL; DEBUG(GetSockName() << " == Close(); because my peer told me to"); Close(); } Csock* CDCCBounce::GetSockObj(const CString& sHost, unsigned short uPort) { Close(); if (m_sRemoteIP.empty()) { m_sRemoteIP = sHost; } CDCCBounce* pSock = new CDCCBounce(m_pModule, sHost, uPort, m_sRemoteNick, m_sRemoteIP, m_sFileName, m_bIsChat); CDCCBounce* pRemoteSock = new CDCCBounce(m_pModule, sHost, uPort, m_sRemoteNick, m_sRemoteIP, m_sFileName, m_bIsChat); pSock->SetPeer(pRemoteSock); pRemoteSock->SetPeer(pSock); pRemoteSock->SetRemote(true); pSock->SetRemote(false); if (!CZNC::Get().GetManager().Connect(m_sConnectIP, m_uRemotePort, "DCC::" + CString((m_bIsChat) ? "Chat" : "XFER") + "::Remote::" + m_sRemoteNick, 60, false, m_sLocalIP, pRemoteSock)) { pRemoteSock->Close(); } pSock->SetSockName(GetSockName()); return pSock; } void CDCCBounce::PutServ(const CString& sLine) { DEBUG(GetSockName() << " -> [" << sLine << "]"); Write(sLine + "\r\n"); } void CDCCBounce::PutPeer(const CString& sLine) { if (m_pPeer) { m_pPeer->PutServ(sLine); } else { PutServ("*** Not connected yet ***"); } } unsigned short CDCCBounce::DCCRequest(const CString& sNick, unsigned long uLongIP, unsigned short uPort, const CString& sFileName, bool bIsChat, CBounceDCCMod* pMod, const CString& sRemoteIP) { CDCCBounce* pDCCBounce = new CDCCBounce(pMod, uLongIP, uPort, sFileName, sNick, sRemoteIP, bIsChat); unsigned short uListenPort = CZNC::Get().GetManager().ListenRand("DCC::" + CString((bIsChat) ? "Chat" : "Xfer") + "::Local::" + sNick, pMod->GetLocalDCCIP(), false, SOMAXCONN, pDCCBounce, 120); return uListenPort; } MODULEDEFS(CBounceDCCMod, "Bounce DCC module")
./CrossVul/dataset_final_sorted/CWE-399/cpp/good_3566_0
crossvul-cpp_data_good_1539_2
/*************************************************************************** * Copyright (C) 2005-2015 by the Quassel Project * * devel@quassel-irc.org * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) version 3. * * * * 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 <QHostInfo> #include "corenetwork.h" #include "core.h" #include "coreidentity.h" #include "corenetworkconfig.h" #include "coresession.h" #include "coreuserinputhandler.h" #include "networkevent.h" INIT_SYNCABLE_OBJECT(CoreNetwork) CoreNetwork::CoreNetwork(const NetworkId &networkid, CoreSession *session) : Network(networkid, session), _coreSession(session), _userInputHandler(new CoreUserInputHandler(this)), _autoReconnectCount(0), _quitRequested(false), _previousConnectionAttemptFailed(false), _lastUsedServerIndex(0), _lastPingTime(0), _pingCount(0), _sendPings(false), _requestedUserModes('-') { _autoReconnectTimer.setSingleShot(true); connect(&_socketCloseTimer, SIGNAL(timeout()), this, SLOT(socketCloseTimeout())); setPingInterval(networkConfig()->pingInterval()); connect(&_pingTimer, SIGNAL(timeout()), this, SLOT(sendPing())); setAutoWhoDelay(networkConfig()->autoWhoDelay()); setAutoWhoInterval(networkConfig()->autoWhoInterval()); QHash<QString, QString> channels = coreSession()->persistentChannels(networkId()); foreach(QString chan, channels.keys()) { _channelKeys[chan.toLower()] = channels[chan]; } connect(networkConfig(), SIGNAL(pingTimeoutEnabledSet(bool)), SLOT(enablePingTimeout(bool))); connect(networkConfig(), SIGNAL(pingIntervalSet(int)), SLOT(setPingInterval(int))); connect(networkConfig(), SIGNAL(autoWhoEnabledSet(bool)), SLOT(setAutoWhoEnabled(bool))); connect(networkConfig(), SIGNAL(autoWhoIntervalSet(int)), SLOT(setAutoWhoInterval(int))); connect(networkConfig(), SIGNAL(autoWhoDelaySet(int)), SLOT(setAutoWhoDelay(int))); connect(&_autoReconnectTimer, SIGNAL(timeout()), this, SLOT(doAutoReconnect())); connect(&_autoWhoTimer, SIGNAL(timeout()), this, SLOT(sendAutoWho())); connect(&_autoWhoCycleTimer, SIGNAL(timeout()), this, SLOT(startAutoWhoCycle())); connect(&_tokenBucketTimer, SIGNAL(timeout()), this, SLOT(fillBucketAndProcessQueue())); connect(&socket, SIGNAL(connected()), this, SLOT(socketInitialized())); connect(&socket, SIGNAL(disconnected()), this, SLOT(socketDisconnected())); connect(&socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError))); connect(&socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState))); connect(&socket, SIGNAL(readyRead()), this, SLOT(socketHasData())); #ifdef HAVE_SSL connect(&socket, SIGNAL(encrypted()), this, SLOT(socketInitialized())); connect(&socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrors(const QList<QSslError> &))); #endif connect(this, SIGNAL(newEvent(Event *)), coreSession()->eventManager(), SLOT(postEvent(Event *))); if (Quassel::isOptionSet("oidentd")) { connect(this, SIGNAL(socketOpen(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(addSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Qt::BlockingQueuedConnection); connect(this, SIGNAL(socketDisconnected(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16)), Core::instance()->oidentdConfigGenerator(), SLOT(removeSocket(const CoreIdentity*, QHostAddress, quint16, QHostAddress, quint16))); } } CoreNetwork::~CoreNetwork() { if (connectionState() != Disconnected && connectionState() != Network::Reconnecting) disconnectFromIrc(false); // clean up, but this does not count as requested disconnect! disconnect(&socket, 0, this, 0); // this keeps the socket from triggering events during clean up delete _userInputHandler; } QString CoreNetwork::channelDecode(const QString &bufferName, const QByteArray &string) const { if (!bufferName.isEmpty()) { IrcChannel *channel = ircChannel(bufferName); if (channel) return channel->decodeString(string); } return decodeString(string); } QString CoreNetwork::userDecode(const QString &userNick, const QByteArray &string) const { IrcUser *user = ircUser(userNick); if (user) return user->decodeString(string); return decodeString(string); } QByteArray CoreNetwork::channelEncode(const QString &bufferName, const QString &string) const { if (!bufferName.isEmpty()) { IrcChannel *channel = ircChannel(bufferName); if (channel) return channel->encodeString(string); } return encodeString(string); } QByteArray CoreNetwork::userEncode(const QString &userNick, const QString &string) const { IrcUser *user = ircUser(userNick); if (user) return user->encodeString(string); return encodeString(string); } void CoreNetwork::connectToIrc(bool reconnecting) { if (!reconnecting && useAutoReconnect() && _autoReconnectCount == 0) { _autoReconnectTimer.setInterval(autoReconnectInterval() * 1000); if (unlimitedReconnectRetries()) _autoReconnectCount = -1; else _autoReconnectCount = autoReconnectRetries(); } if (serverList().isEmpty()) { qWarning() << "Server list empty, ignoring connect request!"; return; } CoreIdentity *identity = identityPtr(); if (!identity) { qWarning() << "Invalid identity configures, ignoring connect request!"; return; } // cleaning up old quit reason _quitReason.clear(); // use a random server? if (useRandomServer()) { _lastUsedServerIndex = qrand() % serverList().size(); } else if (_previousConnectionAttemptFailed) { // cycle to next server if previous connection attempt failed displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connection failed. Cycling to next Server")); if (++_lastUsedServerIndex >= serverList().size()) { _lastUsedServerIndex = 0; } } _previousConnectionAttemptFailed = false; Server server = usedServer(); displayStatusMsg(tr("Connecting to %1:%2...").arg(server.host).arg(server.port)); displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Connecting to %1:%2...").arg(server.host).arg(server.port)); if (server.useProxy) { QNetworkProxy proxy((QNetworkProxy::ProxyType)server.proxyType, server.proxyHost, server.proxyPort, server.proxyUser, server.proxyPass); socket.setProxy(proxy); } else { socket.setProxy(QNetworkProxy::NoProxy); } enablePingTimeout(); // Qt caches DNS entries for a minute, resulting in round-robin (e.g. for chat.freenode.net) not working if several users // connect at a similar time. QHostInfo::fromName(), however, always performs a fresh lookup, overwriting the cache entry. QHostInfo::fromName(server.host); #ifdef HAVE_SSL if (server.useSsl) { CoreIdentity *identity = identityPtr(); if (identity) { socket.setLocalCertificate(identity->sslCert()); socket.setPrivateKey(identity->sslKey()); } socket.connectToHostEncrypted(server.host, server.port); } else { socket.connectToHost(server.host, server.port); } #else socket.connectToHost(server.host, server.port); #endif } void CoreNetwork::disconnectFromIrc(bool requested, const QString &reason, bool withReconnect) { _quitRequested = requested; // see socketDisconnected(); if (!withReconnect) { _autoReconnectTimer.stop(); _autoReconnectCount = 0; // prohibiting auto reconnect } disablePingTimeout(); _msgQueue.clear(); IrcUser *me_ = me(); if (me_) { QString awayMsg; if (me_->isAway()) awayMsg = me_->awayMessage(); Core::setAwayMessage(userId(), networkId(), awayMsg); } if (reason.isEmpty() && identityPtr()) _quitReason = identityPtr()->quitReason(); else _quitReason = reason; displayMsg(Message::Server, BufferInfo::StatusBuffer, "", tr("Disconnecting. (%1)").arg((!requested && !withReconnect) ? tr("Core Shutdown") : _quitReason)); if (socket.state() == QAbstractSocket::UnconnectedState) { socketDisconnected(); } else { if (socket.state() == QAbstractSocket::ConnectedState) { userInputHandler()->issueQuit(_quitReason); } else { socket.close(); } if (requested || withReconnect) { // the irc server has 10 seconds to close the socket _socketCloseTimer.start(10000); } } } void CoreNetwork::userInput(BufferInfo buf, QString msg) { userInputHandler()->handleUserInput(buf, msg); } void CoreNetwork::putRawLine(QByteArray s) { if (_tokenBucket > 0) writeToSocket(s); else _msgQueue.append(s); } void CoreNetwork::putCmd(const QString &cmd, const QList<QByteArray> &params, const QByteArray &prefix) { QByteArray msg; if (!prefix.isEmpty()) msg += ":" + prefix + " "; msg += cmd.toUpper().toLatin1(); for (int i = 0; i < params.size(); i++) { msg += " "; if (i == params.size() - 1 && (params[i].contains(' ') || (!params[i].isEmpty() && params[i][0] == ':'))) msg += ":"; msg += params[i]; } putRawLine(msg); } void CoreNetwork::putCmd(const QString &cmd, const QList<QList<QByteArray>> &params, const QByteArray &prefix) { QListIterator<QList<QByteArray>> i(params); while (i.hasNext()) { QList<QByteArray> msg = i.next(); putCmd(cmd, msg, prefix); } } void CoreNetwork::setChannelJoined(const QString &channel) { _autoWhoQueue.prepend(channel.toLower()); // prepend so this new chan is the first to be checked Core::setChannelPersistent(userId(), networkId(), channel, true); Core::setPersistentChannelKey(userId(), networkId(), channel, _channelKeys[channel.toLower()]); } void CoreNetwork::setChannelParted(const QString &channel) { removeChannelKey(channel); _autoWhoQueue.removeAll(channel.toLower()); _autoWhoPending.remove(channel.toLower()); Core::setChannelPersistent(userId(), networkId(), channel, false); } void CoreNetwork::addChannelKey(const QString &channel, const QString &key) { if (key.isEmpty()) { removeChannelKey(channel); } else { _channelKeys[channel.toLower()] = key; } } void CoreNetwork::removeChannelKey(const QString &channel) { _channelKeys.remove(channel.toLower()); } #ifdef HAVE_QCA2 Cipher *CoreNetwork::cipher(const QString &target) { if (target.isEmpty()) return 0; if (!Cipher::neededFeaturesAvailable()) return 0; CoreIrcChannel *channel = qobject_cast<CoreIrcChannel *>(ircChannel(target)); if (channel) { return channel->cipher(); } CoreIrcUser *user = qobject_cast<CoreIrcUser *>(ircUser(target)); if (user) { return user->cipher(); } else if (!isChannelName(target)) { return qobject_cast<CoreIrcUser*>(newIrcUser(target))->cipher(); } return 0; } QByteArray CoreNetwork::cipherKey(const QString &target) const { CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target)); if (c) return c->cipher()->key(); CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target)); if (u) return u->cipher()->key(); return QByteArray(); } void CoreNetwork::setCipherKey(const QString &target, const QByteArray &key) { CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target)); if (c) { c->setEncrypted(c->cipher()->setKey(key)); return; } CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target)); if (!u && !isChannelName(target)) u = qobject_cast<CoreIrcUser*>(newIrcUser(target)); if (u) { u->setEncrypted(u->cipher()->setKey(key)); return; } } bool CoreNetwork::cipherUsesCBC(const QString &target) { CoreIrcChannel *c = qobject_cast<CoreIrcChannel*>(ircChannel(target)); if (c) return c->cipher()->usesCBC(); CoreIrcUser *u = qobject_cast<CoreIrcUser*>(ircUser(target)); if (u) return u->cipher()->usesCBC(); return false; } #endif /* HAVE_QCA2 */ bool CoreNetwork::setAutoWhoDone(const QString &channel) { QString chan = channel.toLower(); if (_autoWhoPending.value(chan, 0) <= 0) return false; if (--_autoWhoPending[chan] <= 0) _autoWhoPending.remove(chan); return true; } void CoreNetwork::setMyNick(const QString &mynick) { Network::setMyNick(mynick); if (connectionState() == Network::Initializing) networkInitialized(); } void CoreNetwork::socketHasData() { while (socket.canReadLine()) { QByteArray s = socket.readLine(); if (s.endsWith("\r\n")) s.chop(2); else if (s.endsWith("\n")) s.chop(1); NetworkDataEvent *event = new NetworkDataEvent(EventManager::NetworkIncoming, this, s); event->setTimestamp(QDateTime::currentDateTimeUtc()); emit newEvent(event); } } void CoreNetwork::socketError(QAbstractSocket::SocketError error) { if (_quitRequested && error == QAbstractSocket::RemoteHostClosedError) return; _previousConnectionAttemptFailed = true; qWarning() << qPrintable(tr("Could not connect to %1 (%2)").arg(networkName(), socket.errorString())); emit connectionError(socket.errorString()); displayMsg(Message::Error, BufferInfo::StatusBuffer, "", tr("Connection failure: %1").arg(socket.errorString())); emitConnectionError(socket.errorString()); if (socket.state() < QAbstractSocket::ConnectedState) { socketDisconnected(); } } void CoreNetwork::socketInitialized() { CoreIdentity *identity = identityPtr(); if (!identity) { qCritical() << "Identity invalid!"; disconnectFromIrc(); return; } emit socketOpen(identity, localAddress(), localPort(), peerAddress(), peerPort()); Server server = usedServer(); #ifdef HAVE_SSL if (server.useSsl && !socket.isEncrypted()) return; #endif socket.setSocketOption(QAbstractSocket::KeepAliveOption, true); emit socketInitialized(identity, localAddress(), localPort(), peerAddress(), peerPort()); // TokenBucket to avoid sending too much at once _messageDelay = 2200; // this seems to be a safe value (2.2 seconds delay) _burstSize = 5; _tokenBucket = _burstSize; // init with a full bucket _tokenBucketTimer.start(_messageDelay); if (networkInfo().useSasl) { putRawLine(serverEncode(QString("CAP REQ :sasl"))); } if (!server.password.isEmpty()) { putRawLine(serverEncode(QString("PASS %1").arg(server.password))); } QString nick; if (identity->nicks().isEmpty()) { nick = "quassel"; qWarning() << "CoreNetwork::socketInitialized(): no nicks supplied for identity Id" << identity->id(); } else { nick = identity->nicks()[0]; } putRawLine(serverEncode(QString("NICK :%1").arg(nick))); putRawLine(serverEncode(QString("USER %1 8 * :%2").arg(identity->ident(), identity->realName()))); } void CoreNetwork::socketDisconnected() { disablePingTimeout(); _msgQueue.clear(); _autoWhoCycleTimer.stop(); _autoWhoTimer.stop(); _autoWhoQueue.clear(); _autoWhoPending.clear(); _socketCloseTimer.stop(); _tokenBucketTimer.stop(); IrcUser *me_ = me(); if (me_) { foreach(QString channel, me_->channels()) displayMsg(Message::Quit, BufferInfo::ChannelBuffer, channel, _quitReason, me_->hostmask()); } setConnected(false); emit disconnected(networkId()); emit socketDisconnected(identityPtr(), localAddress(), localPort(), peerAddress(), peerPort()); if (_quitRequested) { _quitRequested = false; setConnectionState(Network::Disconnected); Core::setNetworkConnected(userId(), networkId(), false); } else if (_autoReconnectCount != 0) { setConnectionState(Network::Reconnecting); if (_autoReconnectCount == -1 || _autoReconnectCount == autoReconnectRetries()) doAutoReconnect(); // first try is immediate else _autoReconnectTimer.start(); } } void CoreNetwork::socketStateChanged(QAbstractSocket::SocketState socketState) { Network::ConnectionState state; switch (socketState) { case QAbstractSocket::UnconnectedState: state = Network::Disconnected; break; case QAbstractSocket::HostLookupState: case QAbstractSocket::ConnectingState: state = Network::Connecting; break; case QAbstractSocket::ConnectedState: state = Network::Initializing; break; case QAbstractSocket::ClosingState: state = Network::Disconnecting; break; default: state = Network::Disconnected; } setConnectionState(state); } void CoreNetwork::networkInitialized() { setConnectionState(Network::Initialized); setConnected(true); _quitRequested = false; if (useAutoReconnect()) { // reset counter _autoReconnectCount = unlimitedReconnectRetries() ? -1 : autoReconnectRetries(); } // restore away state QString awayMsg = Core::awayMessage(userId(), networkId()); if (!awayMsg.isEmpty()) userInputHandler()->handleAway(BufferInfo(), Core::awayMessage(userId(), networkId())); sendPerform(); _sendPings = true; if (networkConfig()->autoWhoEnabled()) { _autoWhoCycleTimer.start(); _autoWhoTimer.start(); startAutoWhoCycle(); // FIXME wait for autojoin to be completed } Core::bufferInfo(userId(), networkId(), BufferInfo::StatusBuffer); // create status buffer Core::setNetworkConnected(userId(), networkId(), true); } void CoreNetwork::sendPerform() { BufferInfo statusBuf = BufferInfo::fakeStatusBuffer(networkId()); // do auto identify if (useAutoIdentify() && !autoIdentifyService().isEmpty() && !autoIdentifyPassword().isEmpty()) { userInputHandler()->handleMsg(statusBuf, QString("%1 IDENTIFY %2").arg(autoIdentifyService(), autoIdentifyPassword())); } // restore old user modes if server default mode is set. IrcUser *me_ = me(); if (me_) { if (!me_->userModes().isEmpty()) { restoreUserModes(); } else { connect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes())); connect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes())); } } // send perform list foreach(QString line, perform()) { if (!line.isEmpty()) userInput(statusBuf, line); } // rejoin channels we've been in if (rejoinChannels()) { QStringList channels, keys; foreach(QString chan, coreSession()->persistentChannels(networkId()).keys()) { QString key = channelKey(chan); if (!key.isEmpty()) { channels.prepend(chan); keys.prepend(key); } else { channels.append(chan); } } QString joinString = QString("%1 %2").arg(channels.join(",")).arg(keys.join(",")).trimmed(); if (!joinString.isEmpty()) userInputHandler()->handleJoin(statusBuf, joinString); } } void CoreNetwork::restoreUserModes() { IrcUser *me_ = me(); Q_ASSERT(me_); disconnect(me_, SIGNAL(userModesSet(QString)), this, SLOT(restoreUserModes())); disconnect(me_, SIGNAL(userModesAdded(QString)), this, SLOT(restoreUserModes())); QString modesDelta = Core::userModes(userId(), networkId()); QString currentModes = me_->userModes(); QString addModes, removeModes; if (modesDelta.contains('-')) { addModes = modesDelta.section('-', 0, 0); removeModes = modesDelta.section('-', 1); } else { addModes = modesDelta; } addModes.remove(QRegExp(QString("[%1]").arg(currentModes))); if (currentModes.isEmpty()) removeModes = QString(); else removeModes.remove(QRegExp(QString("[^%1]").arg(currentModes))); if (addModes.isEmpty() && removeModes.isEmpty()) return; if (!addModes.isEmpty()) addModes = '+' + addModes; if (!removeModes.isEmpty()) removeModes = '-' + removeModes; // don't use InputHandler::handleMode() as it keeps track of our persistent mode changes putRawLine(serverEncode(QString("MODE %1 %2%3").arg(me_->nick()).arg(addModes).arg(removeModes))); } void CoreNetwork::updateIssuedModes(const QString &requestedModes) { QString addModes; QString removeModes; bool addMode = true; for (int i = 0; i < requestedModes.length(); i++) { if (requestedModes[i] == '+') { addMode = true; continue; } if (requestedModes[i] == '-') { addMode = false; continue; } if (addMode) { addModes += requestedModes[i]; } else { removeModes += requestedModes[i]; } } QString addModesOld = _requestedUserModes.section('-', 0, 0); QString removeModesOld = _requestedUserModes.section('-', 1); addModes.remove(QRegExp(QString("[%1]").arg(addModesOld))); // deduplicate addModesOld.remove(QRegExp(QString("[%1]").arg(removeModes))); // update addModes += addModesOld; removeModes.remove(QRegExp(QString("[%1]").arg(removeModesOld))); // deduplicate removeModesOld.remove(QRegExp(QString("[%1]").arg(addModes))); // update removeModes += removeModesOld; _requestedUserModes = QString("%1-%2").arg(addModes).arg(removeModes); } void CoreNetwork::updatePersistentModes(QString addModes, QString removeModes) { QString persistentUserModes = Core::userModes(userId(), networkId()); QString requestedAdd = _requestedUserModes.section('-', 0, 0); QString requestedRemove = _requestedUserModes.section('-', 1); QString persistentAdd, persistentRemove; if (persistentUserModes.contains('-')) { persistentAdd = persistentUserModes.section('-', 0, 0); persistentRemove = persistentUserModes.section('-', 1); } else { persistentAdd = persistentUserModes; } // remove modes we didn't issue if (requestedAdd.isEmpty()) addModes = QString(); else addModes.remove(QRegExp(QString("[^%1]").arg(requestedAdd))); if (requestedRemove.isEmpty()) removeModes = QString(); else removeModes.remove(QRegExp(QString("[^%1]").arg(requestedRemove))); // deduplicate persistentAdd.remove(QRegExp(QString("[%1]").arg(addModes))); persistentRemove.remove(QRegExp(QString("[%1]").arg(removeModes))); // update persistentAdd.remove(QRegExp(QString("[%1]").arg(removeModes))); persistentRemove.remove(QRegExp(QString("[%1]").arg(addModes))); // update issued mode list requestedAdd.remove(QRegExp(QString("[%1]").arg(addModes))); requestedRemove.remove(QRegExp(QString("[%1]").arg(removeModes))); _requestedUserModes = QString("%1-%2").arg(requestedAdd).arg(requestedRemove); persistentAdd += addModes; persistentRemove += removeModes; Core::setUserModes(userId(), networkId(), QString("%1-%2").arg(persistentAdd).arg(persistentRemove)); } void CoreNetwork::resetPersistentModes() { _requestedUserModes = QString('-'); Core::setUserModes(userId(), networkId(), QString()); } void CoreNetwork::setUseAutoReconnect(bool use) { Network::setUseAutoReconnect(use); if (!use) _autoReconnectTimer.stop(); } void CoreNetwork::setAutoReconnectInterval(quint32 interval) { Network::setAutoReconnectInterval(interval); _autoReconnectTimer.setInterval(interval * 1000); } void CoreNetwork::setAutoReconnectRetries(quint16 retries) { Network::setAutoReconnectRetries(retries); if (_autoReconnectCount != 0) { if (unlimitedReconnectRetries()) _autoReconnectCount = -1; else _autoReconnectCount = autoReconnectRetries(); } } void CoreNetwork::doAutoReconnect() { if (connectionState() != Network::Disconnected && connectionState() != Network::Reconnecting) { qWarning() << "CoreNetwork::doAutoReconnect(): Cannot reconnect while not being disconnected!"; return; } if (_autoReconnectCount > 0 || _autoReconnectCount == -1) _autoReconnectCount--; // -2 means we delay the next reconnect connectToIrc(true); } void CoreNetwork::sendPing() { uint now = QDateTime::currentDateTime().toTime_t(); if (_pingCount != 0) { qDebug() << "UserId:" << userId() << "Network:" << networkName() << "missed" << _pingCount << "pings." << "BA:" << socket.bytesAvailable() << "BTW:" << socket.bytesToWrite(); } if ((int)_pingCount >= networkConfig()->maxPingCount() && now - _lastPingTime <= (uint)(_pingTimer.interval() / 1000) + 1) { // the second check compares the actual elapsed time since the last ping and the pingTimer interval // if the interval is shorter then the actual elapsed time it means that this thread was somehow blocked // and unable to even handle a ping answer. So we ignore those misses. disconnectFromIrc(false, QString("No Ping reply in %1 seconds.").arg(_pingCount * _pingTimer.interval() / 1000), true /* withReconnect */); } else { _lastPingTime = now; _pingCount++; // Don't send pings until the network is initialized if(_sendPings) userInputHandler()->handlePing(BufferInfo(), QString()); } } void CoreNetwork::enablePingTimeout(bool enable) { if (!enable) disablePingTimeout(); else { resetPingTimeout(); if (networkConfig()->pingTimeoutEnabled()) _pingTimer.start(); } } void CoreNetwork::disablePingTimeout() { _pingTimer.stop(); _sendPings = false; resetPingTimeout(); } void CoreNetwork::setPingInterval(int interval) { _pingTimer.setInterval(interval * 1000); } /******** AutoWHO ********/ void CoreNetwork::startAutoWhoCycle() { if (!_autoWhoQueue.isEmpty()) { _autoWhoCycleTimer.stop(); return; } _autoWhoQueue = channels(); } void CoreNetwork::setAutoWhoDelay(int delay) { _autoWhoTimer.setInterval(delay * 1000); } void CoreNetwork::setAutoWhoInterval(int interval) { _autoWhoCycleTimer.setInterval(interval * 1000); } void CoreNetwork::setAutoWhoEnabled(bool enabled) { if (enabled && isConnected() && !_autoWhoTimer.isActive()) _autoWhoTimer.start(); else if (!enabled) { _autoWhoTimer.stop(); _autoWhoCycleTimer.stop(); } } void CoreNetwork::sendAutoWho() { // Don't send autowho if there are still some pending if (_autoWhoPending.count()) return; while (!_autoWhoQueue.isEmpty()) { QString chan = _autoWhoQueue.takeFirst(); IrcChannel *ircchan = ircChannel(chan); if (!ircchan) continue; if (networkConfig()->autoWhoNickLimit() > 0 && ircchan->ircUsers().count() >= networkConfig()->autoWhoNickLimit()) continue; _autoWhoPending[chan]++; putRawLine("WHO " + serverEncode(chan)); break; } if (_autoWhoQueue.isEmpty() && networkConfig()->autoWhoEnabled() && !_autoWhoCycleTimer.isActive()) { // Timer was stopped, means a new cycle is due immediately _autoWhoCycleTimer.start(); startAutoWhoCycle(); } } #ifdef HAVE_SSL void CoreNetwork::sslErrors(const QList<QSslError> &sslErrors) { Q_UNUSED(sslErrors) socket.ignoreSslErrors(); // TODO errorhandling } #endif // HAVE_SSL void CoreNetwork::fillBucketAndProcessQueue() { if (_tokenBucket < _burstSize) { _tokenBucket++; } while (_msgQueue.size() > 0 && _tokenBucket > 0) { writeToSocket(_msgQueue.takeFirst()); } } void CoreNetwork::writeToSocket(const QByteArray &data) { socket.write(data); socket.write("\r\n"); _tokenBucket--; } Network::Server CoreNetwork::usedServer() const { if (_lastUsedServerIndex < serverList().count()) return serverList()[_lastUsedServerIndex]; if (!serverList().isEmpty()) return serverList()[0]; return Network::Server(); } void CoreNetwork::requestConnect() const { if (connectionState() != Disconnected) { qWarning() << "Requesting connect while already being connected!"; return; } QMetaObject::invokeMethod(const_cast<CoreNetwork *>(this), "connectToIrc", Qt::QueuedConnection); } void CoreNetwork::requestDisconnect() const { if (connectionState() == Disconnected) { qWarning() << "Requesting disconnect while not being connected!"; return; } userInputHandler()->handleQuit(BufferInfo(), QString()); } void CoreNetwork::requestSetNetworkInfo(const NetworkInfo &info) { Network::Server currentServer = usedServer(); setNetworkInfo(info); Core::updateNetwork(coreSession()->user(), info); // the order of the servers might have changed, // so we try to find the previously used server _lastUsedServerIndex = 0; for (int i = 0; i < serverList().count(); i++) { Network::Server server = serverList()[i]; if (server.host == currentServer.host && server.port == currentServer.port) { _lastUsedServerIndex = i; break; } } } QList<QList<QByteArray>> CoreNetwork::splitMessage(const QString &cmd, const QString &message, std::function<QList<QByteArray>(QString &)> cmdGenerator) { QString wrkMsg(message); QList<QList<QByteArray>> msgsToSend; // do while (wrkMsg.size() > 0) do { // First, check to see if the whole message can be sent at once. The // cmdGenerator function is passed in by the caller and is used to encode // and encrypt (if applicable) the message, since different callers might // want to use different encoding or encode different values. int splitPos = wrkMsg.size(); QList<QByteArray> initialSplitMsgEnc = cmdGenerator(wrkMsg); int initialOverrun = userInputHandler()->lastParamOverrun(cmd, initialSplitMsgEnc); if (initialOverrun) { // If the message was too long to be sent, first try splitting it along // word boundaries with QTextBoundaryFinder. QString splitMsg(wrkMsg); QTextBoundaryFinder qtbf(QTextBoundaryFinder::Word, splitMsg); qtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun); QList<QByteArray> splitMsgEnc; int overrun = initialOverrun; while (overrun) { splitPos = qtbf.toPreviousBoundary(); // splitPos==-1 means the QTBF couldn't find a split point at all and // splitPos==0 means the QTBF could only find a boundary at the beginning of // the string. Neither one of these works for us. if (splitPos > 0) { // If a split point could be found, split the message there, calculate the // overrun, and continue with the loop. splitMsg = splitMsg.left(splitPos); splitMsgEnc = cmdGenerator(splitMsg); overrun = userInputHandler()->lastParamOverrun(cmd, splitMsgEnc); } else { // If a split point could not be found (the beginning of the message // is reached without finding a split point short enough to send) and we // are still in Word mode, switch to Grapheme mode. We also need to restore // the full wrkMsg to splitMsg, since splitMsg may have been cut down during // the previous attempt to find a split point. if (qtbf.type() == QTextBoundaryFinder::Word) { splitMsg = wrkMsg; splitPos = splitMsg.size(); QTextBoundaryFinder graphemeQtbf(QTextBoundaryFinder::Grapheme, splitMsg); graphemeQtbf.setPosition(initialSplitMsgEnc[1].size() - initialOverrun); qtbf = graphemeQtbf; } else { // If the QTBF fails to find a split point in Grapheme mode, we give up. // This should never happen, but it should be handled anyway. qWarning() << "Unexpected failure to split message!"; return msgsToSend; } } } // Once a message of sendable length has been found, remove it from the wrkMsg and // add it to the list of messages to be sent. wrkMsg.remove(0, splitPos); msgsToSend.append(splitMsgEnc); } else{ // If the entire remaining message is short enough to be sent all at once, remove // it from the wrkMsg and add it to the list of messages to be sent. wrkMsg.remove(0, splitPos); msgsToSend.append(initialSplitMsgEnc); } } while (wrkMsg.size() > 0); return msgsToSend; }
./CrossVul/dataset_final_sorted/CWE-399/cpp/good_1539_2
crossvul-cpp_data_bad_3566_0
/* * Copyright (C) 2004-2011 See the AUTHORS file for details. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. */ #include "zncconfig.h" #include "znc.h" #include "User.h" #include "Modules.h" #include "Socket.h" #include "FileUtils.h" class CBounceDCCMod; class CDCCBounce : public CSocket { public: CDCCBounce(CBounceDCCMod* pMod, unsigned long uLongIP, unsigned short uPort, const CString& sFileName, const CString& sRemoteNick, const CString& sRemoteIP, bool bIsChat = false); CDCCBounce(CBounceDCCMod* pMod, const CString& sHostname, unsigned short uPort, const CString& sRemoteNick, const CString& sRemoteIP, const CString& sFileName, int iTimeout = 60, bool bIsChat = false); virtual ~CDCCBounce(); static unsigned short DCCRequest(const CString& sNick, unsigned long uLongIP, unsigned short uPort, const CString& sFileName, bool bIsChat, CBounceDCCMod* pMod, const CString& sRemoteIP); void ReadLine(const CString& sData); virtual void ReadData(const char* data, size_t len); virtual void ReadPaused(); virtual void Timeout(); virtual void ConnectionRefused(); virtual void ReachedMaxBuffer(); virtual void SockError(int iErrno); virtual void Connected(); virtual void Disconnected(); virtual Csock* GetSockObj(const CString& sHost, unsigned short uPort); void Shutdown(); void PutServ(const CString& sLine); void PutPeer(const CString& sLine); bool IsPeerConnected() { return (m_pPeer) ? m_pPeer->IsConnected() : false; } // Setters void SetPeer(CDCCBounce* p) { m_pPeer = p; } void SetRemoteIP(const CString& s) { m_sRemoteIP = s; } void SetRemoteNick(const CString& s) { m_sRemoteNick = s; } void SetRemote(bool b) { m_bIsRemote = b; } // !Setters // Getters unsigned short GetUserPort() const { return m_uRemotePort; } const CString& GetRemoteIP() const { return m_sRemoteIP; } const CString& GetRemoteNick() const { return m_sRemoteNick; } const CString& GetFileName() const { return m_sFileName; } CDCCBounce* GetPeer() const { return m_pPeer; } bool IsRemote() { return m_bIsRemote; } bool IsChat() { return m_bIsChat; } // !Getters private: protected: CString m_sRemoteNick; CString m_sRemoteIP; CString m_sConnectIP; CString m_sLocalIP; CString m_sFileName; CBounceDCCMod* m_pModule; CDCCBounce* m_pPeer; unsigned short m_uRemotePort; bool m_bIsChat; bool m_bIsRemote; static const unsigned int m_uiMaxDCCBuffer; static const unsigned int m_uiMinDCCBuffer; }; // If we buffer more than this in memory, we will throttle the receiving side const unsigned int CDCCBounce::m_uiMaxDCCBuffer = 10 * 1024; // If less than this is in the buffer, the receiving side continues const unsigned int CDCCBounce::m_uiMinDCCBuffer = 2 * 1024; class CBounceDCCMod : public CModule { public: void ListDCCsCommand(const CString& sLine) { CTable Table; Table.AddColumn("Type"); Table.AddColumn("State"); Table.AddColumn("Speed"); Table.AddColumn("Nick"); Table.AddColumn("IP"); Table.AddColumn("File"); set<CSocket*>::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { CDCCBounce* pSock = (CDCCBounce*) *it; CString sSockName = pSock->GetSockName(); if (!(pSock->IsRemote())) { Table.AddRow(); Table.SetCell("Nick", pSock->GetRemoteNick()); Table.SetCell("IP", pSock->GetRemoteIP()); if (pSock->IsChat()) { Table.SetCell("Type", "Chat"); } else { Table.SetCell("Type", "Xfer"); Table.SetCell("File", pSock->GetFileName()); } CString sState = "Waiting"; if ((pSock->IsConnected()) || (pSock->IsPeerConnected())) { sState = "Halfway"; if ((pSock->IsPeerConnected()) && (pSock->IsPeerConnected())) { sState = "Connected"; } } Table.SetCell("State", sState); } } if (PutModule(Table) == 0) { PutModule("You have no active DCCs."); } } void UseClientIPCommand(const CString& sLine) { CString sValue = sLine.Token(1, true); if (!sValue.empty()) { SetNV("UseClientIP", sValue); } PutModule("UseClientIP: " + CString(GetNV("UseClientIP").ToBool())); } MODCONSTRUCTOR(CBounceDCCMod) { AddHelpCommand(); AddCommand("ListDCCs", static_cast<CModCommand::ModCmdFunc>(&CBounceDCCMod::ListDCCsCommand), "", "List all active DCCs"); AddCommand("UseClientIP", static_cast<CModCommand::ModCmdFunc>(&CBounceDCCMod::UseClientIPCommand), "<true|false>"); } virtual ~CBounceDCCMod() {} CString GetLocalDCCIP() { return m_pUser->GetLocalDCCIP(); } bool UseClientIP() { return GetNV("UseClientIP").ToBool(); } virtual EModRet OnUserCTCP(CString& sTarget, CString& sMessage) { if (sMessage.Equals("DCC ", false, 4)) { CString sType = sMessage.Token(1); CString sFile = sMessage.Token(2); unsigned long uLongIP = sMessage.Token(3).ToULong(); unsigned short uPort = sMessage.Token(4).ToUShort(); unsigned long uFileSize = sMessage.Token(5).ToULong(); CString sIP = GetLocalDCCIP(); if (!UseClientIP()) { uLongIP = CUtils::GetLongIP(m_pClient->GetRemoteIP()); } if (sType.Equals("CHAT")) { unsigned short uBNCPort = CDCCBounce::DCCRequest(sTarget, uLongIP, uPort, "", true, this, ""); if (uBNCPort) { PutIRC("PRIVMSG " + sTarget + " :\001DCC CHAT chat " + CString(CUtils::GetLongIP(sIP)) + " " + CString(uBNCPort) + "\001"); } } else if (sType.Equals("SEND")) { // DCC SEND readme.txt 403120438 5550 1104 unsigned short uBNCPort = CDCCBounce::DCCRequest(sTarget, uLongIP, uPort, sFile, false, this, ""); if (uBNCPort) { PutIRC("PRIVMSG " + sTarget + " :\001DCC SEND " + sFile + " " + CString(CUtils::GetLongIP(sIP)) + " " + CString(uBNCPort) + " " + CString(uFileSize) + "\001"); } } else if (sType.Equals("RESUME")) { // PRIVMSG user :DCC RESUME "znc.o" 58810 151552 unsigned short uResumePort = sMessage.Token(3).ToUShort(); set<CSocket*>::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { CDCCBounce* pSock = (CDCCBounce*) *it; if (pSock->GetLocalPort() == uResumePort) { PutIRC("PRIVMSG " + sTarget + " :\001DCC " + sType + " " + sFile + " " + CString(pSock->GetUserPort()) + " " + sMessage.Token(4) + "\001"); } } } else if (sType.Equals("ACCEPT")) { // Need to lookup the connection by port, filter the port, and forward to the user set<CSocket*>::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { CDCCBounce* pSock = (CDCCBounce*) *it; if (pSock->GetUserPort() == sMessage.Token(3).ToUShort()) { PutIRC("PRIVMSG " + sTarget + " :\001DCC " + sType + " " + sFile + " " + CString(pSock->GetLocalPort()) + " " + sMessage.Token(4) + "\001"); } } } return HALTCORE; } return CONTINUE; } virtual EModRet OnPrivCTCP(CNick& Nick, CString& sMessage) { if (sMessage.Equals("DCC ", false, 4) && m_pUser->IsUserAttached()) { // DCC CHAT chat 2453612361 44592 CString sType = sMessage.Token(1); CString sFile = sMessage.Token(2); unsigned long uLongIP = sMessage.Token(3).ToULong(); unsigned short uPort = sMessage.Token(4).ToUShort(); unsigned long uFileSize = sMessage.Token(5).ToULong(); if (sType.Equals("CHAT")) { CNick FromNick(Nick.GetNickMask()); unsigned short uBNCPort = CDCCBounce::DCCRequest(FromNick.GetNick(), uLongIP, uPort, "", true, this, CUtils::GetIP(uLongIP)); if (uBNCPort) { CString sIP = GetLocalDCCIP(); m_pUser->PutUser(":" + Nick.GetNickMask() + " PRIVMSG " + m_pUser->GetNick() + " :\001DCC CHAT chat " + CString(CUtils::GetLongIP(sIP)) + " " + CString(uBNCPort) + "\001"); } } else if (sType.Equals("SEND")) { // DCC SEND readme.txt 403120438 5550 1104 unsigned short uBNCPort = CDCCBounce::DCCRequest(Nick.GetNick(), uLongIP, uPort, sFile, false, this, CUtils::GetIP(uLongIP)); if (uBNCPort) { CString sIP = GetLocalDCCIP(); m_pUser->PutUser(":" + Nick.GetNickMask() + " PRIVMSG " + m_pUser->GetNick() + " :\001DCC SEND " + sFile + " " + CString(CUtils::GetLongIP(sIP)) + " " + CString(uBNCPort) + " " + CString(uFileSize) + "\001"); } } else if (sType.Equals("RESUME")) { // Need to lookup the connection by port, filter the port, and forward to the user unsigned short uResumePort = sMessage.Token(3).ToUShort(); set<CSocket*>::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { CDCCBounce* pSock = (CDCCBounce*) *it; if (pSock->GetLocalPort() == uResumePort) { m_pUser->PutUser(":" + Nick.GetNickMask() + " PRIVMSG " + m_pClient->GetNick() + " :\001DCC " + sType + " " + sFile + " " + CString(pSock->GetUserPort()) + " " + sMessage.Token(4) + "\001"); } } } else if (sType.Equals("ACCEPT")) { // Need to lookup the connection by port, filter the port, and forward to the user set<CSocket*>::const_iterator it; for (it = BeginSockets(); it != EndSockets(); ++it) { CDCCBounce* pSock = (CDCCBounce*) *it; if (pSock->GetUserPort() == sMessage.Token(3).ToUShort()) { m_pUser->PutUser(":" + Nick.GetNickMask() + " PRIVMSG " + m_pClient->GetNick() + " :\001DCC " + sType + " " + sFile + " " + CString(pSock->GetLocalPort()) + " " + sMessage.Token(4) + "\001"); } } } return HALTCORE; } return CONTINUE; } }; CDCCBounce::CDCCBounce(CBounceDCCMod* pMod, unsigned long uLongIP, unsigned short uPort, const CString& sFileName, const CString& sRemoteNick, const CString& sRemoteIP, bool bIsChat) : CSocket(pMod) { m_uRemotePort = uPort; m_sConnectIP = CUtils::GetIP(uLongIP); m_sRemoteIP = sRemoteIP; m_sFileName = sFileName; m_sRemoteNick = sRemoteNick; m_pModule = pMod; m_bIsChat = bIsChat; m_sLocalIP = pMod->GetLocalDCCIP(); m_pPeer = NULL; m_bIsRemote = false; if (bIsChat) { EnableReadLine(); } else { DisableReadLine(); } } CDCCBounce::CDCCBounce(CBounceDCCMod* pMod, const CString& sHostname, unsigned short uPort, const CString& sRemoteNick, const CString& sRemoteIP, const CString& sFileName, int iTimeout, bool bIsChat) : CSocket(pMod, sHostname, uPort, iTimeout) { m_uRemotePort = 0; m_bIsChat = bIsChat; m_pModule = pMod; m_pPeer = NULL; m_sRemoteNick = sRemoteNick; m_sFileName = sFileName; m_sRemoteIP = sRemoteIP; m_bIsRemote = false; SetMaxBufferThreshold(10240); if (bIsChat) { EnableReadLine(); } else { DisableReadLine(); } } CDCCBounce::~CDCCBounce() { if (m_pPeer) { m_pPeer->Shutdown(); m_pPeer = NULL; } } void CDCCBounce::ReadLine(const CString& sData) { CString sLine = sData.TrimRight_n("\r\n"); DEBUG(GetSockName() << " <- [" << sLine << "]"); PutPeer(sLine); } void CDCCBounce::ReachedMaxBuffer() { DEBUG(GetSockName() << " == ReachedMaxBuffer()"); CString sType = (m_bIsChat) ? "Chat" : "Xfer"; m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + "): Too long line received"); Close(); } void CDCCBounce::ReadData(const char* data, size_t len) { if (m_pPeer) { m_pPeer->Write(data, len); size_t BufLen = m_pPeer->GetInternalWriteBuffer().length(); if (BufLen >= m_uiMaxDCCBuffer) { DEBUG(GetSockName() << " The send buffer is over the " "limit (" << BufLen <<"), throttling"); PauseRead(); } } } void CDCCBounce::ReadPaused() { if (!m_pPeer || m_pPeer->GetInternalWriteBuffer().length() <= m_uiMinDCCBuffer) UnPauseRead(); } void CDCCBounce::Timeout() { DEBUG(GetSockName() << " == Timeout()"); CString sType = (m_bIsChat) ? "Chat" : "Xfer"; if (IsRemote()) { CString sHost = Csock::GetHostName(); if (!sHost.empty()) { sHost = " to [" + sHost + " " + CString(Csock::GetPort()) + "]"; } else { sHost = "."; } m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + "): Timeout while connecting" + sHost); } else { m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + "): Timeout waiting for incoming connection [" + Csock::GetLocalIP() + ":" + CString(Csock::GetLocalPort()) + "]"); } } void CDCCBounce::ConnectionRefused() { DEBUG(GetSockName() << " == ConnectionRefused()"); CString sType = (m_bIsChat) ? "Chat" : "Xfer"; CString sHost = Csock::GetHostName(); if (!sHost.empty()) { sHost = " to [" + sHost + " " + CString(Csock::GetPort()) + "]"; } else { sHost = "."; } m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + "): Connection Refused while connecting" + sHost); } void CDCCBounce::SockError(int iErrno) { DEBUG(GetSockName() << " == SockError(" << iErrno << ")"); CString sType = (m_bIsChat) ? "Chat" : "Xfer"; if (IsRemote()) { CString sHost = Csock::GetHostName(); if (!sHost.empty()) { sHost = "[" + sHost + " " + CString(Csock::GetPort()) + "]"; } m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + "): Socket error [" + CString(strerror(iErrno)) + "]" + sHost); } else { m_pModule->PutModule("DCC " + sType + " Bounce (" + m_sRemoteNick + "): Socket error [" + CString(strerror(iErrno)) + "] [" + Csock::GetLocalIP() + ":" + CString(Csock::GetLocalPort()) + "]"); } } void CDCCBounce::Connected() { SetTimeout(0); DEBUG(GetSockName() << " == Connected()"); } void CDCCBounce::Disconnected() { DEBUG(GetSockName() << " == Disconnected()"); } void CDCCBounce::Shutdown() { m_pPeer = NULL; DEBUG(GetSockName() << " == Close(); because my peer told me to"); Close(); } Csock* CDCCBounce::GetSockObj(const CString& sHost, unsigned short uPort) { Close(); if (m_sRemoteIP.empty()) { m_sRemoteIP = sHost; } CDCCBounce* pSock = new CDCCBounce(m_pModule, sHost, uPort, m_sRemoteNick, m_sRemoteIP, m_sFileName, m_bIsChat); CDCCBounce* pRemoteSock = new CDCCBounce(m_pModule, sHost, uPort, m_sRemoteNick, m_sRemoteIP, m_sFileName, m_bIsChat); pSock->SetPeer(pRemoteSock); pRemoteSock->SetPeer(pSock); pRemoteSock->SetRemote(true); pSock->SetRemote(false); if (!CZNC::Get().GetManager().Connect(m_sConnectIP, m_uRemotePort, "DCC::" + CString((m_bIsChat) ? "Chat" : "XFER") + "::Remote::" + m_sRemoteNick, 60, false, m_sLocalIP, pRemoteSock)) { pRemoteSock->Close(); } pSock->SetSockName(GetSockName()); return pSock; } void CDCCBounce::PutServ(const CString& sLine) { DEBUG(GetSockName() << " -> [" << sLine << "]"); Write(sLine + "\r\n"); } void CDCCBounce::PutPeer(const CString& sLine) { if (m_pPeer) { m_pPeer->PutServ(sLine); } else { PutServ("*** Not connected yet ***"); } } unsigned short CDCCBounce::DCCRequest(const CString& sNick, unsigned long uLongIP, unsigned short uPort, const CString& sFileName, bool bIsChat, CBounceDCCMod* pMod, const CString& sRemoteIP) { CDCCBounce* pDCCBounce = new CDCCBounce(pMod, uLongIP, uPort, sFileName, sNick, sRemoteIP, bIsChat); unsigned short uListenPort = CZNC::Get().GetManager().ListenRand("DCC::" + CString((bIsChat) ? "Chat" : "Xfer") + "::Local::" + sNick, pMod->GetLocalDCCIP(), false, SOMAXCONN, pDCCBounce, 120); return uListenPort; } MODULEDEFS(CBounceDCCMod, "Bounce DCC module")
./CrossVul/dataset_final_sorted/CWE-399/cpp/bad_3566_0
crossvul-cpp_data_good_1539_6
/*************************************************************************** * Copyright (C) 2005-2015 by the Quassel Project * * devel@quassel-irc.org * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) version 3. * * * * 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 "ctcpparser.h" #include "corenetworkconfig.h" #include "coresession.h" #include "ctcpevent.h" #include "messageevent.h" #include "coreuserinputhandler.h" const QByteArray XDELIM = "\001"; CtcpParser::CtcpParser(CoreSession *coreSession, QObject *parent) : QObject(parent), _coreSession(coreSession) { QByteArray MQUOTE = QByteArray("\020"); _ctcpMDequoteHash[MQUOTE + '0'] = QByteArray(1, '\000'); _ctcpMDequoteHash[MQUOTE + 'n'] = QByteArray(1, '\n'); _ctcpMDequoteHash[MQUOTE + 'r'] = QByteArray(1, '\r'); _ctcpMDequoteHash[MQUOTE + MQUOTE] = MQUOTE; setStandardCtcp(_coreSession->networkConfig()->standardCtcp()); connect(_coreSession->networkConfig(), SIGNAL(standardCtcpSet(bool)), this, SLOT(setStandardCtcp(bool))); connect(this, SIGNAL(newEvent(Event *)), _coreSession->eventManager(), SLOT(postEvent(Event *))); } void CtcpParser::setStandardCtcp(bool enabled) { QByteArray XQUOTE = QByteArray("\134"); if (enabled) _ctcpXDelimDequoteHash[XQUOTE + XQUOTE] = XQUOTE; else _ctcpXDelimDequoteHash.remove(XQUOTE + XQUOTE); _ctcpXDelimDequoteHash[XQUOTE + QByteArray("a")] = XDELIM; } void CtcpParser::displayMsg(NetworkEvent *event, Message::Type msgType, const QString &msg, const QString &sender, const QString &target, Message::Flags msgFlags) { if (event->testFlag(EventManager::Silent)) return; MessageEvent *msgEvent = new MessageEvent(msgType, event->network(), msg, sender, target, msgFlags); msgEvent->setTimestamp(event->timestamp()); emit newEvent(msgEvent); } QByteArray CtcpParser::lowLevelQuote(const QByteArray &message) { QByteArray quotedMessage = message; QHash<QByteArray, QByteArray> quoteHash = _ctcpMDequoteHash; QByteArray MQUOTE = QByteArray("\020"); quoteHash.remove(MQUOTE + MQUOTE); quotedMessage.replace(MQUOTE, MQUOTE + MQUOTE); QHash<QByteArray, QByteArray>::const_iterator quoteIter = quoteHash.constBegin(); while (quoteIter != quoteHash.constEnd()) { quotedMessage.replace(quoteIter.value(), quoteIter.key()); quoteIter++; } return quotedMessage; } QByteArray CtcpParser::lowLevelDequote(const QByteArray &message) { QByteArray dequotedMessage; QByteArray messagepart; QHash<QByteArray, QByteArray>::iterator ctcpquote; // copy dequote Message for (int i = 0; i < message.size(); i++) { messagepart = message.mid(i, 1); if (i+1 < message.size()) { for (ctcpquote = _ctcpMDequoteHash.begin(); ctcpquote != _ctcpMDequoteHash.end(); ++ctcpquote) { if (message.mid(i, 2) == ctcpquote.key()) { messagepart = ctcpquote.value(); ++i; break; } } } dequotedMessage += messagepart; } return dequotedMessage; } QByteArray CtcpParser::xdelimQuote(const QByteArray &message) { QByteArray quotedMessage = message; QHash<QByteArray, QByteArray>::const_iterator quoteIter = _ctcpXDelimDequoteHash.constBegin(); while (quoteIter != _ctcpXDelimDequoteHash.constEnd()) { quotedMessage.replace(quoteIter.value(), quoteIter.key()); quoteIter++; } return quotedMessage; } QByteArray CtcpParser::xdelimDequote(const QByteArray &message) { QByteArray dequotedMessage; QByteArray messagepart; QHash<QByteArray, QByteArray>::iterator xdelimquote; for (int i = 0; i < message.size(); i++) { messagepart = message.mid(i, 1); if (i+1 < message.size()) { for (xdelimquote = _ctcpXDelimDequoteHash.begin(); xdelimquote != _ctcpXDelimDequoteHash.end(); ++xdelimquote) { if (message.mid(i, 2) == xdelimquote.key()) { messagepart = xdelimquote.value(); i++; break; } } } dequotedMessage += messagepart; } return dequotedMessage; } void CtcpParser::processIrcEventRawNotice(IrcEventRawMessage *event) { parse(event, Message::Notice); } void CtcpParser::processIrcEventRawPrivmsg(IrcEventRawMessage *event) { parse(event, Message::Plain); } void CtcpParser::parse(IrcEventRawMessage *e, Message::Type messagetype) { //lowlevel message dequote QByteArray dequotedMessage = lowLevelDequote(e->rawMessage()); CtcpEvent::CtcpType ctcptype = e->type() == EventManager::IrcEventRawNotice ? CtcpEvent::Reply : CtcpEvent::Query; Message::Flags flags = (ctcptype == CtcpEvent::Reply && !e->network()->isChannelName(e->target())) ? Message::Redirected : Message::None; if (coreSession()->networkConfig()->standardCtcp()) parseStandard(e, messagetype, dequotedMessage, ctcptype, flags); else parseSimple(e, messagetype, dequotedMessage, ctcptype, flags); } // only accept CTCPs in their simplest form, i.e. one ctcp, from start to // end, no text around it; not as per the 'specs', but makes people happier void CtcpParser::parseSimple(IrcEventRawMessage *e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags) { if (dequotedMessage.count(XDELIM) != 2 || dequotedMessage[0] != '\001' || dequotedMessage[dequotedMessage.count() -1] != '\001') { displayMsg(e, messagetype, targetDecode(e, dequotedMessage), e->prefix(), e->target(), flags); } else { int spacePos = -1; QString ctcpcmd, ctcpparam; QByteArray ctcp = xdelimDequote(dequotedMessage.mid(1, dequotedMessage.count() - 2)); spacePos = ctcp.indexOf(' '); if (spacePos != -1) { ctcpcmd = targetDecode(e, ctcp.left(spacePos)); ctcpparam = targetDecode(e, ctcp.mid(spacePos + 1)); } else { ctcpcmd = targetDecode(e, ctcp); ctcpparam = QString(); } ctcpcmd = ctcpcmd.toUpper(); // we don't want to block /me messages by the CTCP ignore list if (ctcpcmd == QLatin1String("ACTION") || !coreSession()->ignoreListManager()->ctcpMatch(e->prefix(), e->network()->networkName(), ctcpcmd)) { QUuid uuid = QUuid::createUuid(); _replies.insert(uuid, CtcpReply(coreNetwork(e), nickFromMask(e->prefix()))); CtcpEvent *event = new CtcpEvent(EventManager::CtcpEvent, e->network(), e->prefix(), e->target(), ctcptype, ctcpcmd, ctcpparam, e->timestamp(), uuid); emit newEvent(event); CtcpEvent *flushEvent = new CtcpEvent(EventManager::CtcpEventFlush, e->network(), e->prefix(), e->target(), ctcptype, "INVALID", QString(), e->timestamp(), uuid); emit newEvent(flushEvent); } } } void CtcpParser::parseStandard(IrcEventRawMessage *e, Message::Type messagetype, QByteArray dequotedMessage, CtcpEvent::CtcpType ctcptype, Message::Flags flags) { QByteArray ctcp; QList<CtcpEvent *> ctcpEvents; QUuid uuid; // needed to group all replies together // extract tagged / extended data int xdelimPos = -1; int xdelimEndPos = -1; int spacePos = -1; while ((xdelimPos = dequotedMessage.indexOf(XDELIM)) != -1) { if (xdelimPos > 0) displayMsg(e, messagetype, targetDecode(e, dequotedMessage.left(xdelimPos)), e->prefix(), e->target(), flags); xdelimEndPos = dequotedMessage.indexOf(XDELIM, xdelimPos + 1); if (xdelimEndPos == -1) { // no matching end delimiter found... treat rest of the message as ctcp xdelimEndPos = dequotedMessage.count(); } ctcp = xdelimDequote(dequotedMessage.mid(xdelimPos + 1, xdelimEndPos - xdelimPos - 1)); dequotedMessage = dequotedMessage.mid(xdelimEndPos + 1); //dispatch the ctcp command QString ctcpcmd = targetDecode(e, ctcp.left(spacePos)); QString ctcpparam = targetDecode(e, ctcp.mid(spacePos + 1)); spacePos = ctcp.indexOf(' '); if (spacePos != -1) { ctcpcmd = targetDecode(e, ctcp.left(spacePos)); ctcpparam = targetDecode(e, ctcp.mid(spacePos + 1)); } else { ctcpcmd = targetDecode(e, ctcp); ctcpparam = QString(); } ctcpcmd = ctcpcmd.toUpper(); // we don't want to block /me messages by the CTCP ignore list if (ctcpcmd == QLatin1String("ACTION") || !coreSession()->ignoreListManager()->ctcpMatch(e->prefix(), e->network()->networkName(), ctcpcmd)) { if (uuid.isNull()) uuid = QUuid::createUuid(); CtcpEvent *event = new CtcpEvent(EventManager::CtcpEvent, e->network(), e->prefix(), e->target(), ctcptype, ctcpcmd, ctcpparam, e->timestamp(), uuid); ctcpEvents << event; } } if (!ctcpEvents.isEmpty()) { _replies.insert(uuid, CtcpReply(coreNetwork(e), nickFromMask(e->prefix()))); CtcpEvent *flushEvent = new CtcpEvent(EventManager::CtcpEventFlush, e->network(), e->prefix(), e->target(), ctcptype, "INVALID", QString(), e->timestamp(), uuid); ctcpEvents << flushEvent; foreach(CtcpEvent *event, ctcpEvents) { emit newEvent(event); } } if (!dequotedMessage.isEmpty()) displayMsg(e, messagetype, targetDecode(e, dequotedMessage), e->prefix(), e->target(), flags); } void CtcpParser::sendCtcpEvent(CtcpEvent *e) { CoreNetwork *net = coreNetwork(e); if (e->type() == EventManager::CtcpEvent) { QByteArray quotedReply; QString bufname = nickFromMask(e->prefix()); if (e->ctcpType() == CtcpEvent::Query && !e->reply().isNull()) { if (_replies.contains(e->uuid())) _replies[e->uuid()].replies << lowLevelQuote(pack(net->serverEncode(e->ctcpCmd()), net->userEncode(bufname, e->reply()))); else // reply not caused by a request processed in here, so send it off immediately reply(net, bufname, e->ctcpCmd(), e->reply()); } } else if (e->type() == EventManager::CtcpEventFlush && _replies.contains(e->uuid())) { CtcpReply reply = _replies.take(e->uuid()); if (reply.replies.count()) packedReply(net, reply.bufferName, reply.replies); } } QByteArray CtcpParser::pack(const QByteArray &ctcpTag, const QByteArray &message) { if (message.isEmpty()) return XDELIM + ctcpTag + XDELIM; return XDELIM + ctcpTag + ' ' + xdelimQuote(message) + XDELIM; } void CtcpParser::query(CoreNetwork *net, const QString &bufname, const QString &ctcpTag, const QString &message) { QString cmd("PRIVMSG"); std::function<QList<QByteArray>(QString &)> cmdGenerator = [&] (QString &splitMsg) -> QList<QByteArray> { return QList<QByteArray>() << net->serverEncode(bufname) << lowLevelQuote(pack(net->serverEncode(ctcpTag), net->userEncode(bufname, splitMsg))); }; net->putCmd(cmd, net->splitMessage(cmd, message, cmdGenerator)); } void CtcpParser::reply(CoreNetwork *net, const QString &bufname, const QString &ctcpTag, const QString &message) { QList<QByteArray> params; params << net->serverEncode(bufname) << lowLevelQuote(pack(net->serverEncode(ctcpTag), net->userEncode(bufname, message))); net->putCmd("NOTICE", params); } void CtcpParser::packedReply(CoreNetwork *net, const QString &bufname, const QList<QByteArray> &replies) { QList<QByteArray> params; int answerSize = 0; for (int i = 0; i < replies.count(); i++) { answerSize += replies.at(i).size(); } QByteArray quotedReply; quotedReply.reserve(answerSize); for (int i = 0; i < replies.count(); i++) { quotedReply.append(replies.at(i)); } params << net->serverEncode(bufname) << quotedReply; // FIXME user proper event net->putCmd("NOTICE", params); }
./CrossVul/dataset_final_sorted/CWE-399/cpp/good_1539_6
crossvul-cpp_data_good_1539_4
/*************************************************************************** * Copyright (C) 2005-2015 by the Quassel Project * * devel@quassel-irc.org * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) version 3. * * * * 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 "coreuserinputhandler.h" #include "util.h" #include "ctcpparser.h" #include <QRegExp> #ifdef HAVE_QCA2 # include "cipher.h" #endif CoreUserInputHandler::CoreUserInputHandler(CoreNetwork *parent) : CoreBasicHandler(parent) { } void CoreUserInputHandler::handleUserInput(const BufferInfo &bufferInfo, const QString &msg) { if (msg.isEmpty()) return; AliasManager::CommandList list = coreSession()->aliasManager().processInput(bufferInfo, msg); for (int i = 0; i < list.count(); i++) { QString cmd = list.at(i).second.section(' ', 0, 0).remove(0, 1).toUpper(); QString payload = list.at(i).second.section(' ', 1); handle(cmd, Q_ARG(BufferInfo, list.at(i).first), Q_ARG(QString, payload)); } } // ==================== // Public Slots // ==================== void CoreUserInputHandler::handleAway(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) if (msg.startsWith("-all")) { if (msg.length() == 4) { coreSession()->globalAway(); return; } Q_ASSERT(msg.length() > 4); if (msg[4] == ' ') { coreSession()->globalAway(msg.mid(5)); return; } } issueAway(msg); } void CoreUserInputHandler::issueAway(const QString &msg, bool autoCheck) { QString awayMsg = msg; IrcUser *me = network()->me(); // if there is no message supplied we have to check if we are already away or not if (autoCheck && msg.isEmpty()) { if (me && !me->isAway()) { Identity *identity = network()->identityPtr(); if (identity) { awayMsg = identity->awayReason(); } if (awayMsg.isEmpty()) { awayMsg = tr("away"); } } } if (me) me->setAwayMessage(awayMsg); putCmd("AWAY", serverEncode(awayMsg)); } void CoreUserInputHandler::handleBan(const BufferInfo &bufferInfo, const QString &msg) { banOrUnban(bufferInfo, msg, true); } void CoreUserInputHandler::handleUnban(const BufferInfo &bufferInfo, const QString &msg) { banOrUnban(bufferInfo, msg, false); } void CoreUserInputHandler::banOrUnban(const BufferInfo &bufferInfo, const QString &msg, bool ban) { QString banChannel; QString banUser; QStringList params = msg.split(" "); if (!params.isEmpty() && isChannelName(params[0])) { banChannel = params.takeFirst(); } else if (bufferInfo.type() == BufferInfo::ChannelBuffer) { banChannel = bufferInfo.bufferName(); } else { emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: channel unknown in command: /BAN %1").arg(msg)); return; } if (!params.isEmpty() && !params.contains("!") && network()->ircUser(params[0])) { IrcUser *ircuser = network()->ircUser(params[0]); // generalizedHost changes <nick> to *!ident@*.sld.tld. QString generalizedHost = ircuser->host(); if (generalizedHost.isEmpty()) { emit displayMsg(Message::Error, BufferInfo::StatusBuffer, "", QString("Error: host unknown in command: /BAN %1").arg(msg)); return; } static QRegExp ipAddress("\\d+\\.\\d+\\.\\d+\\.\\d+"); if (ipAddress.exactMatch(generalizedHost)) { int lastDotPos = generalizedHost.lastIndexOf('.') + 1; generalizedHost.replace(lastDotPos, generalizedHost.length() - lastDotPos, '*'); } else if (generalizedHost.lastIndexOf(".") != -1 && generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1) != -1) { int secondLastPeriodPosition = generalizedHost.lastIndexOf(".", generalizedHost.lastIndexOf(".")-1); generalizedHost.replace(0, secondLastPeriodPosition, "*"); } banUser = QString("*!%1@%2").arg(ircuser->user(), generalizedHost); } else { banUser = params.join(" "); } QString banMode = ban ? "+b" : "-b"; QString banMsg = QString("MODE %1 %2 %3").arg(banChannel, banMode, banUser); emit putRawLine(serverEncode(banMsg)); } void CoreUserInputHandler::handleCtcp(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) QString nick = msg.section(' ', 0, 0); QString ctcpTag = msg.section(' ', 1, 1).toUpper(); if (ctcpTag.isEmpty()) return; QString message = msg.section(' ', 2); QString verboseMessage = tr("sending CTCP-%1 request to %2").arg(ctcpTag).arg(nick); if (ctcpTag == "PING") { message = QString::number(QDateTime::currentMSecsSinceEpoch()); } // FIXME make this a proper event coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), nick, ctcpTag, message); emit displayMsg(Message::Action, BufferInfo::StatusBuffer, "", verboseMessage, network()->myNick()); } void CoreUserInputHandler::handleDelkey(const BufferInfo &bufferInfo, const QString &msg) { QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName(); #ifdef HAVE_QCA2 if (!bufferInfo.isValid()) return; if (!Cipher::neededFeaturesAvailable()) { emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")); return; } QStringList parms = msg.split(' ', QString::SkipEmptyParts); if (parms.isEmpty() && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages()) parms.prepend(bufferInfo.bufferName()); if (parms.isEmpty()) { emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("[usage] /delkey <nick|channel> deletes the encryption key for nick or channel or just /delkey when in a channel or query.")); return; } QString target = parms.at(0); if (network()->cipherKey(target).isEmpty()) { emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("No key has been set for %1.").arg(target)); return; } network()->setCipherKey(target, QByteArray()); emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 has been deleted.").arg(target)); #else Q_UNUSED(msg) emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built " "with support for the Qt Cryptographic Architecture (QCA2) library. " "Contact your distributor about a Quassel package with QCA2 " "support, or rebuild Quassel with QCA2 present.")); #endif } void CoreUserInputHandler::doMode(const BufferInfo &bufferInfo, const QChar& addOrRemove, const QChar& mode, const QString &nicks) { QString m; bool isNumber; int maxModes = network()->support("MODES").toInt(&isNumber); if (!isNumber || maxModes == 0) maxModes = 1; QStringList nickList; if (nicks == "*") { // All users in channel const QList<IrcUser*> users = network()->ircChannel(bufferInfo.bufferName())->ircUsers(); foreach(IrcUser *user, users) { if ((addOrRemove == '+' && !network()->ircChannel(bufferInfo.bufferName())->userModes(user).contains(mode)) || (addOrRemove == '-' && network()->ircChannel(bufferInfo.bufferName())->userModes(user).contains(mode))) nickList.append(user->nick()); } } else { nickList = nicks.split(' ', QString::SkipEmptyParts); } if (nickList.count() == 0) return; while (!nickList.isEmpty()) { int amount = qMin(nickList.count(), maxModes); QString m = addOrRemove; for(int i = 0; i < amount; i++) m += mode; QStringList params; params << bufferInfo.bufferName() << m; for(int i = 0; i < amount; i++) params << nickList.takeFirst(); emit putCmd("MODE", serverEncode(params)); } } void CoreUserInputHandler::handleDeop(const BufferInfo &bufferInfo, const QString &nicks) { doMode(bufferInfo, '-', 'o', nicks); } void CoreUserInputHandler::handleDehalfop(const BufferInfo &bufferInfo, const QString &nicks) { doMode(bufferInfo, '-', 'h', nicks); } void CoreUserInputHandler::handleDevoice(const BufferInfo &bufferInfo, const QString &nicks) { doMode(bufferInfo, '-', 'v', nicks); } void CoreUserInputHandler::handleHalfop(const BufferInfo &bufferInfo, const QString &nicks) { doMode(bufferInfo, '+', 'h', nicks); } void CoreUserInputHandler::handleOp(const BufferInfo &bufferInfo, const QString &nicks) { doMode(bufferInfo, '+', 'o', nicks); } void CoreUserInputHandler::handleInvite(const BufferInfo &bufferInfo, const QString &msg) { QStringList params; params << msg << bufferInfo.bufferName(); emit putCmd("INVITE", serverEncode(params)); } void CoreUserInputHandler::handleJoin(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo); // trim spaces before chans or keys QString sane_msg = msg; sane_msg.replace(QRegExp(", +"), ","); QStringList params = sane_msg.trimmed().split(" "); QStringList chans = params[0].split(",", QString::SkipEmptyParts); QStringList keys; if (params.count() > 1) keys = params[1].split(","); int i; for (i = 0; i < chans.count(); i++) { if (!network()->isChannelName(chans[i])) chans[i].prepend('#'); if (i < keys.count()) { network()->addChannelKey(chans[i], keys[i]); } else { network()->removeChannelKey(chans[i]); } } static const char *cmd = "JOIN"; i = 0; QStringList joinChans, joinKeys; int slicesize = chans.count(); QList<QByteArray> encodedParams; // go through all to-be-joined channels and (re)build the join list while (i < chans.count()) { joinChans.append(chans.at(i)); if (i < keys.count()) joinKeys.append(keys.at(i)); // if the channel list we built so far either contains all requested channels or exceeds // the desired amount of channels in this slice, try to send what we have so far if (++i == chans.count() || joinChans.count() >= slicesize) { params.clear(); params.append(joinChans.join(",")); params.append(joinKeys.join(",")); encodedParams = serverEncode(params); // check if it fits in one command if (lastParamOverrun(cmd, encodedParams) == 0) { emit putCmd(cmd, encodedParams); } else if (slicesize > 1) { // back to start of slice, try again with half the amount of channels i -= slicesize; slicesize /= 2; } joinChans.clear(); joinKeys.clear(); } } } void CoreUserInputHandler::handleKeyx(const BufferInfo &bufferInfo, const QString &msg) { QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName(); #ifdef HAVE_QCA2 if (!bufferInfo.isValid()) return; if (!Cipher::neededFeaturesAvailable()) { emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")); return; } QStringList parms = msg.split(' ', QString::SkipEmptyParts); if (parms.count() == 0 && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages()) parms.prepend(bufferInfo.bufferName()); else if (parms.count() != 1) { emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("[usage] /keyx [<nick>] Initiates a DH1080 key exchange with the target.")); return; } QString target = parms.at(0); if (network()->isChannelName(target)) { emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("It is only possible to exchange keys in a query buffer.")); return; } Cipher *cipher = network()->cipher(target); if (!cipher) // happens when there is no CoreIrcChannel for the target return; QByteArray pubKey = cipher->initKeyExchange(); if (pubKey.isEmpty()) emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Failed to initiate key exchange with %1.").arg(target)); else { QList<QByteArray> params; params << serverEncode(target) << serverEncode("DH1080_INIT ") + pubKey; emit putCmd("NOTICE", params); emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("Initiated key exchange with %1.").arg(target)); } #else Q_UNUSED(msg) emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built " "with support for the Qt Cryptographic Architecture (QCA) library. " "Contact your distributor about a Quassel package with QCA " "support, or rebuild Quassel with QCA present.")); #endif } void CoreUserInputHandler::handleKick(const BufferInfo &bufferInfo, const QString &msg) { QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty); QString reason = msg.section(' ', 1, -1, QString::SectionSkipEmpty).trimmed(); if (reason.isEmpty()) reason = network()->identityPtr()->kickReason(); QList<QByteArray> params; params << serverEncode(bufferInfo.bufferName()) << serverEncode(nick) << channelEncode(bufferInfo.bufferName(), reason); emit putCmd("KICK", params); } void CoreUserInputHandler::handleKill(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) QString nick = msg.section(' ', 0, 0, QString::SectionSkipEmpty); QString pass = msg.section(' ', 1, -1, QString::SectionSkipEmpty); QList<QByteArray> params; params << serverEncode(nick) << serverEncode(pass); emit putCmd("KILL", params); } void CoreUserInputHandler::handleList(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) emit putCmd("LIST", serverEncode(msg.split(' ', QString::SkipEmptyParts))); } void CoreUserInputHandler::handleMe(const BufferInfo &bufferInfo, const QString &msg) { if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages()) return; // server buffer // FIXME make this a proper event coreNetwork()->coreSession()->ctcpParser()->query(coreNetwork(), bufferInfo.bufferName(), "ACTION", msg); emit displayMsg(Message::Action, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self); } void CoreUserInputHandler::handleMode(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) QStringList params = msg.split(' ', QString::SkipEmptyParts); // if the first argument is neither a channel nor us (user modes are only to oneself) the current buffer is assumed to be the target if (!params.isEmpty()) { if (!network()->isChannelName(params[0]) && !network()->isMyNick(params[0])) params.prepend(bufferInfo.bufferName()); if (network()->isMyNick(params[0]) && params.count() == 2) network()->updateIssuedModes(params[1]); if (params[0] == "-reset" && params.count() == 1) { // FIXME: give feedback to the user (I don't want to add new strings right now) network()->resetPersistentModes(); return; } } // TODO handle correct encoding for buffer modes (channelEncode()) emit putCmd("MODE", serverEncode(params)); } // TODO: show privmsgs void CoreUserInputHandler::handleMsg(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo); if (!msg.contains(' ')) return; QString target = msg.section(' ', 0, 0); QString msgSection = msg.section(' ', 1); std::function<QByteArray(const QString &, const QString &)> encodeFunc = [this] (const QString &target, const QString &message) -> QByteArray { return userEncode(target, message); }; #ifdef HAVE_QCA2 putPrivmsg(target, msgSection, encodeFunc, network()->cipher(target)); #else putPrivmsg(target, msgSection, encodeFunc); #endif } void CoreUserInputHandler::handleNick(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) QString nick = msg.section(' ', 0, 0); emit putCmd("NICK", serverEncode(nick)); } void CoreUserInputHandler::handleNotice(const BufferInfo &bufferInfo, const QString &msg) { QString bufferName = msg.section(' ', 0, 0); QString payload = msg.section(' ', 1); QList<QByteArray> params; params << serverEncode(bufferName) << channelEncode(bufferInfo.bufferName(), payload); emit putCmd("NOTICE", params); emit displayMsg(Message::Notice, typeByTarget(bufferName), bufferName, payload, network()->myNick(), Message::Self); } void CoreUserInputHandler::handleOper(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) emit putRawLine(serverEncode(QString("OPER %1").arg(msg))); } void CoreUserInputHandler::handlePart(const BufferInfo &bufferInfo, const QString &msg) { QList<QByteArray> params; QString partReason; // msg might contain either a channel name and/or a reaon, so we have to check if the first word is a known channel QString channelName = msg.section(' ', 0, 0); if (channelName.isEmpty() || !network()->ircChannel(channelName)) { channelName = bufferInfo.bufferName(); partReason = msg; } else { partReason = msg.mid(channelName.length() + 1); } if (partReason.isEmpty()) partReason = network()->identityPtr()->partReason(); params << serverEncode(channelName) << channelEncode(bufferInfo.bufferName(), partReason); emit putCmd("PART", params); } void CoreUserInputHandler::handlePing(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) QString param = msg; if (param.isEmpty()) param = QTime::currentTime().toString("hh:mm:ss.zzz"); putCmd("PING", serverEncode(param)); } void CoreUserInputHandler::handlePrint(const BufferInfo &bufferInfo, const QString &msg) { if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages()) return; // server buffer QByteArray encMsg = channelEncode(bufferInfo.bufferName(), msg); emit displayMsg(Message::Info, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self); } // TODO: implement queries void CoreUserInputHandler::handleQuery(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) QString target = msg.section(' ', 0, 0); QString message = msg.section(' ', 1); if (message.isEmpty()) emit displayMsg(Message::Server, BufferInfo::QueryBuffer, target, tr("Starting query with %1").arg(target), network()->myNick(), Message::Self); else emit displayMsg(Message::Plain, BufferInfo::QueryBuffer, target, message, network()->myNick(), Message::Self); handleMsg(bufferInfo, msg); } void CoreUserInputHandler::handleQuit(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) network()->disconnectFromIrc(true, msg); } void CoreUserInputHandler::issueQuit(const QString &reason) { emit putCmd("QUIT", serverEncode(reason)); } void CoreUserInputHandler::handleQuote(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) emit putRawLine(serverEncode(msg)); } void CoreUserInputHandler::handleSay(const BufferInfo &bufferInfo, const QString &msg) { if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages()) return; // server buffer std::function<QByteArray(const QString &, const QString &)> encodeFunc = [this] (const QString &target, const QString &message) -> QByteArray { return channelEncode(target, message); }; #ifdef HAVE_QCA2 putPrivmsg(bufferInfo.bufferName(), msg, encodeFunc, network()->cipher(bufferInfo.bufferName())); #else putPrivmsg(bufferInfo.bufferName(), msg, encodeFunc); #endif emit displayMsg(Message::Plain, bufferInfo.type(), bufferInfo.bufferName(), msg, network()->myNick(), Message::Self); } void CoreUserInputHandler::handleSetkey(const BufferInfo &bufferInfo, const QString &msg) { QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName(); #ifdef HAVE_QCA2 if (!bufferInfo.isValid()) return; if (!Cipher::neededFeaturesAvailable()) { emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")); return; } QStringList parms = msg.split(' ', QString::SkipEmptyParts); if (parms.count() == 1 && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages()) parms.prepend(bufferInfo.bufferName()); else if (parms.count() != 2) { emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("[usage] /setkey <nick|channel> <key> sets the encryption key for nick or channel. " "/setkey <key> when in a channel or query buffer sets the key for it.")); return; } QString target = parms.at(0); QByteArray key = parms.at(1).toLocal8Bit(); network()->setCipherKey(target, key); emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 has been set.").arg(target)); #else Q_UNUSED(msg) emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built " "with support for the Qt Cryptographic Architecture (QCA) library. " "Contact your distributor about a Quassel package with QCA " "support, or rebuild Quassel with QCA present.")); #endif } void CoreUserInputHandler::handleShowkey(const BufferInfo &bufferInfo, const QString &msg) { QString bufname = bufferInfo.bufferName().isNull() ? "" : bufferInfo.bufferName(); #ifdef HAVE_QCA2 if (!bufferInfo.isValid()) return; if (!Cipher::neededFeaturesAvailable()) { emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: QCA provider plugin not found. It is usually provided by the qca-ossl plugin.")); return; } QStringList parms = msg.split(' ', QString::SkipEmptyParts); if (parms.isEmpty() && !bufferInfo.bufferName().isEmpty() && bufferInfo.acceptsRegularMessages()) parms.prepend(bufferInfo.bufferName()); if (parms.isEmpty()) { emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("[usage] /showkey <nick|channel> shows the encryption key for nick or channel or just /showkey when in a channel or query.")); return; } QString target = parms.at(0); QByteArray key = network()->cipherKey(target); if (key.isEmpty()) { emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("No key has been set for %1.").arg(target)); return; } emit displayMsg(Message::Info, typeByTarget(bufname), bufname, tr("The key for %1 is %2:%3").arg(target, network()->cipherUsesCBC(target) ? "CBC" : "ECB", QString(key))); #else Q_UNUSED(msg) emit displayMsg(Message::Error, typeByTarget(bufname), bufname, tr("Error: Setting an encryption key requires Quassel to have been built " "with support for the Qt Cryptographic Architecture (QCA2) library. " "Contact your distributor about a Quassel package with QCA2 " "support, or rebuild Quassel with QCA2 present.")); #endif } void CoreUserInputHandler::handleTopic(const BufferInfo &bufferInfo, const QString &msg) { if (bufferInfo.bufferName().isEmpty() || !bufferInfo.acceptsRegularMessages()) return; QList<QByteArray> params; params << serverEncode(bufferInfo.bufferName()); if (!msg.isEmpty()) { # ifdef HAVE_QCA2 params << encrypt(bufferInfo.bufferName(), channelEncode(bufferInfo.bufferName(), msg)); # else params << channelEncode(bufferInfo.bufferName(), msg); # endif } emit putCmd("TOPIC", params); } void CoreUserInputHandler::handleVoice(const BufferInfo &bufferInfo, const QString &msg) { QStringList nicks = msg.split(' ', QString::SkipEmptyParts); QString m = "+"; for (int i = 0; i < nicks.count(); i++) m += 'v'; QStringList params; params << bufferInfo.bufferName() << m << nicks; emit putCmd("MODE", serverEncode(params)); } void CoreUserInputHandler::handleWait(const BufferInfo &bufferInfo, const QString &msg) { int splitPos = msg.indexOf(';'); if (splitPos <= 0) return; bool ok; int delay = msg.left(splitPos).trimmed().toInt(&ok); if (!ok) return; delay *= 1000; QString command = msg.mid(splitPos + 1).trimmed(); if (command.isEmpty()) return; _delayedCommands[startTimer(delay)] = Command(bufferInfo, command); } void CoreUserInputHandler::handleWho(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) emit putCmd("WHO", serverEncode(msg.split(' '))); } void CoreUserInputHandler::handleWhois(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) emit putCmd("WHOIS", serverEncode(msg.split(' '))); } void CoreUserInputHandler::handleWhowas(const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo) emit putCmd("WHOWAS", serverEncode(msg.split(' '))); } void CoreUserInputHandler::defaultHandler(QString cmd, const BufferInfo &bufferInfo, const QString &msg) { Q_UNUSED(bufferInfo); emit putCmd(serverEncode(cmd.toUpper()), serverEncode(msg.split(" "))); } void CoreUserInputHandler::putPrivmsg(const QString &target, const QString &message, std::function<QByteArray(const QString &, const QString &)> encodeFunc, Cipher *cipher) { QString cmd("PRIVMSG"); QByteArray targetEnc = serverEncode(target); std::function<QList<QByteArray>(QString &)> cmdGenerator = [&] (QString &splitMsg) -> QList<QByteArray> { QByteArray splitMsgEnc = encodeFunc(target, splitMsg); #ifdef HAVE_QCA2 if (cipher && !cipher->key().isEmpty() && !splitMsg.isEmpty()) { cipher->encrypt(splitMsgEnc); } #endif return QList<QByteArray>() << targetEnc << splitMsgEnc; }; putCmd(cmd, network()->splitMessage(cmd, message, cmdGenerator)); } // returns 0 if the message will not be chopped by the irc server or number of chopped bytes if message is too long int CoreUserInputHandler::lastParamOverrun(const QString &cmd, const QList<QByteArray> &params) { // the server will pass our message truncated to 512 bytes including CRLF with the following format: // ":prefix COMMAND param0 param1 :lastparam" // where prefix = "nickname!user@host" // that means that the last message can be as long as: // 512 - nicklen - userlen - hostlen - commandlen - sum(param[0]..param[n-1])) - 2 (for CRLF) - 4 (":!@" + 1space between prefix and command) - max(paramcount - 1, 0) (space for simple params) - 2 (space and colon for last param) IrcUser *me = network()->me(); int maxLen = 480 - cmd.toLatin1().count(); // educated guess in case we don't know us (yet?) if (me) maxLen = 512 - serverEncode(me->nick()).count() - serverEncode(me->user()).count() - serverEncode(me->host()).count() - cmd.toLatin1().count() - 6; if (!params.isEmpty()) { for (int i = 0; i < params.count() - 1; i++) { maxLen -= (params[i].count() + 1); } maxLen -= 2; // " :" last param separator; if (params.last().count() > maxLen) { return params.last().count() - maxLen; } else { return 0; } } else { return 0; } } #ifdef HAVE_QCA2 QByteArray CoreUserInputHandler::encrypt(const QString &target, const QByteArray &message_, bool *didEncrypt) const { if (didEncrypt) *didEncrypt = false; if (message_.isEmpty()) return message_; if (!Cipher::neededFeaturesAvailable()) return message_; Cipher *cipher = network()->cipher(target); if (!cipher || cipher->key().isEmpty()) return message_; QByteArray message = message_; bool result = cipher->encrypt(message); if (didEncrypt) *didEncrypt = result; return message; } #endif void CoreUserInputHandler::timerEvent(QTimerEvent *event) { if (!_delayedCommands.contains(event->timerId())) { QObject::timerEvent(event); return; } BufferInfo bufferInfo = _delayedCommands[event->timerId()].bufferInfo; QString rawCommand = _delayedCommands[event->timerId()].command; _delayedCommands.remove(event->timerId()); event->accept(); // the stored command might be the result of an alias expansion, so we need to split it up again QStringList commands = rawCommand.split(QRegExp("; ?")); foreach(QString command, commands) { handleUserInput(bufferInfo, command); } }
./CrossVul/dataset_final_sorted/CWE-399/cpp/good_1539_4
crossvul-cpp_data_bad_5642_0
/* -*- C++ -*- * File: libraw_cxx.cpp * Copyright 2008-2013 LibRaw LLC (info@libraw.org) * Created: Sat Mar 8 , 2008 * * LibRaw C++ interface (implementation) LibRaw is free software; you can redistribute it and/or modify it under the terms of the one of three licenses as you choose: 1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1 (See file LICENSE.LGPL provided in LibRaw distribution archive for details). 2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 (See file LICENSE.CDDL provided in LibRaw distribution archive for details). 3. LibRaw Software License 27032010 (See file LICENSE.LibRaw.pdf provided in LibRaw distribution archive for details). */ #include <math.h> #include <errno.h> #include <float.h> #include <new> #include <exception> #include <sys/types.h> #include <sys/stat.h> #ifndef WIN32 #include <netinet/in.h> #else #include <winsock2.h> #endif #define LIBRAW_LIBRARY_BUILD #include "libraw/libraw.h" #include "internal/defines.h" #ifdef USE_RAWSPEED #include "../RawSpeed/rawspeed_xmldata.cpp" #include <RawSpeed/StdAfx.h> #include <RawSpeed/FileMap.h> #include <RawSpeed/RawParser.h> #include <RawSpeed/RawDecoder.h> #include <RawSpeed/CameraMetaData.h> #include <RawSpeed/ColorFilterArray.h> #endif #ifdef __cplusplus extern "C" { #endif void default_memory_callback(void *,const char *file,const char *where) { fprintf (stderr,"%s: Out of memory in %s\n", file?file:"unknown file", where); } void default_data_callback(void*,const char *file, const int offset) { if(offset < 0) fprintf (stderr,"%s: Unexpected end of file\n", file?file:"unknown file"); else fprintf (stderr,"%s: data corrupted at %d\n",file?file:"unknown file",offset); } const char *libraw_strerror(int e) { enum LibRaw_errors errorcode = (LibRaw_errors)e; switch(errorcode) { case LIBRAW_SUCCESS: return "No error"; case LIBRAW_UNSPECIFIED_ERROR: return "Unspecified error"; case LIBRAW_FILE_UNSUPPORTED: return "Unsupported file format or not RAW file"; case LIBRAW_REQUEST_FOR_NONEXISTENT_IMAGE: return "Request for nonexisting image number"; case LIBRAW_OUT_OF_ORDER_CALL: return "Out of order call of libraw function"; case LIBRAW_NO_THUMBNAIL: return "No thumbnail in file"; case LIBRAW_UNSUPPORTED_THUMBNAIL: return "Unsupported thumbnail format"; case LIBRAW_INPUT_CLOSED: return "No input stream, or input stream closed"; case LIBRAW_UNSUFFICIENT_MEMORY: return "Unsufficient memory"; case LIBRAW_DATA_ERROR: return "Corrupted data or unexpected EOF"; case LIBRAW_IO_ERROR: return "Input/output error"; case LIBRAW_CANCELLED_BY_CALLBACK: return "Cancelled by user callback"; case LIBRAW_BAD_CROP: return "Bad crop box"; default: return "Unknown error code"; } } #ifdef __cplusplus } #endif const double LibRaw_constants::xyz_rgb[3][3] = { { 0.412453, 0.357580, 0.180423 }, { 0.212671, 0.715160, 0.072169 }, { 0.019334, 0.119193, 0.950227 } }; const float LibRaw_constants::d65_white[3] = { 0.950456f, 1.0f, 1.088754f }; #define P1 imgdata.idata #define S imgdata.sizes #define O imgdata.params #define C imgdata.color #define T imgdata.thumbnail #define IO libraw_internal_data.internal_output_params #define ID libraw_internal_data.internal_data #define EXCEPTION_HANDLER(e) do{ \ /* fprintf(stderr,"Exception %d caught\n",e);*/ \ switch(e) \ { \ case LIBRAW_EXCEPTION_ALLOC: \ recycle(); \ return LIBRAW_UNSUFFICIENT_MEMORY; \ case LIBRAW_EXCEPTION_DECODE_RAW: \ case LIBRAW_EXCEPTION_DECODE_JPEG: \ recycle(); \ return LIBRAW_DATA_ERROR; \ case LIBRAW_EXCEPTION_DECODE_JPEG2000: \ recycle(); \ return LIBRAW_DATA_ERROR; \ case LIBRAW_EXCEPTION_IO_EOF: \ case LIBRAW_EXCEPTION_IO_CORRUPT: \ recycle(); \ return LIBRAW_IO_ERROR; \ case LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK:\ recycle(); \ return LIBRAW_CANCELLED_BY_CALLBACK; \ case LIBRAW_EXCEPTION_BAD_CROP: \ recycle(); \ return LIBRAW_BAD_CROP; \ default: \ return LIBRAW_UNSPECIFIED_ERROR; \ } \ }while(0) const char* LibRaw::version() { return LIBRAW_VERSION_STR;} int LibRaw::versionNumber() { return LIBRAW_VERSION; } const char* LibRaw::strerror(int p) { return libraw_strerror(p);} void LibRaw::derror() { if (!libraw_internal_data.unpacker_data.data_error && libraw_internal_data.internal_data.input) { if (libraw_internal_data.internal_data.input->eof()) { if(callbacks.data_cb)(*callbacks.data_cb)(callbacks.datacb_data, libraw_internal_data.internal_data.input->fname(),-1); throw LIBRAW_EXCEPTION_IO_EOF; } else { if(callbacks.data_cb)(*callbacks.data_cb)(callbacks.datacb_data, libraw_internal_data.internal_data.input->fname(), libraw_internal_data.internal_data.input->tell()); throw LIBRAW_EXCEPTION_IO_CORRUPT; } } libraw_internal_data.unpacker_data.data_error++; } void LibRaw::dcraw_clear_mem(libraw_processed_image_t* p) { if(p) ::free(p); } #ifdef USE_RAWSPEED using namespace RawSpeed; class CameraMetaDataLR : public CameraMetaData { public: CameraMetaDataLR() : CameraMetaData() {} CameraMetaDataLR(char *filename) : CameraMetaData(filename){} CameraMetaDataLR(char *data, int sz); }; CameraMetaDataLR::CameraMetaDataLR(char *data, int sz) : CameraMetaData() { ctxt = xmlNewParserCtxt(); if (ctxt == NULL) { ThrowCME("CameraMetaData:Could not initialize context."); } xmlResetLastError(); doc = xmlCtxtReadMemory(ctxt, data,sz, "", NULL, XML_PARSE_DTDVALID); if (doc == NULL) { ThrowCME("CameraMetaData: XML Document could not be parsed successfully. Error was: %s", ctxt->lastError.message); } if (ctxt->valid == 0) { if (ctxt->lastError.code == 0x5e) { // printf("CameraMetaData: Unable to locate DTD, attempting to ignore."); } else { ThrowCME("CameraMetaData: XML file does not validate. DTD Error was: %s", ctxt->lastError.message); } } xmlNodePtr cur; cur = xmlDocGetRootElement(doc); if (xmlStrcmp(cur->name, (const xmlChar *) "Cameras")) { ThrowCME("CameraMetaData: XML document of the wrong type, root node is not cameras."); return; } cur = cur->xmlChildrenNode; while (cur != NULL) { if ((!xmlStrcmp(cur->name, (const xmlChar *)"Camera"))) { Camera *camera = new Camera(doc, cur); addCamera(camera); // Create cameras for aliases. for (uint32 i = 0; i < camera->aliases.size(); i++) { addCamera(new Camera(camera, i)); } } cur = cur->next; } if (doc) xmlFreeDoc(doc); doc = 0; if (ctxt) xmlFreeParserCtxt(ctxt); ctxt = 0; } #define RAWSPEED_DATA_COUNT (sizeof(_rawspeed_data_xml)/sizeof(_rawspeed_data_xml[0])) static CameraMetaDataLR* make_camera_metadata() { int len = 0,i; for(i=0;i<RAWSPEED_DATA_COUNT;i++) if(_rawspeed_data_xml[i]) { len+=strlen(_rawspeed_data_xml[i]); } char *rawspeed_xml = (char*)calloc(len+1,sizeof(_rawspeed_data_xml[0][0])); if(!rawspeed_xml) return NULL; int offt = 0; for(i=0;i<RAWSPEED_DATA_COUNT;i++) if(_rawspeed_data_xml[i]) { int ll = strlen(_rawspeed_data_xml[i]); if(offt+ll>len) break; memmove(rawspeed_xml+offt,_rawspeed_data_xml[i],ll); offt+=ll; } rawspeed_xml[offt]=0; CameraMetaDataLR *ret=NULL; try { ret = new CameraMetaDataLR(rawspeed_xml,offt); } catch (...) { // Mask all exceptions } free(rawspeed_xml); return ret; } #endif #define ZERO(a) memset(&a,0,sizeof(a)) LibRaw:: LibRaw(unsigned int flags) { double aber[4] = {1,1,1,1}; double gamm[6] = { 0.45,4.5,0,0,0,0 }; unsigned greybox[4] = { 0, 0, UINT_MAX, UINT_MAX }; unsigned cropbox[4] = { 0, 0, UINT_MAX, UINT_MAX }; #ifdef DCRAW_VERBOSE verbose = 1; #else verbose = 0; #endif ZERO(imgdata); ZERO(libraw_internal_data); ZERO(callbacks); _rawspeed_camerameta = _rawspeed_decoder = NULL; #ifdef USE_RAWSPEED CameraMetaDataLR *camerameta = make_camera_metadata(); // May be NULL in case of exception in make_camera_metadata() _rawspeed_camerameta = static_cast<void*>(camerameta); #endif callbacks.mem_cb = (flags & LIBRAW_OPIONS_NO_MEMERR_CALLBACK) ? NULL: &default_memory_callback; callbacks.data_cb = (flags & LIBRAW_OPIONS_NO_DATAERR_CALLBACK)? NULL : &default_data_callback; memmove(&imgdata.params.aber,&aber,sizeof(aber)); memmove(&imgdata.params.gamm,&gamm,sizeof(gamm)); memmove(&imgdata.params.greybox,&greybox,sizeof(greybox)); memmove(&imgdata.params.cropbox,&cropbox,sizeof(cropbox)); imgdata.params.bright=1; imgdata.params.use_camera_matrix=-1; imgdata.params.user_flip=-1; imgdata.params.user_black=-1; imgdata.params.user_cblack[0]=imgdata.params.user_cblack[1]=imgdata.params.user_cblack[2]=imgdata.params.user_cblack[3]=-1000001; imgdata.params.user_sat=-1; imgdata.params.user_qual=-1; imgdata.params.output_color=1; imgdata.params.output_bps=8; imgdata.params.use_fuji_rotate=1; imgdata.params.exp_shift = 1.0; imgdata.params.auto_bright_thr = LIBRAW_DEFAULT_AUTO_BRIGHTNESS_THRESHOLD; imgdata.params.adjust_maximum_thr= LIBRAW_DEFAULT_ADJUST_MAXIMUM_THRESHOLD; imgdata.params.use_rawspeed = 1; imgdata.params.green_matching = 0; imgdata.parent_class = this; imgdata.progress_flags = 0; tls = new LibRaw_TLS; tls->init(); } int LibRaw::set_rawspeed_camerafile(char *filename) { #ifdef USE_RAWSPEED try { CameraMetaDataLR *camerameta = new CameraMetaDataLR(filename); if(_rawspeed_camerameta) { CameraMetaDataLR *d = static_cast<CameraMetaDataLR*>(_rawspeed_camerameta); delete d; } _rawspeed_camerameta = static_cast<void*>(camerameta); } catch (...) { //just return error code return -1; } #endif return 0; } LibRaw::~LibRaw() { recycle(); delete tls; #ifdef USE_RAWSPEED if(_rawspeed_camerameta) { CameraMetaDataLR *cmeta = static_cast<CameraMetaDataLR*>(_rawspeed_camerameta); delete cmeta; _rawspeed_camerameta = NULL; } #endif } void* LibRaw:: malloc(size_t t) { void *p = memmgr.malloc(t); if(!p) throw LIBRAW_EXCEPTION_ALLOC; return p; } void* LibRaw:: realloc(void *q,size_t t) { void *p = memmgr.realloc(q,t); if(!p) throw LIBRAW_EXCEPTION_ALLOC; return p; } void* LibRaw:: calloc(size_t n,size_t t) { void *p = memmgr.calloc(n,t); if(!p) throw LIBRAW_EXCEPTION_ALLOC; return p; } void LibRaw:: free(void *p) { memmgr.free(p); } void LibRaw:: recycle_datastream() { if(libraw_internal_data.internal_data.input && libraw_internal_data.internal_data.input_internal) { delete libraw_internal_data.internal_data.input; libraw_internal_data.internal_data.input = NULL; } libraw_internal_data.internal_data.input_internal = 0; } void LibRaw:: recycle() { recycle_datastream(); #define FREE(a) do { if(a) { free(a); a = NULL;} }while(0) FREE(imgdata.image); FREE(imgdata.thumbnail.thumb); FREE(libraw_internal_data.internal_data.meta_data); FREE(libraw_internal_data.output_data.histogram); FREE(libraw_internal_data.output_data.oprof); FREE(imgdata.color.profile); FREE(imgdata.rawdata.ph1_black); FREE(imgdata.rawdata.raw_alloc); #undef FREE ZERO(imgdata.rawdata); ZERO(imgdata.sizes); ZERO(imgdata.color); ZERO(libraw_internal_data); #ifdef USE_RAWSPEED if(_rawspeed_decoder) { RawDecoder *d = static_cast<RawDecoder*>(_rawspeed_decoder); delete d; } _rawspeed_decoder = 0; #endif memmgr.cleanup(); imgdata.thumbnail.tformat = LIBRAW_THUMBNAIL_UNKNOWN; imgdata.progress_flags = 0; tls->init(); } const char * LibRaw::unpack_function_name() { libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); return decoder_info.decoder_name; } int LibRaw::get_decoder_info(libraw_decoder_info_t* d_info) { if(!d_info) return LIBRAW_UNSPECIFIED_ERROR; if(!load_raw) return LIBRAW_OUT_OF_ORDER_CALL; d_info->decoder_flags = LIBRAW_DECODER_NOTSET; int rawdata = (imgdata.idata.filters || P1.colors == 1); // dcraw.c names order if (load_raw == &LibRaw::canon_600_load_raw) { d_info->decoder_name = "canon_600_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; // WB set within decoder, no need to load raw } else if (load_raw == &LibRaw::canon_load_raw) { d_info->decoder_name = "canon_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::lossless_jpeg_load_raw) { // Check rbayer d_info->decoder_name = "lossless_jpeg_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD | LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::canon_sraw_load_raw) { d_info->decoder_name = "canon_sraw_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY | LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::lossless_dng_load_raw) { // Check rbayer d_info->decoder_name = "lossless_dng_load_raw()"; d_info->decoder_flags = rawdata? LIBRAW_DECODER_FLATFIELD : LIBRAW_DECODER_LEGACY ; d_info->decoder_flags |= LIBRAW_DECODER_HASCURVE; d_info->decoder_flags |= LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::packed_dng_load_raw) { // Check rbayer d_info->decoder_name = "packed_dng_load_raw()"; d_info->decoder_flags = rawdata ? LIBRAW_DECODER_FLATFIELD : LIBRAW_DECODER_LEGACY; d_info->decoder_flags |= LIBRAW_DECODER_HASCURVE; d_info->decoder_flags |= LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::pentax_load_raw ) { d_info->decoder_name = "pentax_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD | LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::nikon_load_raw) { // Check rbayer d_info->decoder_name = "nikon_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD | LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::rollei_load_raw ) { // UNTESTED d_info->decoder_name = "rollei_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::phase_one_load_raw ) { d_info->decoder_name = "phase_one_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::phase_one_load_raw_c ) { d_info->decoder_name = "phase_one_load_raw_c()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::hasselblad_load_raw ) { d_info->decoder_name = "hasselblad_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::leaf_hdr_load_raw ) { d_info->decoder_name = "leaf_hdr_load_raw()"; d_info->decoder_flags = imgdata.idata.filters? LIBRAW_DECODER_FLATFIELD:LIBRAW_DECODER_LEGACY; } else if (load_raw == &LibRaw::unpacked_load_raw ) { d_info->decoder_name = "unpacked_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD | LIBRAW_DECODER_USEBAYER2; } else if (load_raw == &LibRaw::sinar_4shot_load_raw ) { // UNTESTED d_info->decoder_name = "sinar_4shot_load_raw()"; d_info->decoder_flags = (O.shot_select|| O.half_size)?LIBRAW_DECODER_FLATFIELD:LIBRAW_DECODER_LEGACY; } else if (load_raw == &LibRaw::imacon_full_load_raw ) { d_info->decoder_name = "imacon_full_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY; } else if (load_raw == &LibRaw::hasselblad_full_load_raw ) { d_info->decoder_name = "hasselblad_full_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY; } else if (load_raw == &LibRaw::packed_load_raw ) { d_info->decoder_name = "packed_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; d_info->decoder_flags |= LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::nokia_load_raw ) { // UNTESTED d_info->decoder_name = "nokia_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::panasonic_load_raw ) { d_info->decoder_name = "panasonic_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD | LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::olympus_load_raw ) { d_info->decoder_name = "olympus_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD | LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::minolta_rd175_load_raw ) { // UNTESTED d_info->decoder_name = "minolta_rd175_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::quicktake_100_load_raw ) { // UNTESTED d_info->decoder_name = "quicktake_100_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::kodak_radc_load_raw ) { d_info->decoder_name = "kodak_radc_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::kodak_jpeg_load_raw ) { // UNTESTED + RBAYER d_info->decoder_name = "kodak_jpeg_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::lossy_dng_load_raw) { // Check rbayer d_info->decoder_name = "lossy_dng_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY | LIBRAW_DECODER_TRYRAWSPEED; d_info->decoder_flags |= LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::kodak_dc120_load_raw ) { d_info->decoder_name = "kodak_dc120_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::eight_bit_load_raw ) { d_info->decoder_name = "eight_bit_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; d_info->decoder_flags |= LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::kodak_yrgb_load_raw ) { d_info->decoder_name = "kodak_yrgb_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY; d_info->decoder_flags |= LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::kodak_262_load_raw ) { d_info->decoder_name = "kodak_262_load_raw()"; // UNTESTED! d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; d_info->decoder_flags |= LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::kodak_65000_load_raw ) { d_info->decoder_name = "kodak_65000_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; d_info->decoder_flags |= LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::kodak_ycbcr_load_raw ) { // UNTESTED d_info->decoder_name = "kodak_ycbcr_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY; d_info->decoder_flags |= LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::kodak_rgb_load_raw ) { // UNTESTED d_info->decoder_name = "kodak_rgb_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY; } else if (load_raw == &LibRaw::sony_load_raw ) { d_info->decoder_name = "sony_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::sony_arw_load_raw ) { d_info->decoder_name = "sony_arw_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; #ifndef NOSONY_RAWSPEED d_info->decoder_flags |= LIBRAW_DECODER_TRYRAWSPEED; #endif } else if (load_raw == &LibRaw::sony_arw2_load_raw ) { d_info->decoder_name = "sony_arw2_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; d_info->decoder_flags |= LIBRAW_DECODER_HASCURVE; #ifndef NOSONY_RAWSPEED d_info->decoder_flags |= LIBRAW_DECODER_TRYRAWSPEED; #endif d_info->decoder_flags |= LIBRAW_DECODER_ITSASONY; } else if (load_raw == &LibRaw::smal_v6_load_raw ) { // UNTESTED d_info->decoder_name = "smal_v6_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::smal_v9_load_raw ) { // UNTESTED d_info->decoder_name = "smal_v9_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; } else if (load_raw == &LibRaw::redcine_load_raw) { d_info->decoder_name = "redcine_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FLATFIELD; d_info->decoder_flags |= LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::foveon_sd_load_raw ) { d_info->decoder_name = "foveon_sd_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY; } else if (load_raw == &LibRaw::foveon_dp_load_raw ) { d_info->decoder_name = "foveon_dp_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY; } else { d_info->decoder_name = "Unknown unpack function"; d_info->decoder_flags = LIBRAW_DECODER_NOTSET; } return LIBRAW_SUCCESS; } int LibRaw::adjust_maximum() { ushort real_max; float auto_threshold; if(O.adjust_maximum_thr < 0.00001) return LIBRAW_SUCCESS; else if (O.adjust_maximum_thr > 0.99999) auto_threshold = LIBRAW_DEFAULT_ADJUST_MAXIMUM_THRESHOLD; else auto_threshold = O.adjust_maximum_thr; real_max = C.data_maximum; if (real_max > 0 && real_max < C.maximum && real_max > C.maximum* auto_threshold) { C.maximum = real_max; } return LIBRAW_SUCCESS; } void LibRaw:: merror (void *ptr, const char *where) { if (ptr) return; if(callbacks.mem_cb)(*callbacks.mem_cb)(callbacks.memcb_data, libraw_internal_data.internal_data.input ?libraw_internal_data.internal_data.input->fname() :NULL, where); throw LIBRAW_EXCEPTION_ALLOC; } int LibRaw::open_file(const char *fname, INT64 max_buf_size) { #ifndef WIN32 struct stat st; if(stat(fname,&st)) return LIBRAW_IO_ERROR; int big = (st.st_size > max_buf_size)?1:0; #else struct _stati64 st; if(_stati64(fname,&st)) return LIBRAW_IO_ERROR; int big = (st.st_size > max_buf_size)?1:0; #endif LibRaw_abstract_datastream *stream; try { if(big) stream = new LibRaw_bigfile_datastream(fname); else stream = new LibRaw_file_datastream(fname); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if(!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input_internal = 0; // preserve from deletion on error int ret = open_datastream(stream); if (ret == LIBRAW_SUCCESS) { ID.input_internal =1 ; // flag to delete datastream on recycle } else { delete stream; ID.input_internal = 0; } return ret; } #ifdef WIN32 int LibRaw::open_file(const wchar_t *fname, INT64 max_buf_size) { struct _stati64 st; if(_wstati64(fname,&st)) return LIBRAW_IO_ERROR; int big = (st.st_size > max_buf_size)?1:0; LibRaw_abstract_datastream *stream; try { if(big) stream = new LibRaw_bigfile_datastream(fname); else stream = new LibRaw_file_datastream(fname); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if(!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input_internal = 0; // preserve from deletion on error int ret = open_datastream(stream); if (ret == LIBRAW_SUCCESS) { ID.input_internal =1 ; // flag to delete datastream on recycle } else { delete stream; ID.input_internal = 0; } return ret; } #endif int LibRaw::open_buffer(void *buffer, size_t size) { // this stream will close on recycle() if(!buffer || buffer==(void*)-1) return LIBRAW_IO_ERROR; LibRaw_buffer_datastream *stream; try { stream = new LibRaw_buffer_datastream(buffer,size); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if(!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input_internal = 0; // preserve from deletion on error int ret = open_datastream(stream); if (ret == LIBRAW_SUCCESS) { ID.input_internal =1 ; // flag to delete datastream on recycle } else { delete stream; ID.input_internal = 0; } return ret; } void LibRaw::hasselblad_full_load_raw() { int row, col; for (row=0; row < S.height; row++) for (col=0; col < S.width; col++) { read_shorts (&imgdata.image[row*S.width+col][2], 1); // B read_shorts (&imgdata.image[row*S.width+col][1], 1); // G read_shorts (&imgdata.image[row*S.width+col][0], 1); // R } } int LibRaw::open_datastream(LibRaw_abstract_datastream *stream) { if(!stream) return ENOENT; if(!stream->valid()) return LIBRAW_IO_ERROR; recycle(); try { ID.input = stream; SET_PROC_FLAG(LIBRAW_PROGRESS_OPEN); if (O.use_camera_matrix < 0) O.use_camera_matrix = O.use_camera_wb; identify(); #if 0 size_t bytes = ID.input->size()-libraw_internal_data.unpacker_data.data_offset; float bpp = float(bytes)/float(S.raw_width)/float(S.raw_height); float bpp2 = float(bytes)/float(S.width)/float(S.height); printf("RawSize: %dx%d data offset: %d data size:%d bpp: %g bpp2: %g\n",S.raw_width,S.raw_height,libraw_internal_data.unpacker_data.data_offset,bytes,bpp,bpp2); if(!strcasecmp(imgdata.idata.make,"Hasselblad") && bpp == 6.0f) { load_raw = &LibRaw::hasselblad_full_load_raw; S.width = S.raw_width; S.height = S.raw_height; P1.filters = 0; P1.colors=3; P1.raw_count=1; C.maximum=0xffff; printf("3 channel hassy found\n"); } #endif if(C.profile_length) { if(C.profile) free(C.profile); C.profile = malloc(C.profile_length); merror(C.profile,"LibRaw::open_file()"); ID.input->seek(ID.profile_offset,SEEK_SET); ID.input->read(C.profile,C.profile_length,1); } SET_PROC_FLAG(LIBRAW_PROGRESS_IDENTIFY); } catch ( LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } catch (std::exception ee) { EXCEPTION_HANDLER(LIBRAW_EXCEPTION_IO_CORRUPT); } if(P1.raw_count < 1) return LIBRAW_FILE_UNSUPPORTED; write_fun = &LibRaw::write_ppm_tiff; if (load_raw == &LibRaw::kodak_ycbcr_load_raw) { S.height += S.height & 1; S.width += S.width & 1; } libraw_decoder_info_t dinfo; get_decoder_info(&dinfo); if(dinfo.decoder_flags & LIBRAW_DECODER_LEGACY) { // Adjust sizes according to image buffer size S.raw_width = S.width; S.left_margin = 0; S.raw_height = S.height; S.top_margin = 0; } IO.shrink = P1.filters && (O.half_size || ((O.threshold || O.aber[0] != 1 || O.aber[2] != 1) )); S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; if(imgdata.idata.filters == 303979333U) { //printf("BL=%d [%d,%d,%d,%d]\n",C.black,C.cblack[0],C.cblack[1],C.cblack[2],C.cblack[3]); C.black = C.cblack[0]; C.cblack[0]=C.cblack[1]=C.cblack[2]=C.cblack[3]=0; imgdata.idata.filters = 2; } // X20 if(imgdata.idata.filters == 0x5bb8445b) { C.black = 257; C.cblack[0]=C.cblack[1]=C.cblack[2]=C.cblack[3]=0; imgdata.idata.filters = 2; S.width = 4030; S.height = 3010; S.top_margin = 2; S.left_margin = 2; } // X100S if(imgdata.idata.filters == 0x5145bb84) { C.black = 1024; C.cblack[0]=C.cblack[1]=C.cblack[2]=C.cblack[3]=0; S.left_margin = 2; S.top_margin = 1; S.width = 4934; S.height = 3290; imgdata.idata.filters = 2; } // Save color,sizes and internal data into raw_image fields memmove(&imgdata.rawdata.color,&imgdata.color,sizeof(imgdata.color)); memmove(&imgdata.rawdata.sizes,&imgdata.sizes,sizeof(imgdata.sizes)); memmove(&imgdata.rawdata.iparams,&imgdata.idata,sizeof(imgdata.idata)); memmove(&imgdata.rawdata.ioparams,&libraw_internal_data.internal_output_params,sizeof(libraw_internal_data.internal_output_params)); SET_PROC_FLAG(LIBRAW_PROGRESS_SIZE_ADJUST); return LIBRAW_SUCCESS; } #ifdef USE_RAWSPEED void LibRaw::fix_after_rawspeed(int bl) { if (load_raw == &LibRaw::lossy_dng_load_raw) C.maximum = 0xffff; else if (load_raw == &LibRaw::sony_load_raw) C.maximum = 0x3ff0; else if ( (load_raw == &LibRaw::sony_arw2_load_raw || (load_raw == &LibRaw::packed_load_raw && !strcasecmp(imgdata.idata.make,"Sony"))) && bl >= (C.black+C.cblack[0])*2 ) { C.maximum *=4; C.black *=4; for(int c=0; c< 4; c++) C.cblack[c]*=4; } } #else void LibRaw::fix_after_rawspeed(int) { } #endif int LibRaw::unpack(void) { CHECK_ORDER_HIGH(LIBRAW_PROGRESS_LOAD_RAW); CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); try { if(!libraw_internal_data.internal_data.input) return LIBRAW_INPUT_CLOSED; RUN_CALLBACK(LIBRAW_PROGRESS_LOAD_RAW,0,2); if (O.shot_select >= P1.raw_count) return LIBRAW_REQUEST_FOR_NONEXISTENT_IMAGE; if(!load_raw) return LIBRAW_UNSPECIFIED_ERROR; if (O.use_camera_matrix && C.cmatrix[0][0] > 0.25) { memcpy (C.rgb_cam, C.cmatrix, sizeof (C.cmatrix)); IO.raw_color = 0; } // already allocated ? if(imgdata.image) { free(imgdata.image); imgdata.image = 0; } if(imgdata.rawdata.raw_alloc) { free(imgdata.rawdata.raw_alloc); imgdata.rawdata.raw_alloc = 0; } if (libraw_internal_data.unpacker_data.meta_length) { libraw_internal_data.internal_data.meta_data = (char *) malloc (libraw_internal_data.unpacker_data.meta_length); merror (libraw_internal_data.internal_data.meta_data, "LibRaw::unpack()"); } libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); int save_iwidth = S.iwidth, save_iheight = S.iheight, save_shrink = IO.shrink; int rwidth = S.raw_width, rheight = S.raw_height; if( !IO.fuji_width) { // adjust non-Fuji allocation if(rwidth < S.width + S.left_margin) rwidth = S.width + S.left_margin; if(rheight < S.height + S.top_margin) rheight = S.height + S.top_margin; } S.raw_pitch = S.raw_width*2; imgdata.rawdata.raw_image = 0; imgdata.rawdata.color4_image = 0; imgdata.rawdata.color3_image = 0; #ifdef USE_RAWSPEED // RawSpeed Supported, if(O.use_rawspeed && (decoder_info.decoder_flags & LIBRAW_DECODER_TRYRAWSPEED) && _rawspeed_camerameta) { INT64 spos = ID.input->tell(); try { // printf("Using rawspeed\n"); ID.input->seek(0,SEEK_SET); INT64 _rawspeed_buffer_sz = ID.input->size()+32; void *_rawspeed_buffer = malloc(_rawspeed_buffer_sz); if(!_rawspeed_buffer) throw LIBRAW_EXCEPTION_ALLOC; ID.input->read(_rawspeed_buffer,_rawspeed_buffer_sz,1); FileMap map((uchar8*)_rawspeed_buffer,_rawspeed_buffer_sz); RawParser t(&map); RawDecoder *d = 0; CameraMetaDataLR *meta = static_cast<CameraMetaDataLR*>(_rawspeed_camerameta); d = t.getDecoder(); try { d->checkSupport(meta); } catch (const RawDecoderException& e) { imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_UNSUPPORTED; throw e; } d->decodeRaw(); d->decodeMetaData(meta); RawImage r = d->mRaw; if (r->isCFA) { // Save pointer to decoder _rawspeed_decoder = static_cast<void*>(d); imgdata.rawdata.raw_image = (ushort*) r->getDataUncropped(0,0); S.raw_pitch = r->pitch; fix_after_rawspeed(r->blackLevel); } else if(r->getCpp()==4) { _rawspeed_decoder = static_cast<void*>(d); imgdata.rawdata.color4_image = (ushort(*)[4]) r->getDataUncropped(0,0); S.raw_pitch = r->pitch; C.maximum = r->whitePoint; fix_after_rawspeed(r->blackLevel); } else if(r->getCpp() == 3) { _rawspeed_decoder = static_cast<void*>(d); imgdata.rawdata.color3_image = (ushort(*)[3]) r->getDataUncropped(0,0); S.raw_pitch = r->pitch; C.maximum = r->whitePoint; fix_after_rawspeed(r->blackLevel); } else { delete d; } free(_rawspeed_buffer); imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_PROCESSED; } catch (...) { imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_PROBLEM; // no other actions: if raw_image is not set we'll try usual load_raw call } ID.input->seek(spos,SEEK_SET); } #endif if(!imgdata.rawdata.raw_image && !imgdata.rawdata.color4_image && !imgdata.rawdata.color3_image) // RawSpeed failed! { // Not allocated on RawSpeed call, try call LibRaw if(decoder_info.decoder_flags & LIBRAW_DECODER_FLATFIELD) { imgdata.rawdata.raw_alloc = malloc(rwidth*(rheight+7)*sizeof(imgdata.rawdata.raw_image[0])); imgdata.rawdata.raw_image = (ushort*) imgdata.rawdata.raw_alloc; } else if (decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { // sRAW and Foveon only, so extra buffer size is just 1/4 // Legacy converters does not supports half mode! S.iwidth = S.width; S.iheight= S.height; IO.shrink = 0; S.raw_pitch = S.width*8; // allocate image as temporary buffer, size imgdata.rawdata.raw_alloc = calloc(S.iwidth*S.iheight,sizeof(*imgdata.image)); imgdata.image = (ushort (*)[4]) imgdata.rawdata.raw_alloc; } ID.input->seek(libraw_internal_data.unpacker_data.data_offset, SEEK_SET); unsigned m_save = C.maximum; if(load_raw == &LibRaw::unpacked_load_raw && !strcasecmp(imgdata.idata.make,"Nikon")) C.maximum=65535; (this->*load_raw)(); if(load_raw == &LibRaw::unpacked_load_raw && !strcasecmp(imgdata.idata.make,"Nikon")) C.maximum = m_save; } if(imgdata.rawdata.raw_image) crop_masked_pixels(); // calculate black levels // recover saved if( (decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) && !imgdata.rawdata.color4_image) { imgdata.image = 0; imgdata.rawdata.color4_image = (ushort (*)[4]) imgdata.rawdata.raw_alloc; } // recover image sizes S.iwidth = save_iwidth; S.iheight = save_iheight; IO.shrink = save_shrink; // adjust black to possible maximum unsigned int i = C.cblack[3]; unsigned int c; for(c=0;c<3;c++) if (i > C.cblack[c]) i = C.cblack[c]; for (c=0;c<4;c++) C.cblack[c] -= i; C.black += i; // Save color,sizes and internal data into raw_image fields memmove(&imgdata.rawdata.color,&imgdata.color,sizeof(imgdata.color)); memmove(&imgdata.rawdata.sizes,&imgdata.sizes,sizeof(imgdata.sizes)); memmove(&imgdata.rawdata.iparams,&imgdata.idata,sizeof(imgdata.idata)); memmove(&imgdata.rawdata.ioparams,&libraw_internal_data.internal_output_params,sizeof(libraw_internal_data.internal_output_params)); SET_PROC_FLAG(LIBRAW_PROGRESS_LOAD_RAW); RUN_CALLBACK(LIBRAW_PROGRESS_LOAD_RAW,1,2); return 0; } catch ( LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } catch (std::exception ee) { EXCEPTION_HANDLER(LIBRAW_EXCEPTION_IO_CORRUPT); } } void LibRaw::free_image(void) { if(imgdata.image) { free(imgdata.image); imgdata.image = 0; imgdata.progress_flags = LIBRAW_PROGRESS_START|LIBRAW_PROGRESS_OPEN |LIBRAW_PROGRESS_IDENTIFY|LIBRAW_PROGRESS_SIZE_ADJUST|LIBRAW_PROGRESS_LOAD_RAW; } } void LibRaw::raw2image_start() { // restore color,sizes and internal data into raw_image fields memmove(&imgdata.color,&imgdata.rawdata.color,sizeof(imgdata.color)); memmove(&imgdata.sizes,&imgdata.rawdata.sizes,sizeof(imgdata.sizes)); memmove(&imgdata.idata,&imgdata.rawdata.iparams,sizeof(imgdata.idata)); memmove(&libraw_internal_data.internal_output_params,&imgdata.rawdata.ioparams,sizeof(libraw_internal_data.internal_output_params)); if (O.user_flip >= 0) S.flip = O.user_flip; switch ((S.flip+3600) % 360) { case 270: S.flip = 5; break; case 180: S.flip = 3; break; case 90: S.flip = 6; break; } // adjust for half mode! IO.shrink = P1.filters && (O.half_size || ((O.threshold || O.aber[0] != 1 || O.aber[2] != 1) )); S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; } int LibRaw::is_phaseone_compressed() { return (load_raw == &LibRaw::phase_one_load_raw_c && imgdata.rawdata.ph1_black); } int LibRaw::raw2image(void) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); try { raw2image_start(); if (is_phaseone_compressed()) { phase_one_allocate_tempbuffer(); phase_one_subtract_black((ushort*)imgdata.rawdata.raw_alloc,imgdata.rawdata.raw_image); phase_one_correct(); } // free and re-allocate image bitmap if(imgdata.image) { imgdata.image = (ushort (*)[4]) realloc (imgdata.image,S.iheight*S.iwidth *sizeof (*imgdata.image)); memset(imgdata.image,0,S.iheight*S.iwidth *sizeof (*imgdata.image)); } else imgdata.image = (ushort (*)[4]) calloc (S.iheight*S.iwidth, sizeof (*imgdata.image)); merror (imgdata.image, "raw2image()"); libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); // Move saved bitmap to imgdata.image if(decoder_info.decoder_flags & LIBRAW_DECODER_FLATFIELD) { if (IO.fuji_width) { unsigned r,c; int row,col; for (row=0; row < S.raw_height-S.top_margin*2; row++) { for (col=0; col < IO.fuji_width << !libraw_internal_data.unpacker_data.fuji_layout; col++) { if (libraw_internal_data.unpacker_data.fuji_layout) { r = IO.fuji_width - 1 - col + (row >> 1); c = col + ((row+1) >> 1); } else { r = IO.fuji_width - 1 + row - (col >> 1); c = row + ((col+1) >> 1); } if (r < S.height && c < S.width) imgdata.image[((r)>>IO.shrink)*S.iwidth+((c)>>IO.shrink)][FC(r,c)] = imgdata.rawdata.raw_image[(row+S.top_margin)*S.raw_pitch/2+(col+S.left_margin)]; } } } else { int row,col; for (row=0; row < S.height; row++) for (col=0; col < S.width; col++) imgdata.image[((row) >> IO.shrink)*S.iwidth + ((col) >> IO.shrink)][fcol(row,col)] = imgdata.rawdata.raw_image[(row+S.top_margin)*S.raw_pitch/2+(col+S.left_margin)]; } } else if(decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { if(imgdata.rawdata.color4_image) { if(S.width*8 == S.raw_pitch) memmove(imgdata.image,imgdata.rawdata.color4_image,S.width*S.height*sizeof(*imgdata.image)); else { for(int row = 0; row < S.height; row++) memmove(&imgdata.image[row*S.width], &imgdata.rawdata.color4_image[(row+S.top_margin)*S.raw_pitch/8+S.left_margin], S.width*sizeof(*imgdata.image)); } } else if(imgdata.rawdata.color3_image) { unsigned char *c3image = (unsigned char*) imgdata.rawdata.color3_image; for(int row = 0; row < S.height; row++) { ushort (*srcrow)[3] = (ushort (*)[3]) &c3image[(row+S.top_margin)*S.raw_pitch]; ushort (*dstrow)[4] = (ushort (*)[4]) &imgdata.image[row*S.width]; for(int col=0; col < S.width; col++) { for(int c=0; c< 3; c++) dstrow[col][c] = srcrow[S.left_margin+col][c]; dstrow[col][3]=0; } } } else { // legacy decoder, but no data? throw LIBRAW_EXCEPTION_DECODE_RAW; } } // Free PhaseOne separate copy allocated at function start if (is_phaseone_compressed()) { phase_one_free_tempbuffer(); } // hack - clear later flags! if (load_raw == &CLASS canon_600_load_raw && S.width < S.raw_width) { canon_600_correct(); } imgdata.progress_flags = LIBRAW_PROGRESS_START|LIBRAW_PROGRESS_OPEN | LIBRAW_PROGRESS_RAW2_IMAGE |LIBRAW_PROGRESS_IDENTIFY|LIBRAW_PROGRESS_SIZE_ADJUST|LIBRAW_PROGRESS_LOAD_RAW; return 0; } catch ( LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } void LibRaw::phase_one_allocate_tempbuffer() { // Allocate temp raw_image buffer imgdata.rawdata.raw_image = (ushort*)malloc(S.raw_pitch*S.raw_height); merror (imgdata.rawdata.raw_image, "phase_one_prepare_to_correct()"); } void LibRaw::phase_one_free_tempbuffer() { free(imgdata.rawdata.raw_image); imgdata.rawdata.raw_image = (ushort*) imgdata.rawdata.raw_alloc; } void LibRaw::phase_one_subtract_black(ushort *src, ushort *dest) { // ushort *src = (ushort*)imgdata.rawdata.raw_alloc; if(O.user_black<0 && O.user_cblack[0] <= -1000000 && O.user_cblack[1] <= -1000000 && O.user_cblack[2] <= -1000000 && O.user_cblack[3] <= -1000000) { for(int row = 0; row < S.raw_height; row++) { ushort bl = imgdata.color.phase_one_data.t_black - imgdata.rawdata.ph1_black[row][0]; for(int col=0; col < imgdata.color.phase_one_data.split_col && col < S.raw_width; col++) { int idx = row*S.raw_width + col; ushort val = src[idx]; dest[idx] = val>bl?val-bl:0; } bl = imgdata.color.phase_one_data.t_black - imgdata.rawdata.ph1_black[row][1]; for(int col=imgdata.color.phase_one_data.split_col; col < S.raw_width; col++) { int idx = row*S.raw_width + col; ushort val = src[idx]; dest[idx] = val>bl?val-bl:0; } } } else // black set by user interaction { // Black level in cblack! for(int row = 0; row < S.raw_height; row++) { unsigned short cblk[16]; for(int cc=0; cc<16;cc++) cblk[cc]=C.cblack[fcol(row,cc)]; for(int col = 0; col < S.raw_width; col++) { int idx = row*S.raw_width + col; ushort val = src[idx]; ushort bl = cblk[col&0xf]; dest[idx] = val>bl?val-bl:0; } } } } void LibRaw::copy_fuji_uncropped(unsigned short cblack[4],unsigned short *dmaxp) { int row; #if defined(LIBRAW_USE_OPENMP) #pragma omp parallel for default(shared) #endif for (row=0; row < S.raw_height-S.top_margin*2; row++) { int col; unsigned short ldmax = 0; for (col=0; col < IO.fuji_width << !libraw_internal_data.unpacker_data.fuji_layout; col++) { unsigned r,c; if (libraw_internal_data.unpacker_data.fuji_layout) { r = IO.fuji_width - 1 - col + (row >> 1); c = col + ((row+1) >> 1); } else { r = IO.fuji_width - 1 + row - (col >> 1); c = row + ((col+1) >> 1); } if (r < S.height && c < S.width) { unsigned short val = imgdata.rawdata.raw_image[(row+S.top_margin)*S.raw_pitch/2+(col+S.left_margin)]; int cc = FC(r,c); if(val>cblack[cc]) { val-=cblack[cc]; if(val>ldmax)ldmax = val; } else val = 0; imgdata.image[((r)>>IO.shrink)*S.iwidth+((c)>>IO.shrink)][cc] = val; } } #if defined(LIBRAW_USE_OPENMP) #pragma omp critical(dataupdate) #endif { if(*dmaxp < ldmax) *dmaxp = ldmax; } } } void LibRaw::copy_bayer(unsigned short cblack[4],unsigned short *dmaxp) { // Both cropped and uncropped int row; #if defined(LIBRAW_USE_OPENMP) #pragma omp parallel for default(shared) #endif for (row=0; row < S.height; row++) { int col; unsigned short ldmax = 0; for (col=0; col < S.width; col++) { unsigned short val = imgdata.rawdata.raw_image[(row+S.top_margin)*S.raw_pitch/2+(col+S.left_margin)]; int cc = fcol(row,col); if(val>cblack[cc]) { val-=cblack[cc]; if(val>ldmax)ldmax = val; } else val = 0; imgdata.image[((row) >> IO.shrink)*S.iwidth + ((col) >> IO.shrink)][cc] = val; } #if defined(LIBRAW_USE_OPENMP) #pragma omp critical(dataupdate) #endif { if(*dmaxp < ldmax) *dmaxp = ldmax; } } } int LibRaw::raw2image_ex(int do_subtract_black) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); try { raw2image_start(); // Compressed P1 files with bl data! if (is_phaseone_compressed()) { phase_one_allocate_tempbuffer(); phase_one_subtract_black((ushort*)imgdata.rawdata.raw_alloc,imgdata.rawdata.raw_image); phase_one_correct(); } // process cropping int do_crop = 0; unsigned save_width = S.width; if (~O.cropbox[2] && ~O.cropbox[3] && load_raw != &LibRaw::foveon_sd_load_raw) // Foveon SD to be cropped later { int crop[4],c,filt; for(int c=0;c<4;c++) { crop[c] = O.cropbox[c]; if(crop[c]<0) crop[c]=0; } if(IO.fuji_width && imgdata.idata.filters >= 1000) { crop[0] = (crop[0]/4)*4; crop[1] = (crop[1]/4)*4; if(!libraw_internal_data.unpacker_data.fuji_layout) { crop[2]*=sqrt(2.0); crop[3]/=sqrt(2.0); } crop[2] = (crop[2]/4+1)*4; crop[3] = (crop[3]/4+1)*4; } else if (imgdata.idata.filters == 1) { crop[0] = (crop[0]/16)*16; crop[1] = (crop[1]/16)*16; } else if(imgdata.idata.filters == 2) { crop[0] = (crop[0]/6)*6; crop[1] = (crop[1]/6)*6; } do_crop = 1; crop[2] = MIN (crop[2], (signed) S.width-crop[0]); crop[3] = MIN (crop[3], (signed) S.height-crop[1]); if (crop[2] <= 0 || crop[3] <= 0) throw LIBRAW_EXCEPTION_BAD_CROP; // adjust sizes! S.left_margin+=crop[0]; S.top_margin+=crop[1]; S.width=crop[2]; S.height=crop[3]; S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; if(!IO.fuji_width && imgdata.idata.filters && imgdata.idata.filters >= 1000) { for (filt=c=0; c < 16; c++) filt |= FC((c >> 1)+(crop[1]), (c & 1)+(crop[0])) << c*2; imgdata.idata.filters = filt; } } int alloc_width = S.iwidth; int alloc_height = S.iheight; if(IO.fuji_width && do_crop) { int IO_fw = S.width >> !libraw_internal_data.unpacker_data.fuji_layout; int t_alloc_width = (S.height >> libraw_internal_data.unpacker_data.fuji_layout) + IO_fw; int t_alloc_height = t_alloc_width - 1; alloc_height = (t_alloc_height + IO.shrink) >> IO.shrink; alloc_width = (t_alloc_width + IO.shrink) >> IO.shrink; } int alloc_sz = alloc_width*alloc_height; if(imgdata.image) { imgdata.image = (ushort (*)[4]) realloc (imgdata.image,alloc_sz *sizeof (*imgdata.image)); memset(imgdata.image,0,alloc_sz *sizeof (*imgdata.image)); } else imgdata.image = (ushort (*)[4]) calloc (alloc_sz, sizeof (*imgdata.image)); merror (imgdata.image, "raw2image_ex()"); libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); // Adjust black levels unsigned short cblack[4]={0,0,0,0}; unsigned short dmax = 0; if(do_subtract_black) { adjust_bl(); for(int i=0; i< 4; i++) cblack[i] = (unsigned short)C.cblack[i]; } // Move saved bitmap to imgdata.image if(decoder_info.decoder_flags & LIBRAW_DECODER_FLATFIELD) { if (IO.fuji_width) { if(do_crop) { IO.fuji_width = S.width >> !libraw_internal_data.unpacker_data.fuji_layout; int IO_fwidth = (S.height >> libraw_internal_data.unpacker_data.fuji_layout) + IO.fuji_width; int IO_fheight = IO_fwidth - 1; int row,col; for(row=0;row<S.height;row++) { for(col=0;col<S.width;col++) { int r,c; if (libraw_internal_data.unpacker_data.fuji_layout) { r = IO.fuji_width - 1 - col + (row >> 1); c = col + ((row+1) >> 1); } else { r = IO.fuji_width - 1 + row - (col >> 1); c = row + ((col+1) >> 1); } unsigned short val = imgdata.rawdata.raw_image[(row+S.top_margin)*S.raw_pitch/2 +(col+S.left_margin)]; int cc = FCF(row,col); if(val > cblack[cc]) { val-=cblack[cc]; if(dmax < val) dmax = val; } else val = 0; imgdata.image[((r) >> IO.shrink)*alloc_width + ((c) >> IO.shrink)][cc] = val; } } S.height = IO_fheight; S.width = IO_fwidth; S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; S.raw_height -= 2*S.top_margin; } else { copy_fuji_uncropped(cblack,&dmax); } } // end Fuji else { copy_bayer(cblack,&dmax); } } else if(decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { if(imgdata.rawdata.color4_image) { if(S.raw_pitch != S.width*8) { for(int row = 0; row < S.height; row++) memmove(&imgdata.image[row*S.width], &imgdata.rawdata.color4_image[(row+S.top_margin)*S.raw_pitch/8+S.left_margin], S.width*sizeof(*imgdata.image)); } else { // legacy is always 4channel and not shrinked! memmove(imgdata.image,imgdata.rawdata.color4_image,S.width*S.height*sizeof(*imgdata.image)); } } else if(imgdata.rawdata.color3_image) { unsigned char *c3image = (unsigned char*) imgdata.rawdata.color3_image; for(int row = 0; row < S.height; row++) { ushort (*srcrow)[3] = (ushort (*)[3]) &c3image[(row+S.top_margin)*S.raw_pitch]; ushort (*dstrow)[4] = (ushort (*)[4]) &imgdata.image[row*S.width]; for(int col=0; col < S.width; col++) { for(int c=0; c< 3; c++) dstrow[col][c] = srcrow[S.left_margin+col][c]; dstrow[col][3]=0; } } } else { // legacy decoder, but no data? throw LIBRAW_EXCEPTION_DECODE_RAW; } } // Free PhaseOne separate copy allocated at function start if (is_phaseone_compressed()) { phase_one_free_tempbuffer(); } if (load_raw == &CLASS canon_600_load_raw && S.width < S.raw_width) { canon_600_correct(); } if(do_subtract_black) { C.data_maximum = (int)dmax; C.maximum -= C.black; ZERO(C.cblack); C.black = 0; } // hack - clear later flags! imgdata.progress_flags = LIBRAW_PROGRESS_START|LIBRAW_PROGRESS_OPEN | LIBRAW_PROGRESS_RAW2_IMAGE |LIBRAW_PROGRESS_IDENTIFY|LIBRAW_PROGRESS_SIZE_ADJUST|LIBRAW_PROGRESS_LOAD_RAW; return 0; } catch ( LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } #if 1 libraw_processed_image_t * LibRaw::dcraw_make_mem_thumb(int *errcode) { if(!T.thumb) { if ( !ID.toffset) { if(errcode) *errcode= LIBRAW_NO_THUMBNAIL; } else { if(errcode) *errcode= LIBRAW_OUT_OF_ORDER_CALL; } return NULL; } if (T.tformat == LIBRAW_THUMBNAIL_BITMAP) { libraw_processed_image_t * ret = (libraw_processed_image_t *)::malloc(sizeof(libraw_processed_image_t)+T.tlength); if(!ret) { if(errcode) *errcode= ENOMEM; return NULL; } memset(ret,0,sizeof(libraw_processed_image_t)); ret->type = LIBRAW_IMAGE_BITMAP; ret->height = T.theight; ret->width = T.twidth; ret->colors = 3; ret->bits = 8; ret->data_size = T.tlength; memmove(ret->data,T.thumb,T.tlength); if(errcode) *errcode= 0; return ret; } else if (T.tformat == LIBRAW_THUMBNAIL_JPEG) { ushort exif[5]; int mk_exif = 0; if(strcmp(T.thumb+6,"Exif")) mk_exif = 1; int dsize = T.tlength + mk_exif * (sizeof(exif)+sizeof(tiff_hdr)); libraw_processed_image_t * ret = (libraw_processed_image_t *)::malloc(sizeof(libraw_processed_image_t)+dsize); if(!ret) { if(errcode) *errcode= ENOMEM; return NULL; } memset(ret,0,sizeof(libraw_processed_image_t)); ret->type = LIBRAW_IMAGE_JPEG; ret->data_size = dsize; ret->data[0] = 0xff; ret->data[1] = 0xd8; if(mk_exif) { struct tiff_hdr th; memcpy (exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons (8 + sizeof th); memmove(ret->data+2,exif,sizeof(exif)); tiff_head (&th, 0); memmove(ret->data+(2+sizeof(exif)),&th,sizeof(th)); memmove(ret->data+(2+sizeof(exif)+sizeof(th)),T.thumb+2,T.tlength-2); } else { memmove(ret->data+2,T.thumb+2,T.tlength-2); } if(errcode) *errcode= 0; return ret; } else { if(errcode) *errcode= LIBRAW_UNSUPPORTED_THUMBNAIL; return NULL; } } // jlb // macros for copying pixels to either BGR or RGB formats #define FORBGR for(c=P1.colors-1; c >=0 ; c--) #define FORRGB for(c=0; c < P1.colors ; c++) void LibRaw::get_mem_image_format(int* width, int* height, int* colors, int* bps) const { if (S.flip & 4) { *width = S.height; *height = S.width; } else { *width = S.width; *height = S.height; } *colors = P1.colors; *bps = O.output_bps; } int LibRaw::copy_mem_image(void* scan0, int stride, int bgr) { // the image memory pointed to by scan0 is assumed to be in the format returned by get_mem_image_format if((imgdata.progress_flags & LIBRAW_PROGRESS_THUMB_MASK) < LIBRAW_PROGRESS_PRE_INTERPOLATE) return LIBRAW_OUT_OF_ORDER_CALL; if(libraw_internal_data.output_data.histogram) { int perc, val, total, t_white=0x2000,c; perc = S.width * S.height * 0.01; /* 99th percentile white level */ if (IO.fuji_width) perc /= 2; if (!((O.highlight & ~2) || O.no_auto_bright)) for (t_white=c=0; c < P1.colors; c++) { for (val=0x2000, total=0; --val > 32; ) if ((total += libraw_internal_data.output_data.histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve (O.gamm[0], O.gamm[1], 2, (t_white << 3)/O.bright); } int s_iheight = S.iheight; int s_iwidth = S.iwidth; int s_width = S.width; int s_hwight = S.height; S.iheight = S.height; S.iwidth = S.width; if (S.flip & 4) SWAP(S.height,S.width); uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; soff = flip_index (0, 0); cstep = flip_index (0, 1) - soff; rstep = flip_index (1, 0) - flip_index (0, S.width); for (row=0; row < S.height; row++, soff += rstep) { uchar *bufp = ((uchar*)scan0)+row*stride; ppm2 = (ushort*) (ppm = bufp); // keep trivial decisions in the outer loop for speed if (bgr) { if (O.output_bps == 8) { for (col=0; col < S.width; col++, soff += cstep) FORBGR *ppm++ = imgdata.color.curve[imgdata.image[soff][c]]>>8; } else { for (col=0; col < S.width; col++, soff += cstep) FORBGR *ppm2++ = imgdata.color.curve[imgdata.image[soff][c]]; } } else { if (O.output_bps == 8) { for (col=0; col < S.width; col++, soff += cstep) FORRGB *ppm++ = imgdata.color.curve[imgdata.image[soff][c]]>>8; } else { for (col=0; col < S.width; col++, soff += cstep) FORRGB *ppm2++ = imgdata.color.curve[imgdata.image[soff][c]]; } } // bufp += stride; // go to the next line } S.iheight = s_iheight; S.iwidth = s_iwidth; S.width = s_width; S.height = s_hwight; return 0; } #undef FORBGR #undef FORRGB libraw_processed_image_t *LibRaw::dcraw_make_mem_image(int *errcode) { int width, height, colors, bps; get_mem_image_format(&width, &height, &colors, &bps); int stride = width * (bps/8) * colors; unsigned ds = height * stride; libraw_processed_image_t *ret = (libraw_processed_image_t*)::malloc(sizeof(libraw_processed_image_t)+ds); if(!ret) { if(errcode) *errcode= ENOMEM; return NULL; } memset(ret,0,sizeof(libraw_processed_image_t)); // metadata init ret->type = LIBRAW_IMAGE_BITMAP; ret->height = height; ret->width = width; ret->colors = colors; ret->bits = bps; ret->data_size = ds; copy_mem_image(ret->data, stride, 0); return ret; } #undef FORC #undef FORCC #undef SWAP #endif int LibRaw::dcraw_ppm_tiff_writer(const char *filename) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); if(!imgdata.image) return LIBRAW_OUT_OF_ORDER_CALL; if(!filename) return ENOENT; FILE *f = fopen(filename,"wb"); if(!f) return errno; try { if(!libraw_internal_data.output_data.histogram) { libraw_internal_data.output_data.histogram = (int (*)[LIBRAW_HISTOGRAM_SIZE]) malloc(sizeof(*libraw_internal_data.output_data.histogram)*4); merror(libraw_internal_data.output_data.histogram,"LibRaw::dcraw_ppm_tiff_writer()"); } libraw_internal_data.internal_data.output = f; write_ppm_tiff(); SET_PROC_FLAG(LIBRAW_PROGRESS_FLIP); libraw_internal_data.internal_data.output = NULL; fclose(f); return 0; } catch ( LibRaw_exceptions err) { fclose(f); EXCEPTION_HANDLER(err); } } void LibRaw::kodak_thumb_loader() { // some kodak cameras ushort s_height = S.height, s_width = S.width,s_iwidth = S.iwidth,s_iheight=S.iheight; int s_colors = P1.colors; unsigned s_filters = P1.filters; ushort (*s_image)[4] = imgdata.image; S.height = T.theight; S.width = T.twidth; P1.filters = 0; if (thumb_load_raw == &CLASS kodak_ycbcr_load_raw) { S.height += S.height & 1; S.width += S.width & 1; } imgdata.image = (ushort (*)[4]) calloc (S.iheight*S.iwidth, sizeof (*imgdata.image)); merror (imgdata.image, "LibRaw::kodak_thumb_loader()"); ID.input->seek(ID.toffset, SEEK_SET); // read kodak thumbnail into T.image[] (this->*thumb_load_raw)(); // copy-n-paste from image pipe #define MIN(a,b) ((a) < (b) ? (a) : (b)) #define MAX(a,b) ((a) > (b) ? (a) : (b)) #define LIM(x,min,max) MAX(min,MIN(x,max)) #define CLIP(x) LIM(x,0,65535) #define SWAP(a,b) { a ^= b; a ^= (b ^= a); } // from scale_colors { double dmax; float scale_mul[4]; int c,val; for (dmax=DBL_MAX, c=0; c < 3; c++) if (dmax > C.pre_mul[c]) dmax = C.pre_mul[c]; for( c=0; c< 3; c++) scale_mul[c] = (C.pre_mul[c] / dmax) * 65535.0 / C.maximum; scale_mul[3] = scale_mul[1]; size_t size = S.height * S.width; for (unsigned i=0; i < size*4 ; i++) { val = imgdata.image[0][i]; if(!val) continue; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } // from convert_to_rgb ushort *img; int row,col; int (*t_hist)[LIBRAW_HISTOGRAM_SIZE] = (int (*)[LIBRAW_HISTOGRAM_SIZE]) calloc(sizeof(*t_hist),4); merror (t_hist, "LibRaw::kodak_thumb_loader()"); float out[3], out_cam[3][4] = { {2.81761312, -1.98369181, 0.166078627, 0}, {-0.111855984, 1.73688626, -0.625030339, 0}, {-0.0379119813, -0.891268849, 1.92918086, 0} }; for (img=imgdata.image[0], row=0; row < S.height; row++) for (col=0; col < S.width; col++, img+=4) { out[0] = out[1] = out[2] = 0; int c; for(c=0;c<3;c++) { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } for(c=0; c<3; c++) img[c] = CLIP((int) out[c]); for(c=0; c<P1.colors;c++) t_hist[c][img[c] >> 3]++; } // from gamma_lut int (*save_hist)[LIBRAW_HISTOGRAM_SIZE] = libraw_internal_data.output_data.histogram; libraw_internal_data.output_data.histogram = t_hist; // make curve output curve! ushort (*t_curve) = (ushort*) calloc(sizeof(C.curve),1); merror (t_curve, "LibRaw::kodak_thumb_loader()"); memmove(t_curve,C.curve,sizeof(C.curve)); memset(C.curve,0,sizeof(C.curve)); { int perc, val, total, t_white=0x2000,c; perc = S.width * S.height * 0.01; /* 99th percentile white level */ if (IO.fuji_width) perc /= 2; if (!((O.highlight & ~2) || O.no_auto_bright)) for (t_white=c=0; c < P1.colors; c++) { for (val=0x2000, total=0; --val > 32; ) if ((total += libraw_internal_data.output_data.histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve (O.gamm[0], O.gamm[1], 2, (t_white << 3)/O.bright); } libraw_internal_data.output_data.histogram = save_hist; free(t_hist); // from write_ppm_tiff - copy pixels into bitmap S.iheight = S.height; S.iwidth = S.width; if (S.flip & 4) SWAP(S.height,S.width); if(T.thumb) free(T.thumb); T.thumb = (char*) calloc (S.width * S.height, P1.colors); merror (T.thumb, "LibRaw::kodak_thumb_loader()"); T.tlength = S.width * S.height * P1.colors; // from write_tiff_ppm { int soff = flip_index (0, 0); int cstep = flip_index (0, 1) - soff; int rstep = flip_index (1, 0) - flip_index (0, S.width); for (int row=0; row < S.height; row++, soff += rstep) { char *ppm = T.thumb + row*S.width*P1.colors; for (int col=0; col < S.width; col++, soff += cstep) for(int c = 0; c < P1.colors; c++) ppm [col*P1.colors+c] = imgdata.color.curve[imgdata.image[soff][c]]>>8; } } memmove(C.curve,t_curve,sizeof(C.curve)); free(t_curve); // restore variables free(imgdata.image); imgdata.image = s_image; T.twidth = S.width; S.width = s_width; S.iwidth = s_iwidth; S.iheight = s_iheight; T.theight = S.height; S.height = s_height; T.tcolors = P1.colors; P1.colors = s_colors; P1.filters = s_filters; } #undef MIN #undef MAX #undef LIM #undef CLIP #undef SWAP // ������� thumbnail �� �����, ������ thumb_format � ������������ � �������� int LibRaw::unpack_thumb(void) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); CHECK_ORDER_BIT(LIBRAW_PROGRESS_THUMB_LOAD); try { if(!libraw_internal_data.internal_data.input) return LIBRAW_INPUT_CLOSED; if ( !ID.toffset) { return LIBRAW_NO_THUMBNAIL; } else if (thumb_load_raw) { kodak_thumb_loader(); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else { ID.input->seek(ID.toffset, SEEK_SET); if ( write_thumb == &LibRaw::jpeg_thumb) { if(T.thumb) free(T.thumb); T.thumb = (char *) malloc (T.tlength); merror (T.thumb, "jpeg_thumb()"); ID.input->read (T.thumb, 1, T.tlength); T.tcolors = 3; T.tformat = LIBRAW_THUMBNAIL_JPEG; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::ppm_thumb) { T.tlength = T.twidth * T.theight*3; if(T.thumb) free(T.thumb); T.thumb = (char *) malloc (T.tlength); merror (T.thumb, "ppm_thumb()"); ID.input->read(T.thumb, 1, T.tlength); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::ppm16_thumb) { T.tlength = T.twidth * T.theight*3; ushort *t_thumb = (ushort*)calloc(T.tlength,2); ID.input->read(t_thumb,2,T.tlength); if ((libraw_internal_data.unpacker_data.order= 0x4949) == (ntohs(0x1234) == 0x1234)) swab ((char*)t_thumb, (char*)t_thumb, T.tlength*2); if(T.thumb) free(T.thumb); T.thumb = (char *) malloc (T.tlength); merror (T.thumb, "ppm_thumb()"); for (int i=0; i < T.tlength; i++) T.thumb[i] = t_thumb[i] >> 8; free(t_thumb); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::foveon_thumb) { foveon_thumb_loader(); // may return with error, so format is set in // foveon thumb loader itself SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } // else if -- all other write_thumb cases! else { return LIBRAW_UNSUPPORTED_THUMBNAIL; } } // last resort return LIBRAW_UNSUPPORTED_THUMBNAIL; } catch ( LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } int LibRaw::dcraw_thumb_writer(const char *fname) { // CHECK_ORDER_LOW(LIBRAW_PROGRESS_THUMB_LOAD); if(!fname) return ENOENT; FILE *tfp = fopen(fname,"wb"); if(!tfp) return errno; if(!T.thumb) { fclose(tfp); return LIBRAW_OUT_OF_ORDER_CALL; } try { switch (T.tformat) { case LIBRAW_THUMBNAIL_JPEG: jpeg_thumb_writer (tfp,T.thumb,T.tlength); break; case LIBRAW_THUMBNAIL_BITMAP: fprintf (tfp, "P6\n%d %d\n255\n", T.twidth, T.theight); fwrite (T.thumb, 1, T.tlength, tfp); break; default: fclose(tfp); return LIBRAW_UNSUPPORTED_THUMBNAIL; } fclose(tfp); return 0; } catch ( LibRaw_exceptions err) { fclose(tfp); EXCEPTION_HANDLER(err); } } int LibRaw::adjust_sizes_info_only(void) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); raw2image_start(); if (O.use_fuji_rotate) { if (IO.fuji_width) { IO.fuji_width = (IO.fuji_width - 1 + IO.shrink) >> IO.shrink; S.iwidth = (ushort)(IO.fuji_width / sqrt(0.5)); S.iheight = (ushort)( (S.iheight - IO.fuji_width) / sqrt(0.5)); } else { if (S.pixel_aspect < 1) S.iheight = (ushort)( S.iheight / S.pixel_aspect + 0.5); if (S.pixel_aspect > 1) S.iwidth = (ushort) (S.iwidth * S.pixel_aspect + 0.5); } } SET_PROC_FLAG(LIBRAW_PROGRESS_FUJI_ROTATE); if ( S.flip & 4) { unsigned short t = S.iheight; S.iheight=S.iwidth; S.iwidth = t; SET_PROC_FLAG(LIBRAW_PROGRESS_FLIP); } return 0; } int LibRaw::subtract_black() { CHECK_ORDER_LOW(LIBRAW_PROGRESS_RAW2_IMAGE); try { if(!is_phaseone_compressed() && (C.cblack[0] || C.cblack[1] || C.cblack[2] || C.cblack[3])) { #define BAYERC(row,col,c) imgdata.image[((row) >> IO.shrink)*S.iwidth + ((col) >> IO.shrink)][c] int cblk[4],i; for(i=0;i<4;i++) cblk[i] = C.cblack[i]; int size = S.iheight * S.iwidth; #define MIN(a,b) ((a) < (b) ? (a) : (b)) #define MAX(a,b) ((a) > (b) ? (a) : (b)) #define LIM(x,min,max) MAX(min,MIN(x,max)) #define CLIP(x) LIM(x,0,65535) int dmax = 0; for(i=0; i< size*4; i++) { int val = imgdata.image[0][i]; val -= cblk[i & 3]; imgdata.image[0][i] = CLIP(val); if(dmax < val) dmax = val; } C.data_maximum = dmax & 0xffff; #undef MIN #undef MAX #undef LIM #undef CLIP C.maximum -= C.black; ZERO(C.cblack); C.black = 0; #undef BAYERC } else { // Nothing to Do, maximum is already calculated, black level is 0, so no change // only calculate channel maximum; int idx; ushort *p = (ushort*)imgdata.image; int dmax = 0; for(idx=0;idx<S.iheight*S.iwidth*4;idx++) if(dmax < p[idx]) dmax = p[idx]; C.data_maximum = dmax; } return 0; } catch ( LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } #define TBLN 65535 void LibRaw::exp_bef(float shift, float smooth) { // params limits if(shift>8) shift = 8; if(shift<0.25) shift = 0.25; if(smooth < 0.0) smooth = 0.0; if(smooth > 1.0) smooth = 1.0; unsigned short *lut = (ushort*)malloc((TBLN+1)*sizeof(unsigned short)); if(shift <=1.0) { for(int i=0;i<=TBLN;i++) lut[i] = (unsigned short)((float)i*shift); } else { float x1,x2,y1,y2; float cstops = log(shift)/log(2.0f); float room = cstops*2; float roomlin = powf(2.0f,room); x2 = (float)TBLN; x1 = (x2+1)/roomlin-1; y1 = x1*shift; y2 = x2*(1+(1-smooth)*(shift-1)); float sq3x=powf(x1*x1*x2,1.0f/3.0f); float B = (y2-y1+shift*(3*x1-3.0f*sq3x)) / (x2+2.0f*x1-3.0f*sq3x); float A = (shift - B)*3.0f*powf(x1*x1,1.0f/3.0f); float CC = y2 - A*powf(x2,1.0f/3.0f)-B*x2; for(int i=0;i<=TBLN;i++) { float X = (float)i; float Y = A*powf(X,1.0f/3.0f)+B*X+CC; if(i<x1) lut[i] = (unsigned short)((float)i*shift); else lut[i] = Y<0?0:(Y>TBLN?TBLN:(unsigned short)(Y)); } } for(int i=0; i< S.height*S.width; i++) { imgdata.image[i][0] = lut[imgdata.image[i][0]]; imgdata.image[i][1] = lut[imgdata.image[i][1]]; imgdata.image[i][2] = lut[imgdata.image[i][2]]; imgdata.image[i][3] = lut[imgdata.image[i][3]]; } if(C.data_maximum <=TBLN) C.data_maximum = lut[C.data_maximum]; if(C.maximum <= TBLN) C.maximum = lut[C.maximum]; // no need to adjust the minumum, black is already subtracted free(lut); } #define MIN(a,b) ((a) < (b) ? (a) : (b)) #define MAX(a,b) ((a) > (b) ? (a) : (b)) #define LIM(x,min,max) MAX(min,MIN(x,max)) #define ULIM(x,y,z) ((y) < (z) ? LIM(x,y,z) : LIM(x,z,y)) #define CLIP(x) LIM(x,0,65535) void LibRaw::convert_to_rgb_loop(float out_cam[3][4]) { int row,col,c; float out[3]; ushort *img; memset(libraw_internal_data.output_data.histogram,0,sizeof(int)*LIBRAW_HISTOGRAM_SIZE*4); for (img=imgdata.image[0], row=0; row < S.height; row++) for (col=0; col < S.width; col++, img+=4) { if (!libraw_internal_data.internal_output_params.raw_color) { out[0] = out[1] = out[2] = 0; for(c=0; c< imgdata.idata.colors; c++) { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } for(c=0;c<3;c++) img[c] = CLIP((int) out[c]); } for(c=0; c< imgdata.idata.colors; c++) libraw_internal_data.output_data.histogram[c][img[c] >> 3]++; } } void LibRaw::scale_colors_loop(float scale_mul[4]) { unsigned size = S.iheight*S.iwidth; if(C.cblack[0]||C.cblack[1]||C.cblack[2]||C.cblack[3]) { for (unsigned i=0; i < size*4; i++) { int val = imgdata.image[0][i]; if (!val) continue; val -= C.cblack[i & 3]; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } else // BL is zero { for (unsigned i=0; i < size*4; i++) { int val = imgdata.image[0][i]; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } } void LibRaw::adjust_bl() { if (O.user_black >= 0) C.black = O.user_black; for(int i=0; i<4; i++) if(O.user_cblack[i]>-1000000) C.cblack[i] = O.user_cblack[i]; // remove common part from C.cblack[] int i = C.cblack[3]; int c; for(c=0;c<3;c++) if (i > C.cblack[c]) i = C.cblack[c]; for(c=0;c<4;c++) C.cblack[c] -= i; C.black += i; for(c=0;c<4;c++) C.cblack[c] += C.black; } int LibRaw::dcraw_process(void) { int quality,i; int iterations=-1, dcb_enhance=1, noiserd=0; int eeci_refine_fl=0, es_med_passes_fl=0; float cared=0,cablue=0; float linenoise=0; float lclean=0,cclean=0; float thresh=0; float preser=0; float expos=1.0; CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); // CHECK_ORDER_HIGH(LIBRAW_PROGRESS_PRE_INTERPOLATE); try { int no_crop = 1; if (~O.cropbox[2] && ~O.cropbox[3]) no_crop=0; libraw_decoder_info_t di; get_decoder_info(&di); int subtract_inline = !O.bad_pixels && !O.dark_frame && !O.wf_debanding && !(di.decoder_flags & LIBRAW_DECODER_LEGACY) && !IO.zero_is_bad; raw2image_ex(subtract_inline); // allocate imgdata.image and copy data! int save_4color = O.four_color_rgb; if (IO.zero_is_bad) { remove_zeroes(); SET_PROC_FLAG(LIBRAW_PROGRESS_REMOVE_ZEROES); } if(O.half_size) O.four_color_rgb = 1; if(O.bad_pixels && no_crop) { bad_pixels(O.bad_pixels); SET_PROC_FLAG(LIBRAW_PROGRESS_BAD_PIXELS); } if (O.dark_frame && no_crop) { subtract (O.dark_frame); SET_PROC_FLAG(LIBRAW_PROGRESS_DARK_FRAME); } if (O.wf_debanding) { wf_remove_banding(); } quality = 2 + !IO.fuji_width; if (O.user_qual >= 0) quality = O.user_qual; if(!subtract_inline || !C.data_maximum) { adjust_bl(); subtract_black(); } adjust_maximum(); if (O.user_sat > 0) C.maximum = O.user_sat; if (P1.is_foveon) { if(load_raw == &LibRaw::foveon_dp_load_raw) { for (int i=0; i < S.height*S.width*4; i++) if ((short) imgdata.image[0][i] < 0) imgdata.image[0][i] = 0; } else foveon_interpolate(); SET_PROC_FLAG(LIBRAW_PROGRESS_FOVEON_INTERPOLATE); } if (O.green_matching && !O.half_size) { green_matching(); } if (!P1.is_foveon) { scale_colors(); SET_PROC_FLAG(LIBRAW_PROGRESS_SCALE_COLORS); } pre_interpolate(); SET_PROC_FLAG(LIBRAW_PROGRESS_PRE_INTERPOLATE); if (O.dcb_iterations >= 0) iterations = O.dcb_iterations; if (O.dcb_enhance_fl >=0 ) dcb_enhance = O.dcb_enhance_fl; if (O.fbdd_noiserd >=0 ) noiserd = O.fbdd_noiserd; if (O.eeci_refine >=0 ) eeci_refine_fl = O.eeci_refine; if (O.es_med_passes >0 ) es_med_passes_fl = O.es_med_passes; // LIBRAW_DEMOSAIC_PACK_GPL3 if (!O.half_size && O.cfa_green >0) {thresh=O.green_thresh ;green_equilibrate(thresh);} if (O.exp_correc >0) {expos=O.exp_shift ; preser=O.exp_preser; exp_bef(expos,preser);} if (O.ca_correc >0 ) {cablue=O.cablue; cared=O.cared; CA_correct_RT(cablue, cared);} if (O.cfaline >0 ) {linenoise=O.linenoise; cfa_linedn(linenoise);} if (O.cfa_clean >0 ) {lclean=O.lclean; cclean=O.cclean; cfa_impulse_gauss(lclean,cclean);} if (P1.filters) { if (noiserd>0 && P1.colors==3 && P1.filters) fbdd(noiserd); if (quality == 0) lin_interpolate(); else if (quality == 1 || P1.colors > 3 || P1.filters < 1000) vng_interpolate(); else if (quality == 2) ppg_interpolate(); else if (quality == 3) ahd_interpolate(); // really don't need it here due to fallback op else if (quality == 4) dcb(iterations, dcb_enhance); // LIBRAW_DEMOSAIC_PACK_GPL2 else if (quality == 5) ahd_interpolate_mod(); else if (quality == 6) afd_interpolate_pl(2,1); else if (quality == 7) vcd_interpolate(0); else if (quality == 8) vcd_interpolate(12); else if (quality == 9) lmmse_interpolate(1); // LIBRAW_DEMOSAIC_PACK_GPL3 else if (quality == 10) amaze_demosaic_RT(); // LGPL2 else if (quality == 11) dht_interpolate(); else if (quality == 12) aahd_interpolate(); // fallback to AHD else ahd_interpolate(); SET_PROC_FLAG(LIBRAW_PROGRESS_INTERPOLATE); } if (IO.mix_green) { for (P1.colors=3, i=0; i < S.height * S.width; i++) imgdata.image[i][1] = (imgdata.image[i][1] + imgdata.image[i][3]) >> 1; SET_PROC_FLAG(LIBRAW_PROGRESS_MIX_GREEN); } if(!P1.is_foveon) { if (P1.colors == 3) { if (quality == 8) { if (eeci_refine_fl == 1) refinement(); if (O.med_passes > 0) median_filter_new(); if (es_med_passes_fl > 0) es_median_filter(); } else { median_filter(); } SET_PROC_FLAG(LIBRAW_PROGRESS_MEDIAN_FILTER); } } if (O.highlight == 2) { blend_highlights(); SET_PROC_FLAG(LIBRAW_PROGRESS_HIGHLIGHTS); } if (O.highlight > 2) { recover_highlights(); SET_PROC_FLAG(LIBRAW_PROGRESS_HIGHLIGHTS); } if (O.use_fuji_rotate) { fuji_rotate(); SET_PROC_FLAG(LIBRAW_PROGRESS_FUJI_ROTATE); } if(!libraw_internal_data.output_data.histogram) { libraw_internal_data.output_data.histogram = (int (*)[LIBRAW_HISTOGRAM_SIZE]) malloc(sizeof(*libraw_internal_data.output_data.histogram)*4); merror(libraw_internal_data.output_data.histogram,"LibRaw::dcraw_process()"); } #ifndef NO_LCMS if(O.camera_profile) { apply_profile(O.camera_profile,O.output_profile); SET_PROC_FLAG(LIBRAW_PROGRESS_APPLY_PROFILE); } #endif convert_to_rgb(); SET_PROC_FLAG(LIBRAW_PROGRESS_CONVERT_RGB); if (O.use_fuji_rotate) { stretch(); SET_PROC_FLAG(LIBRAW_PROGRESS_STRETCH); } O.four_color_rgb = save_4color; // also, restore return 0; } catch ( LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } // Supported cameras: static const char *static_camera_list[] = { "Adobe Digital Negative (DNG)", "AgfaPhoto DC-833m", "Apple QuickTake 100", "Apple QuickTake 150", "Apple QuickTake 200", "ARRIRAW format", "AVT F-080C", "AVT F-145C", "AVT F-201C", "AVT F-510C", "AVT F-810C", "Canon PowerShot 600", "Canon PowerShot A5", "Canon PowerShot A5 Zoom", "Canon PowerShot A50", "Canon PowerShot A460 (CHDK hack)", "Canon PowerShot A470 (CHDK hack)", "Canon PowerShot A530 (CHDK hack)", "Canon PowerShot A570 (CHDK hack)", "Canon PowerShot A590 (CHDK hack)", "Canon PowerShot A610 (CHDK hack)", "Canon PowerShot A620 (CHDK hack)", "Canon PowerShot A630 (CHDK hack)", "Canon PowerShot A640 (CHDK hack)", "Canon PowerShot A650 (CHDK hack)", "Canon PowerShot A710 IS (CHDK hack)", "Canon PowerShot A720 IS (CHDK hack)", "Canon PowerShot Pro70", "Canon PowerShot Pro90 IS", "Canon PowerShot Pro1", "Canon PowerShot G1", "Canon PowerShot G1 X", "Canon PowerShot G2", "Canon PowerShot G3", "Canon PowerShot G5", "Canon PowerShot G6", "Canon PowerShot G7 (CHDK hack)", "Canon PowerShot G9", "Canon PowerShot G10", "Canon PowerShot G11", "Canon PowerShot G12", "Canon PowerShot G15", "Canon PowerShot S2 IS (CHDK hack)", "Canon PowerShot S3 IS (CHDK hack)", "Canon PowerShot S5 IS (CHDK hack)", "Canon PowerShot SD300 (CHDK hack)", "Canon PowerShot S30", "Canon PowerShot S40", "Canon PowerShot S45", "Canon PowerShot S50", "Canon PowerShot S60", "Canon PowerShot S70", "Canon PowerShot S90", "Canon PowerShot S95", "Canon PowerShot S100", "Canon PowerShot S110", "Canon PowerShot SX1 IS", "Canon PowerShot SX50 HS", "Canon PowerShot SX110 IS (CHDK hack)", "Canon PowerShot SX120 IS (CHDK hack)", "Canon PowerShot SX220 HS (CHDK hack)", "Canon PowerShot SX20 IS (CHDK hack)", "Canon PowerShot SX30 IS (CHDK hack)", "Canon EOS D30", "Canon EOS D60", "Canon EOS 5D", "Canon EOS 5D Mark II", "Canon EOS 5D Mark III", "Canon EOS 6D", "Canon EOS 7D", "Canon EOS 10D", "Canon EOS 20D", "Canon EOS 30D", "Canon EOS 40D", "Canon EOS 50D", "Canon EOS 60D", "Canon EOS 100D/ Digital Rebel SL1", "Canon EOS 300D / Digital Rebel / Kiss Digital", "Canon EOS 350D / Digital Rebel XT / Kiss Digital N", "Canon EOS 400D / Digital Rebel XTi / Kiss Digital X", "Canon EOS 450D / Digital Rebel XSi / Kiss Digital X2", "Canon EOS 500D / Digital Rebel T1i / Kiss Digital X3", "Canon EOS 550D / Digital Rebel T2i / Kiss Digital X4", "Canon EOS 600D / Digital Rebel T3i / Kiss Digital X5", "Canon EOS 650D / Digital Rebel T4i / Kiss Digital X6i", "Canon EOS 700D / Digital Rebel T54i", "Canon EOS 1000D / Digital Rebel XS / Kiss Digital F", "Canon EOS 1100D / Digital Rebel T3 / Kiss Digital X50", "Canon EOS D2000C", "Canon EOS M", "Canon EOS-1D", "Canon EOS-1DS", "Canon EOS-1D X", "Canon EOS-1D Mark II", "Canon EOS-1D Mark II N", "Canon EOS-1D Mark III", "Canon EOS-1D Mark IV", "Canon EOS-1Ds Mark II", "Canon EOS-1Ds Mark III", "Casio QV-2000UX", "Casio QV-3000EX", "Casio QV-3500EX", "Casio QV-4000", "Casio QV-5700", "Casio QV-R41", "Casio QV-R51", "Casio QV-R61", "Casio EX-S20", "Casio EX-S100", "Casio EX-Z4", "Casio EX-Z50", "Casio EX-Z500", "Casio EX-Z55", "Casio EX-Z60", "Casio EX-Z75", "Casio EX-Z750", "Casio EX-Z8", "Casio EX-Z850", "Casio EX-Z1050", "Casio EX-Z1080", "Casio EX-ZR100", "Casio Exlim Pro 505", "Casio Exlim Pro 600", "Casio Exlim Pro 700", "Contax N Digital", "Creative PC-CAM 600", "Epson R-D1", "Foculus 531C", "Fuji E550", "Fuji E900", "Fuji F700", "Fuji F710", "Fuji F800", "Fuji F810", "Fuji S2Pro", "Fuji S3Pro", "Fuji S5Pro", "Fuji S20Pro", "Fuji S100FS", "Fuji S5000", "Fuji S5100/S5500", "Fuji S5200/S5600", "Fuji S6000fd", "Fuji S7000", "Fuji S9000/S9500", "Fuji S9100/S9600", "Fuji S200EXR", "Fuji SL1000", "Fuji HS10/HS11", "Fuji HS20EXR", "Fuji HS30EXR", "Fuji HS50EXR", "Fuji F550EXR", "Fuji F600EXR", "Fuji F770EXR", "Fuji F800EXR", "Fuji X-Pro1", "Fuji X-S1", "Fuji X100", "Fuji X100S", "Fuji X10", "Fuji X20", "Fuji X-E1", "Fuji XF1", "Fuji IS-1", "Hasselblad CFV", "Hasselblad H3D", "Hasselblad H4D", "Hasselblad V96C", "Imacon Ixpress 16-megapixel", "Imacon Ixpress 22-megapixel", "Imacon Ixpress 39-megapixel", "ISG 2020x1520", "Kodak DC20", "Kodak DC25", "Kodak DC40", "Kodak DC50", "Kodak DC120 (also try kdc2tiff)", "Kodak DCS200", "Kodak DCS315C", "Kodak DCS330C", "Kodak DCS420", "Kodak DCS460", "Kodak DCS460A", "Kodak DCS520C", "Kodak DCS560C", "Kodak DCS620C", "Kodak DCS620X", "Kodak DCS660C", "Kodak DCS660M", "Kodak DCS720X", "Kodak DCS760C", "Kodak DCS760M", "Kodak EOSDCS1", "Kodak EOSDCS3B", "Kodak NC2000F", "Kodak ProBack", "Kodak PB645C", "Kodak PB645H", "Kodak PB645M", "Kodak DCS Pro 14n", "Kodak DCS Pro 14nx", "Kodak DCS Pro SLR/c", "Kodak DCS Pro SLR/n", "Kodak C330", "Kodak C603", "Kodak P850", "Kodak P880", "Kodak Z980", "Kodak Z981", "Kodak Z990", "Kodak Z1015", "Kodak KAI-0340", "Konica KD-400Z", "Konica KD-510Z", "Leaf AFi 7", "Leaf AFi-II 5", "Leaf AFi-II 6", "Leaf AFi-II 7", "Leaf AFi-II 8", "Leaf AFi-II 10", "Leaf AFi-II 10R", "Leaf AFi-II 12", "Leaf AFi-II 12R", "Leaf Aptus 17", "Leaf Aptus 22", "Leaf Aptus 54S", "Leaf Aptus 65", "Leaf Aptus 75", "Leaf Aptus 75S", "Leaf Cantare", "Leaf CatchLight", "Leaf CMost", "Leaf DCB2", "Leaf Valeo 6", "Leaf Valeo 11", "Leaf Valeo 17", "Leaf Valeo 22", "Leaf Volare", "Leica Digilux 2", "Leica Digilux 3", "Leica D-LUX2", "Leica D-LUX3", "Leica D-LUX4", "Leica D-LUX5", "Leica D-LUX6", "Leica V-LUX1", "Leica V-LUX2", "Leica V-LUX3", "Leica V-LUX4", "Logitech Fotoman Pixtura", "Mamiya ZD", "Micron 2010", "Minolta RD175", "Minolta DiMAGE 5", "Minolta DiMAGE 7", "Minolta DiMAGE 7i", "Minolta DiMAGE 7Hi", "Minolta DiMAGE A1", "Minolta DiMAGE A2", "Minolta DiMAGE A200", "Minolta DiMAGE G400", "Minolta DiMAGE G500", "Minolta DiMAGE G530", "Minolta DiMAGE G600", "Minolta DiMAGE Z2", "Minolta Alpha/Dynax/Maxxum 5D", "Minolta Alpha/Dynax/Maxxum 7D", "Motorola PIXL", "Nikon D1", "Nikon D1H", "Nikon D1X", "Nikon D2H", "Nikon D2Hs", "Nikon D2X", "Nikon D2Xs", "Nikon D3", "Nikon D3s", "Nikon D3X", "Nikon D4", "Nikon D40", "Nikon D40X", "Nikon D50", "Nikon D60", "Nikon D600", "Nikon D70", "Nikon D70s", "Nikon D80", "Nikon D90", "Nikon D100", "Nikon D200", "Nikon D300", "Nikon D300s", "Nikon D700", "Nikon D3000", "Nikon D3100", "Nikon D3200", "Nikon D5000", "Nikon D5100", "Nikon D7000", "Nikon D800", "Nikon D800E", "Nikon 1 J1", "Nikon 1 S1", "Nikon 1 V1", "Nikon 1 J2", "Nikon 1 V2", "Nikon 1 J3", "Nikon E700 (\"DIAG RAW\" hack)", "Nikon E800 (\"DIAG RAW\" hack)", "Nikon E880 (\"DIAG RAW\" hack)", "Nikon E900 (\"DIAG RAW\" hack)", "Nikon E950 (\"DIAG RAW\" hack)", "Nikon E990 (\"DIAG RAW\" hack)", "Nikon E995 (\"DIAG RAW\" hack)", "Nikon E2100 (\"DIAG RAW\" hack)", "Nikon E2500 (\"DIAG RAW\" hack)", "Nikon E3200 (\"DIAG RAW\" hack)", "Nikon E3700 (\"DIAG RAW\" hack)", "Nikon E4300 (\"DIAG RAW\" hack)", "Nikon E4500 (\"DIAG RAW\" hack)", "Nikon E5000", "Nikon E5400", "Nikon E5700", "Nikon E8400", "Nikon E8700", "Nikon E8800", "Nikon Coolpix A", "Nikon Coolpix P330", "Nikon Coolpix P6000", "Nikon Coolpix P7000", "Nikon Coolpix P7100", "Nikon Coolpix P7700", "Nikon Coolpix S6 (\"DIAG RAW\" hack)", "Nokia N95", "Nokia X2", "Olympus C3030Z", "Olympus C5050Z", "Olympus C5060WZ", "Olympus C7070WZ", "Olympus C70Z,C7000Z", "Olympus C740UZ", "Olympus C770UZ", "Olympus C8080WZ", "Olympus X200,D560Z,C350Z", "Olympus E-1", "Olympus E-3", "Olympus E-5", "Olympus E-10", "Olympus E-20", "Olympus E-30", "Olympus E-300", "Olympus E-330", "Olympus E-400", "Olympus E-410", "Olympus E-420", "Olympus E-500", "Olympus E-510", "Olympus E-520", "Olympus E-620", "Olympus E-P1", "Olympus E-P2", "Olympus E-P3", "Olympus E-PL1", "Olympus E-PL1s", "Olympus E-PL2", "Olympus E-PL3", "Olympus E-PL5", "Olympus E-PM1", "Olympus E-PM2", "Olympus E-M5", "Olympus SP310", "Olympus SP320", "Olympus SP350", "Olympus SP500UZ", "Olympus SP510UZ", "Olympus SP550UZ", "Olympus SP560UZ", "Olympus SP570UZ", "Olympus XZ-1", "Olympus XZ-10", "Olympus XZ-2", "Panasonic DMC-FZ8", "Panasonic DMC-FZ18", "Panasonic DMC-FZ28", "Panasonic DMC-FZ30", "Panasonic DMC-FZ35/FZ38", "Panasonic DMC-FZ40", "Panasonic DMC-FZ50", "Panasonic DMC-FZ100", "Panasonic DMC-FZ150", "Panasonic DMC-FZ200", "Panasonic DMC-FX150", "Panasonic DMC-G1", "Panasonic DMC-G10", "Panasonic DMC-G2", "Panasonic DMC-G3", "Panasonic DMC-G5", "Panasonic DMC-G6", "Panasonic DMC-GF1", "Panasonic DMC-GF2", "Panasonic DMC-GF3", "Panasonic DMC-GF5", "Panasonic DMC-GH1", "Panasonic DMC-GH2", "Panasonic DMC-GH3", "Panasonic DMC-GX1", "Panasonic DMC-L1", "Panasonic DMC-L10", "Panasonic DMC-LC1", "Panasonic DMC-LX1", "Panasonic DMC-LX2", "Panasonic DMC-LX3", "Panasonic DMC-LX5", "Panasonic DMC-LX7", "Pentax *ist D", "Pentax *ist DL", "Pentax *ist DL2", "Pentax *ist DS", "Pentax *ist DS2", "Pentax K10D", "Pentax K20D", "Pentax K100D", "Pentax K100D Super", "Pentax K200D", "Pentax K2000/K-m", "Pentax K-x", "Pentax K-r", "Pentax K-30", "Pentax K-5", "Pentax K-5 II", "Pentax K-5 IIs", "Pentax K-7", "Pentax MX-1", "Pentax Q10", "Pentax Optio S", "Pentax Optio S4", "Pentax Optio 33WR", "Pentax Optio 750Z", "Pentax 645D", "Phase One LightPhase", "Phase One H 10", "Phase One H 20", "Phase One H 25", "Phase One P 20", "Phase One P 25", "Phase One P 30", "Phase One P 45", "Phase One P 45+", "Phase One P 65", "Pixelink A782", #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 "Polaroid x530", #endif #ifndef NO_JASPER "Redcode R3D format", #endif "Rollei d530flex", "RoverShot 3320af", "Samsung EX1", "Samsung EX2F", "Samsung GX-1S", "Samsung GX10", "Samsung GX20", "Samsung NX10", "Samsung NX11", "Samsung NX100", "Samsung NX20", "Samsung NX200", "Samsung NX210", "Samsung NX1000", "Samsung WB550", "Samsung WB2000", "Samsung S85 (hacked)", "Samsung S850 (hacked)", "Sarnoff 4096x5440", #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 "Sigma SD9", "Sigma SD10", "Sigma SD14", "Sigma SD15", "Sigma SD1", "Sigma SD1 Merill", "Sigma DP1", "Sigma DP1 Merill", "Sigma DP1S", "Sigma DP1X", "Sigma DP2", "Sigma DP2 Merill", "Sigma DP2S", "Sigma DP2X", #endif "Sinar 3072x2048", "Sinar 4080x4080", "Sinar 4080x5440", "Sinar STI format", "SMaL Ultra-Pocket 3", "SMaL Ultra-Pocket 4", "SMaL Ultra-Pocket 5", "Sony DSC-F828", "Sony DSC-R1", "Sony DSC-RX1", "Sony DSC-RX100", "Sony DSC-V3", "Sony DSLR-A100", "Sony DSLR-A200", "Sony DSLR-A230", "Sony DSLR-A290", "Sony DSLR-A300", "Sony DSLR-A330", "Sony DSLR-A350", "Sony DSLR-A380", "Sony DSLR-A390", "Sony DSLR-A450", "Sony DSLR-A500", "Sony DSLR-A550", "Sony DSLR-A580", "Sony DSLR-A700", "Sony DSLR-A850", "Sony DSLR-A900", "Sony NEX-3", "Sony NEX-5", "Sony NEX-5N", "Sony NEX-5R", "Sony NEX-6", "Sony NEX-7", "Sony NEX-C3", "Sony NEX-F3", "Sony SLT-A33", "Sony SLT-A35", "Sony SLT-A37", "Sony SLT-A55V", "Sony SLT-A57", "Sony SLT-A58", "Sony SLT-A65V", "Sony SLT-A77V", "Sony SLT-A99V", "Sony XCD-SX910CR", "STV680 VGA", "ptGrey GRAS-50S5C", "JaiPulnix BB-500CL", "JaiPulnix BB-500GE", "SVS SVS625CL", NULL }; const char** LibRaw::cameraList() { return static_camera_list;} int LibRaw::cameraCount() { return (sizeof(static_camera_list)/sizeof(static_camera_list[0]))-1; } const char * LibRaw::strprogress(enum LibRaw_progress p) { switch(p) { case LIBRAW_PROGRESS_START: return "Starting"; case LIBRAW_PROGRESS_OPEN : return "Opening file"; case LIBRAW_PROGRESS_IDENTIFY : return "Reading metadata"; case LIBRAW_PROGRESS_SIZE_ADJUST: return "Adjusting size"; case LIBRAW_PROGRESS_LOAD_RAW: return "Reading RAW data"; case LIBRAW_PROGRESS_REMOVE_ZEROES: return "Clearing zero values"; case LIBRAW_PROGRESS_BAD_PIXELS : return "Removing dead pixels"; case LIBRAW_PROGRESS_DARK_FRAME: return "Subtracting dark frame data"; case LIBRAW_PROGRESS_FOVEON_INTERPOLATE: return "Interpolating Foveon sensor data"; case LIBRAW_PROGRESS_SCALE_COLORS: return "Scaling colors"; case LIBRAW_PROGRESS_PRE_INTERPOLATE: return "Pre-interpolating"; case LIBRAW_PROGRESS_INTERPOLATE: return "Interpolating"; case LIBRAW_PROGRESS_MIX_GREEN : return "Mixing green channels"; case LIBRAW_PROGRESS_MEDIAN_FILTER : return "Median filter"; case LIBRAW_PROGRESS_HIGHLIGHTS: return "Highlight recovery"; case LIBRAW_PROGRESS_FUJI_ROTATE : return "Rotating Fuji diagonal data"; case LIBRAW_PROGRESS_FLIP : return "Flipping image"; case LIBRAW_PROGRESS_APPLY_PROFILE: return "ICC conversion"; case LIBRAW_PROGRESS_CONVERT_RGB: return "Converting to RGB"; case LIBRAW_PROGRESS_STRETCH: return "Stretching image"; case LIBRAW_PROGRESS_THUMB_LOAD: return "Loading thumbnail"; default: return "Some strange things"; } }
./CrossVul/dataset_final_sorted/CWE-399/cpp/bad_5642_0
crossvul-cpp_data_good_3449_0
/* * fs/inotify_user.c - inotify support for userspace * * Authors: * John McCutchan <ttb@tentacle.dhs.org> * Robert Love <rml@novell.com> * * Copyright (C) 2005 John McCutchan * Copyright 2006 Hewlett-Packard Development Company, L.P. * * Copyright (C) 2009 Eric Paris <Red Hat Inc> * inotify was largely rewriten to make use of the fsnotify infrastructure * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ #include <linux/dcache.h> /* d_unlinked */ #include <linux/fs.h> /* struct inode */ #include <linux/fsnotify_backend.h> #include <linux/inotify.h> #include <linux/path.h> /* struct path */ #include <linux/slab.h> /* kmem_* */ #include <linux/types.h> #include <linux/sched.h> #include "inotify.h" /* * Check if 2 events contain the same information. We do not compare private data * but at this moment that isn't a problem for any know fsnotify listeners. */ static bool event_compare(struct fsnotify_event *old, struct fsnotify_event *new) { if ((old->mask == new->mask) && (old->to_tell == new->to_tell) && (old->data_type == new->data_type) && (old->name_len == new->name_len)) { switch (old->data_type) { case (FSNOTIFY_EVENT_INODE): /* remember, after old was put on the wait_q we aren't * allowed to look at the inode any more, only thing * left to check was if the file_name is the same */ if (!old->name_len || !strcmp(old->file_name, new->file_name)) return true; break; case (FSNOTIFY_EVENT_PATH): if ((old->path.mnt == new->path.mnt) && (old->path.dentry == new->path.dentry)) return true; break; case (FSNOTIFY_EVENT_NONE): if (old->mask & FS_Q_OVERFLOW) return true; else if (old->mask & FS_IN_IGNORED) return false; return true; }; } return false; } static struct fsnotify_event *inotify_merge(struct list_head *list, struct fsnotify_event *event) { struct fsnotify_event_holder *last_holder; struct fsnotify_event *last_event; /* and the list better be locked by something too */ spin_lock(&event->lock); last_holder = list_entry(list->prev, struct fsnotify_event_holder, event_list); last_event = last_holder->event; if (event_compare(last_event, event)) fsnotify_get_event(last_event); else last_event = NULL; spin_unlock(&event->lock); return last_event; } static int inotify_handle_event(struct fsnotify_group *group, struct fsnotify_mark *inode_mark, struct fsnotify_mark *vfsmount_mark, struct fsnotify_event *event) { struct inotify_inode_mark *i_mark; struct inode *to_tell; struct inotify_event_private_data *event_priv; struct fsnotify_event_private_data *fsn_event_priv; struct fsnotify_event *added_event; int wd, ret = 0; BUG_ON(vfsmount_mark); pr_debug("%s: group=%p event=%p to_tell=%p mask=%x\n", __func__, group, event, event->to_tell, event->mask); to_tell = event->to_tell; i_mark = container_of(inode_mark, struct inotify_inode_mark, fsn_mark); wd = i_mark->wd; event_priv = kmem_cache_alloc(event_priv_cachep, GFP_KERNEL); if (unlikely(!event_priv)) return -ENOMEM; fsn_event_priv = &event_priv->fsnotify_event_priv_data; fsn_event_priv->group = group; event_priv->wd = wd; added_event = fsnotify_add_notify_event(group, event, fsn_event_priv, inotify_merge); if (added_event) { inotify_free_event_priv(fsn_event_priv); if (!IS_ERR(added_event)) fsnotify_put_event(added_event); else ret = PTR_ERR(added_event); } if (inode_mark->mask & IN_ONESHOT) fsnotify_destroy_mark(inode_mark); return ret; } static void inotify_freeing_mark(struct fsnotify_mark *fsn_mark, struct fsnotify_group *group) { inotify_ignored_and_remove_idr(fsn_mark, group); } static bool inotify_should_send_event(struct fsnotify_group *group, struct inode *inode, struct fsnotify_mark *inode_mark, struct fsnotify_mark *vfsmount_mark, __u32 mask, void *data, int data_type) { if ((inode_mark->mask & FS_EXCL_UNLINK) && (data_type == FSNOTIFY_EVENT_PATH)) { struct path *path = data; if (d_unlinked(path->dentry)) return false; } return true; } /* * This is NEVER supposed to be called. Inotify marks should either have been * removed from the idr when the watch was removed or in the * fsnotify_destroy_mark_by_group() call when the inotify instance was being * torn down. This is only called if the idr is about to be freed but there * are still marks in it. */ static int idr_callback(int id, void *p, void *data) { struct fsnotify_mark *fsn_mark; struct inotify_inode_mark *i_mark; static bool warned = false; if (warned) return 0; warned = true; fsn_mark = p; i_mark = container_of(fsn_mark, struct inotify_inode_mark, fsn_mark); WARN(1, "inotify closing but id=%d for fsn_mark=%p in group=%p still in " "idr. Probably leaking memory\n", id, p, data); /* * I'm taking the liberty of assuming that the mark in question is a * valid address and I'm dereferencing it. This might help to figure * out why we got here and the panic is no worse than the original * BUG() that was here. */ if (fsn_mark) printk(KERN_WARNING "fsn_mark->group=%p inode=%p wd=%d\n", fsn_mark->group, fsn_mark->i.inode, i_mark->wd); return 0; } static void inotify_free_group_priv(struct fsnotify_group *group) { /* ideally the idr is empty and we won't hit the BUG in teh callback */ idr_for_each(&group->inotify_data.idr, idr_callback, group); idr_remove_all(&group->inotify_data.idr); idr_destroy(&group->inotify_data.idr); atomic_dec(&group->inotify_data.user->inotify_devs); free_uid(group->inotify_data.user); } void inotify_free_event_priv(struct fsnotify_event_private_data *fsn_event_priv) { struct inotify_event_private_data *event_priv; event_priv = container_of(fsn_event_priv, struct inotify_event_private_data, fsnotify_event_priv_data); kmem_cache_free(event_priv_cachep, event_priv); } const struct fsnotify_ops inotify_fsnotify_ops = { .handle_event = inotify_handle_event, .should_send_event = inotify_should_send_event, .free_group_priv = inotify_free_group_priv, .free_event_priv = inotify_free_event_priv, .freeing_mark = inotify_freeing_mark, };
./CrossVul/dataset_final_sorted/CWE-399/c/good_3449_0
crossvul-cpp_data_bad_1856_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 = MagickMin(min + steps, 255); \ if (max - min < steps) \ min = MagickMax(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), ReadDDSInfo(Image *,DDSInfo *), ReadDXT1(Image *,DDSInfo *,ExceptionInfo *), ReadDXT3(Image *,DDSInfo *,ExceptionInfo *), ReadDXT5(Image *,DDSInfo *,ExceptionInfo *), ReadUncompressedRGB(Image *,DDSInfo *,ExceptionInfo *), ReadUncompressedRGBA(Image *,DDSInfo *,ExceptionInfo *), SkipDXTMipmaps(Image *,DDSInfo *,int,ExceptionInfo *), SkipRGBMipmaps(Image *,DDSInfo *,int,ExceptionInfo *), WriteDDSImage(const ImageInfo *,Image *), WriteMipmaps(Image *,const size_t,const size_t,const size_t, const MagickBooleanType,const MagickBooleanType,ExceptionInfo *); static void RemapIndices(const ssize_t *,const unsigned char *,unsigned char *), WriteDDSInfo(Image *,const size_t,const size_t,const size_t), WriteFourCC(Image *,const size_t,const MagickBooleanType, const MagickBooleanType,ExceptionInfo *), WriteImageData(Image *,const size_t,const size_t,const MagickBooleanType, const MagickBooleanType,ExceptionInfo *), WriteIndices(Image *,const DDSVector3,const DDSVector3, unsigned char *), WriteSingleColorFit(Image *,const DDSVector4 *,const ssize_t *), WriteUncompressed(Image *,ExceptionInfo *); 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 = MagickMin(1.0f,MagickMax(0.0f,value->x)); value->y = MagickMin(1.0f,MagickMax(0.0f,value->y)); value->z = MagickMin(1.0f,MagickMax(0.0f,value->z)); value->w = MagickMin(1.0f,MagickMax(0.0f,value->w)); } static inline void VectorClamp3(DDSVector3 *value) { value->x = MagickMin(1.0f,MagickMax(0.0f,value->x)); value->y = MagickMin(1.0f,MagickMax(0.0f,value->y)); value->z = MagickMin(1.0f,MagickMax(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 / MagickMax(w.x,MagickMax(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, MagickMin(4, dds_info->width - x), MagickMin(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; } } return(SkipDXTMipmaps(image,dds_info,8,exception)); } 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, MagickMin(4, dds_info->width - x), MagickMin(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; } } return(SkipDXTMipmaps(image,dds_info,16,exception)); } 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, MagickMin(4, dds_info->width - x), MagickMin(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; } } return(SkipDXTMipmaps(image,dds_info,16,exception)); } 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; } return(SkipRGBMipmaps(image,dds_info,3,exception)); } 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; } return(SkipRGBMipmaps(image,dds_info,4,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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 MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info, int texel_size,ExceptionInfo *exception) { register ssize_t i; MagickOffsetType offset; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } 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); } } return(MagickTrue); } /* Skip the mipmap images for uncompressed (RGB or RGBA) dds files */ static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info, int pixel_size,ExceptionInfo *exception) { MagickOffsetType offset; register ssize_t i; size_t h, w; /* Only skip mipmaps for textures and cube maps */ if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); return(MagickFalse); } 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); } } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % 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) (MagickMax(1,(image->columns+3)/4) * 8)); else (void) WriteBlobLSBLong(image, (unsigned int) (MagickMax(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-399/c/bad_1856_0
crossvul-cpp_data_bad_2392_8
/* * 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. */ #ifdef WIN32 #include <windows.h> #include <shlwapi.h> #endif #include "file.h" #ifndef lint FILE_RCSID("@(#)$File: magic.c,v 1.89 2014/11/28 02:46:39 christos Exp $") #endif /* lint */ #include "magic.h" #include <stdlib.h> #include <unistd.h> #include <string.h> #ifdef QUICK #include <sys/mman.h> #endif #ifdef HAVE_LIMITS_H #include <limits.h> /* for PIPE_BUF */ #endif #if defined(HAVE_UTIMES) # include <sys/time.h> #elif defined(HAVE_UTIME) # if defined(HAVE_SYS_UTIME_H) # include <sys/utime.h> # elif defined(HAVE_UTIME_H) # include <utime.h> # endif #endif #ifdef HAVE_UNISTD_H #include <unistd.h> /* for read() */ #endif #ifndef PIPE_BUF /* Get the PIPE_BUF from pathconf */ #ifdef _PC_PIPE_BUF #define PIPE_BUF pathconf(".", _PC_PIPE_BUF) #else #define PIPE_BUF 512 #endif #endif private void close_and_restore(const struct magic_set *, const char *, int, const struct stat *); private int unreadable_info(struct magic_set *, mode_t, const char *); private const char* get_default_magic(void); #ifndef COMPILE_ONLY private const char *file_or_fd(struct magic_set *, const char *, int); #endif #ifndef STDIN_FILENO #define STDIN_FILENO 0 #endif private const char * get_default_magic(void) { static const char hmagic[] = "/.magic/magic.mgc"; static char *default_magic; char *home, *hmagicpath; #ifndef WIN32 struct stat st; if (default_magic) { free(default_magic); default_magic = NULL; } if ((home = getenv("HOME")) == NULL) return MAGIC; if (asprintf(&hmagicpath, "%s/.magic.mgc", home) < 0) return MAGIC; if (stat(hmagicpath, &st) == -1) { free(hmagicpath); if (asprintf(&hmagicpath, "%s/.magic", home) < 0) return MAGIC; if (stat(hmagicpath, &st) == -1) goto out; if (S_ISDIR(st.st_mode)) { free(hmagicpath); if (asprintf(&hmagicpath, "%s/%s", home, hmagic) < 0) return MAGIC; if (access(hmagicpath, R_OK) == -1) goto out; } } if (asprintf(&default_magic, "%s:%s", hmagicpath, MAGIC) < 0) goto out; free(hmagicpath); return default_magic; out: default_magic = NULL; free(hmagicpath); return MAGIC; #else char *hmagicp; char *tmppath = NULL; LPTSTR dllpath; hmagicpath = NULL; #define APPENDPATH() \ do { \ if (tmppath && access(tmppath, R_OK) != -1) { \ if (hmagicpath == NULL) \ hmagicpath = tmppath; \ else { \ if (asprintf(&hmagicp, "%s%c%s", hmagicpath, \ PATHSEP, tmppath) >= 0) { \ free(hmagicpath); \ hmagicpath = hmagicp; \ } \ free(tmppath); \ } \ tmppath = NULL; \ } \ } while (/*CONSTCOND*/0) if (default_magic) { free(default_magic); default_magic = NULL; } /* First, try to get user-specific magic file */ if ((home = getenv("LOCALAPPDATA")) == NULL) { if ((home = getenv("USERPROFILE")) != NULL) if (asprintf(&tmppath, "%s/Local Settings/Application Data%s", home, hmagic) < 0) tmppath = NULL; } else { if (asprintf(&tmppath, "%s%s", home, hmagic) < 0) tmppath = NULL; } APPENDPATH(); /* Second, try to get a magic file from Common Files */ if ((home = getenv("COMMONPROGRAMFILES")) != NULL) { if (asprintf(&tmppath, "%s%s", home, hmagic) >= 0) APPENDPATH(); } /* Third, try to get magic file relative to dll location */ dllpath = malloc(sizeof(*dllpath) * (MAX_PATH + 1)); dllpath[MAX_PATH] = 0; /* just in case long path gets truncated and not null terminated */ if (GetModuleFileNameA(NULL, dllpath, MAX_PATH)){ PathRemoveFileSpecA(dllpath); if (strlen(dllpath) > 3 && stricmp(&dllpath[strlen(dllpath) - 3], "bin") == 0) { if (asprintf(&tmppath, "%s/../share/misc/magic.mgc", dllpath) >= 0) APPENDPATH(); } else { if (asprintf(&tmppath, "%s/share/misc/magic.mgc", dllpath) >= 0) APPENDPATH(); else if (asprintf(&tmppath, "%s/magic.mgc", dllpath) >= 0) APPENDPATH(); } } /* Don't put MAGIC constant - it likely points to a file within MSys tree */ default_magic = hmagicpath; return default_magic; #endif } public const char * magic_getpath(const char *magicfile, int action) { if (magicfile != NULL) return magicfile; magicfile = getenv("MAGIC"); if (magicfile != NULL) return magicfile; return action == FILE_LOAD ? get_default_magic() : MAGIC; } public struct magic_set * magic_open(int flags) { return file_ms_alloc(flags); } private int unreadable_info(struct magic_set *ms, mode_t md, const char *file) { if (file) { /* We cannot open it, but we were able to stat it. */ if (access(file, W_OK) == 0) if (file_printf(ms, "writable, ") == -1) return -1; if (access(file, X_OK) == 0) if (file_printf(ms, "executable, ") == -1) return -1; } if (S_ISREG(md)) if (file_printf(ms, "regular file, ") == -1) return -1; if (file_printf(ms, "no read permission") == -1) return -1; return 0; } public void magic_close(struct magic_set *ms) { if (ms == NULL) return; file_ms_free(ms); } /* * load a magic file */ public int magic_load(struct magic_set *ms, const char *magicfile) { if (ms == NULL) return -1; return file_apprentice(ms, magicfile, FILE_LOAD); } #ifndef COMPILE_ONLY /* * Install a set of compiled magic buffers. */ public int magic_load_buffers(struct magic_set *ms, void **bufs, size_t *sizes, size_t nbufs) { if (ms == NULL) return -1; return buffer_apprentice(ms, (struct magic **)bufs, sizes, nbufs); } #endif public int magic_compile(struct magic_set *ms, const char *magicfile) { if (ms == NULL) return -1; return file_apprentice(ms, magicfile, FILE_COMPILE); } public int magic_check(struct magic_set *ms, const char *magicfile) { if (ms == NULL) return -1; return file_apprentice(ms, magicfile, FILE_CHECK); } public int magic_list(struct magic_set *ms, const char *magicfile) { if (ms == NULL) return -1; return file_apprentice(ms, magicfile, FILE_LIST); } private void close_and_restore(const struct magic_set *ms, const char *name, int fd, const struct stat *sb) { if (fd == STDIN_FILENO || name == NULL) return; (void) close(fd); if ((ms->flags & MAGIC_PRESERVE_ATIME) != 0) { /* * Try to restore access, modification times if read it. * This is really *bad* because it will modify the status * time of the file... And of course this will affect * backup programs */ #ifdef HAVE_UTIMES struct timeval utsbuf[2]; (void)memset(utsbuf, 0, sizeof(utsbuf)); utsbuf[0].tv_sec = sb->st_atime; utsbuf[1].tv_sec = sb->st_mtime; (void) utimes(name, utsbuf); /* don't care if loses */ #elif defined(HAVE_UTIME_H) || defined(HAVE_SYS_UTIME_H) struct utimbuf utbuf; (void)memset(&utbuf, 0, sizeof(utbuf)); utbuf.actime = sb->st_atime; utbuf.modtime = sb->st_mtime; (void) utime(name, &utbuf); /* don't care if loses */ #endif } } #ifndef COMPILE_ONLY /* * find type of descriptor */ public const char * magic_descriptor(struct magic_set *ms, int fd) { if (ms == NULL) return NULL; return file_or_fd(ms, NULL, fd); } /* * find type of named file */ public const char * magic_file(struct magic_set *ms, const char *inname) { if (ms == NULL) return NULL; return file_or_fd(ms, inname, STDIN_FILENO); } private const char * file_or_fd(struct magic_set *ms, const char *inname, int fd) { int rv = -1; unsigned char *buf; struct stat sb; ssize_t nbytes = 0; /* number of bytes read from a datafile */ int ispipe = 0; off_t pos = (off_t)-1; if (file_reset(ms) == -1) goto out; /* * one extra for terminating '\0', and * some overlapping space for matches near EOF */ #define SLOP (1 + sizeof(union VALUETYPE)) if ((buf = CAST(unsigned char *, malloc(HOWMANY + SLOP))) == NULL) return NULL; switch (file_fsmagic(ms, inname, &sb)) { case -1: /* error */ goto done; case 0: /* nothing found */ break; default: /* matched it and printed type */ rv = 0; goto done; } #ifdef WIN32 /* Place stdin in binary mode, so EOF (Ctrl+Z) doesn't stop early. */ if (fd == STDIN_FILENO) _setmode(STDIN_FILENO, O_BINARY); #endif if (inname == NULL) { if (fstat(fd, &sb) == 0 && S_ISFIFO(sb.st_mode)) ispipe = 1; else pos = lseek(fd, (off_t)0, SEEK_CUR); } else { int flags = O_RDONLY|O_BINARY; int okstat = stat(inname, &sb) == 0; if (okstat && S_ISFIFO(sb.st_mode)) { #ifdef O_NONBLOCK flags |= O_NONBLOCK; #endif ispipe = 1; } errno = 0; if ((fd = open(inname, flags)) < 0) { #ifdef WIN32 /* * Can't stat, can't open. It may have been opened in * fsmagic, so if the user doesn't have read permission, * allow it to say so; otherwise an error was probably * displayed in fsmagic. */ if (!okstat && errno == EACCES) { sb.st_mode = S_IFBLK; okstat = 1; } #endif if (okstat && unreadable_info(ms, sb.st_mode, inname) == -1) goto done; rv = 0; goto done; } #ifdef O_NONBLOCK if ((flags = fcntl(fd, F_GETFL)) != -1) { flags &= ~O_NONBLOCK; (void)fcntl(fd, F_SETFL, flags); } #endif } /* * try looking at the first HOWMANY bytes */ if (ispipe) { ssize_t r = 0; while ((r = sread(fd, (void *)&buf[nbytes], (size_t)(HOWMANY - nbytes), 1)) > 0) { nbytes += r; if (r < PIPE_BUF) break; } if (nbytes == 0) { /* We can not read it, but we were able to stat it. */ if (unreadable_info(ms, sb.st_mode, inname) == -1) goto done; rv = 0; goto done; } } else { /* Windows refuses to read from a big console buffer. */ size_t howmany = #if defined(WIN32) && HOWMANY > 8 * 1024 _isatty(fd) ? 8 * 1024 : #endif HOWMANY; if ((nbytes = read(fd, (char *)buf, howmany)) == -1) { if (inname == NULL && fd != STDIN_FILENO) file_error(ms, errno, "cannot read fd %d", fd); else file_error(ms, errno, "cannot read `%s'", inname == NULL ? "/dev/stdin" : inname); goto done; } } (void)memset(buf + nbytes, 0, SLOP); /* NUL terminate */ if (file_buffer(ms, fd, inname, buf, (size_t)nbytes) == -1) goto done; rv = 0; done: free(buf); if (pos != (off_t)-1) (void)lseek(fd, pos, SEEK_SET); close_and_restore(ms, inname, fd, &sb); out: return rv == 0 ? file_getbuffer(ms) : NULL; } public const char * magic_buffer(struct magic_set *ms, const void *buf, size_t nb) { if (ms == NULL) return NULL; if (file_reset(ms) == -1) return NULL; /* * The main work is done here! * We have the file name and/or the data buffer to be identified. */ if (file_buffer(ms, -1, NULL, buf, nb) == -1) { return NULL; } return file_getbuffer(ms); } #endif public const char * magic_error(struct magic_set *ms) { if (ms == NULL) return "Magic database is not open"; return (ms->event_flags & EVENT_HAD_ERR) ? ms->o.buf : NULL; } public int magic_errno(struct magic_set *ms) { if (ms == NULL) return EINVAL; return (ms->event_flags & EVENT_HAD_ERR) ? ms->error : 0; } public int magic_setflags(struct magic_set *ms, int flags) { if (ms == NULL) return -1; #if !defined(HAVE_UTIME) && !defined(HAVE_UTIMES) if (flags & MAGIC_PRESERVE_ATIME) return -1; #endif ms->flags = flags; return 0; } public int magic_version(void) { return MAGIC_VERSION; } public int magic_setparam(struct magic_set *ms, int param, const void *val) { switch (param) { case MAGIC_PARAM_INDIR_MAX: ms->indir_max = *(const size_t *)val; return 0; case MAGIC_PARAM_NAME_MAX: ms->name_max = *(const size_t *)val; return 0; case MAGIC_PARAM_ELF_PHNUM_MAX: ms->elf_phnum_max = *(const size_t *)val; return 0; case MAGIC_PARAM_ELF_SHNUM_MAX: ms->elf_shnum_max = *(const size_t *)val; return 0; default: errno = EINVAL; return -1; } } public int magic_getparam(struct magic_set *ms, int param, void *val) { switch (param) { case MAGIC_PARAM_INDIR_MAX: *(size_t *)val = ms->indir_max; return 0; case MAGIC_PARAM_NAME_MAX: *(size_t *)val = ms->name_max; return 0; case MAGIC_PARAM_ELF_PHNUM_MAX: *(size_t *)val = ms->elf_phnum_max; return 0; case MAGIC_PARAM_ELF_SHNUM_MAX: *(size_t *)val = ms->elf_shnum_max; return 0; default: errno = EINVAL; return -1; } }
./CrossVul/dataset_final_sorted/CWE-399/c/bad_2392_8
crossvul-cpp_data_bad_3486_2
/* * ARMv7 Cortex-A8 and Cortex-A9 Performance Events handling code. * * ARMv7 support: Jean Pihet <jpihet@mvista.com> * 2010 (c) MontaVista Software, LLC. * * Copied from ARMv6 code, with the low level code inspired * by the ARMv7 Oprofile code. * * Cortex-A8 has up to 4 configurable performance counters and * a single cycle counter. * Cortex-A9 has up to 31 configurable performance counters and * a single cycle counter. * * All counters can be enabled/disabled and IRQ masked separately. The cycle * counter and all 4 performance counters together can be reset separately. */ #ifdef CONFIG_CPU_V7 /* Common ARMv7 event types */ enum armv7_perf_types { ARMV7_PERFCTR_PMNC_SW_INCR = 0x00, ARMV7_PERFCTR_IFETCH_MISS = 0x01, ARMV7_PERFCTR_ITLB_MISS = 0x02, ARMV7_PERFCTR_DCACHE_REFILL = 0x03, ARMV7_PERFCTR_DCACHE_ACCESS = 0x04, ARMV7_PERFCTR_DTLB_REFILL = 0x05, ARMV7_PERFCTR_DREAD = 0x06, ARMV7_PERFCTR_DWRITE = 0x07, ARMV7_PERFCTR_EXC_TAKEN = 0x09, ARMV7_PERFCTR_EXC_EXECUTED = 0x0A, ARMV7_PERFCTR_CID_WRITE = 0x0B, /* ARMV7_PERFCTR_PC_WRITE is equivalent to HW_BRANCH_INSTRUCTIONS. * It counts: * - all branch instructions, * - instructions that explicitly write the PC, * - exception generating instructions. */ ARMV7_PERFCTR_PC_WRITE = 0x0C, ARMV7_PERFCTR_PC_IMM_BRANCH = 0x0D, ARMV7_PERFCTR_UNALIGNED_ACCESS = 0x0F, ARMV7_PERFCTR_PC_BRANCH_MIS_PRED = 0x10, ARMV7_PERFCTR_CLOCK_CYCLES = 0x11, ARMV7_PERFCTR_PC_BRANCH_MIS_USED = 0x12, ARMV7_PERFCTR_CPU_CYCLES = 0xFF }; /* ARMv7 Cortex-A8 specific event types */ enum armv7_a8_perf_types { ARMV7_PERFCTR_INSTR_EXECUTED = 0x08, ARMV7_PERFCTR_PC_PROC_RETURN = 0x0E, ARMV7_PERFCTR_WRITE_BUFFER_FULL = 0x40, ARMV7_PERFCTR_L2_STORE_MERGED = 0x41, ARMV7_PERFCTR_L2_STORE_BUFF = 0x42, ARMV7_PERFCTR_L2_ACCESS = 0x43, ARMV7_PERFCTR_L2_CACH_MISS = 0x44, ARMV7_PERFCTR_AXI_READ_CYCLES = 0x45, ARMV7_PERFCTR_AXI_WRITE_CYCLES = 0x46, ARMV7_PERFCTR_MEMORY_REPLAY = 0x47, ARMV7_PERFCTR_UNALIGNED_ACCESS_REPLAY = 0x48, ARMV7_PERFCTR_L1_DATA_MISS = 0x49, ARMV7_PERFCTR_L1_INST_MISS = 0x4A, ARMV7_PERFCTR_L1_DATA_COLORING = 0x4B, ARMV7_PERFCTR_L1_NEON_DATA = 0x4C, ARMV7_PERFCTR_L1_NEON_CACH_DATA = 0x4D, ARMV7_PERFCTR_L2_NEON = 0x4E, ARMV7_PERFCTR_L2_NEON_HIT = 0x4F, ARMV7_PERFCTR_L1_INST = 0x50, ARMV7_PERFCTR_PC_RETURN_MIS_PRED = 0x51, ARMV7_PERFCTR_PC_BRANCH_FAILED = 0x52, ARMV7_PERFCTR_PC_BRANCH_TAKEN = 0x53, ARMV7_PERFCTR_PC_BRANCH_EXECUTED = 0x54, ARMV7_PERFCTR_OP_EXECUTED = 0x55, ARMV7_PERFCTR_CYCLES_INST_STALL = 0x56, ARMV7_PERFCTR_CYCLES_INST = 0x57, ARMV7_PERFCTR_CYCLES_NEON_DATA_STALL = 0x58, ARMV7_PERFCTR_CYCLES_NEON_INST_STALL = 0x59, ARMV7_PERFCTR_NEON_CYCLES = 0x5A, ARMV7_PERFCTR_PMU0_EVENTS = 0x70, ARMV7_PERFCTR_PMU1_EVENTS = 0x71, ARMV7_PERFCTR_PMU_EVENTS = 0x72, }; /* ARMv7 Cortex-A9 specific event types */ enum armv7_a9_perf_types { ARMV7_PERFCTR_JAVA_HW_BYTECODE_EXEC = 0x40, ARMV7_PERFCTR_JAVA_SW_BYTECODE_EXEC = 0x41, ARMV7_PERFCTR_JAZELLE_BRANCH_EXEC = 0x42, ARMV7_PERFCTR_COHERENT_LINE_MISS = 0x50, ARMV7_PERFCTR_COHERENT_LINE_HIT = 0x51, ARMV7_PERFCTR_ICACHE_DEP_STALL_CYCLES = 0x60, ARMV7_PERFCTR_DCACHE_DEP_STALL_CYCLES = 0x61, ARMV7_PERFCTR_TLB_MISS_DEP_STALL_CYCLES = 0x62, ARMV7_PERFCTR_STREX_EXECUTED_PASSED = 0x63, ARMV7_PERFCTR_STREX_EXECUTED_FAILED = 0x64, ARMV7_PERFCTR_DATA_EVICTION = 0x65, ARMV7_PERFCTR_ISSUE_STAGE_NO_INST = 0x66, ARMV7_PERFCTR_ISSUE_STAGE_EMPTY = 0x67, ARMV7_PERFCTR_INST_OUT_OF_RENAME_STAGE = 0x68, ARMV7_PERFCTR_PREDICTABLE_FUNCT_RETURNS = 0x6E, ARMV7_PERFCTR_MAIN_UNIT_EXECUTED_INST = 0x70, ARMV7_PERFCTR_SECOND_UNIT_EXECUTED_INST = 0x71, ARMV7_PERFCTR_LD_ST_UNIT_EXECUTED_INST = 0x72, ARMV7_PERFCTR_FP_EXECUTED_INST = 0x73, ARMV7_PERFCTR_NEON_EXECUTED_INST = 0x74, ARMV7_PERFCTR_PLD_FULL_DEP_STALL_CYCLES = 0x80, ARMV7_PERFCTR_DATA_WR_DEP_STALL_CYCLES = 0x81, ARMV7_PERFCTR_ITLB_MISS_DEP_STALL_CYCLES = 0x82, ARMV7_PERFCTR_DTLB_MISS_DEP_STALL_CYCLES = 0x83, ARMV7_PERFCTR_MICRO_ITLB_MISS_DEP_STALL_CYCLES = 0x84, ARMV7_PERFCTR_MICRO_DTLB_MISS_DEP_STALL_CYCLES = 0x85, ARMV7_PERFCTR_DMB_DEP_STALL_CYCLES = 0x86, ARMV7_PERFCTR_INTGR_CLK_ENABLED_CYCLES = 0x8A, ARMV7_PERFCTR_DATA_ENGINE_CLK_EN_CYCLES = 0x8B, ARMV7_PERFCTR_ISB_INST = 0x90, ARMV7_PERFCTR_DSB_INST = 0x91, ARMV7_PERFCTR_DMB_INST = 0x92, ARMV7_PERFCTR_EXT_INTERRUPTS = 0x93, ARMV7_PERFCTR_PLE_CACHE_LINE_RQST_COMPLETED = 0xA0, ARMV7_PERFCTR_PLE_CACHE_LINE_RQST_SKIPPED = 0xA1, ARMV7_PERFCTR_PLE_FIFO_FLUSH = 0xA2, ARMV7_PERFCTR_PLE_RQST_COMPLETED = 0xA3, ARMV7_PERFCTR_PLE_FIFO_OVERFLOW = 0xA4, ARMV7_PERFCTR_PLE_RQST_PROG = 0xA5 }; /* * Cortex-A8 HW events mapping * * The hardware events that we support. We do support cache operations but * we have harvard caches and no way to combine instruction and data * accesses/misses in hardware. */ static const unsigned armv7_a8_perf_map[PERF_COUNT_HW_MAX] = { [PERF_COUNT_HW_CPU_CYCLES] = ARMV7_PERFCTR_CPU_CYCLES, [PERF_COUNT_HW_INSTRUCTIONS] = ARMV7_PERFCTR_INSTR_EXECUTED, [PERF_COUNT_HW_CACHE_REFERENCES] = HW_OP_UNSUPPORTED, [PERF_COUNT_HW_CACHE_MISSES] = HW_OP_UNSUPPORTED, [PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = ARMV7_PERFCTR_PC_WRITE, [PERF_COUNT_HW_BRANCH_MISSES] = ARMV7_PERFCTR_PC_BRANCH_MIS_PRED, [PERF_COUNT_HW_BUS_CYCLES] = ARMV7_PERFCTR_CLOCK_CYCLES, }; static const unsigned armv7_a8_perf_cache_map[PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [C(L1D)] = { /* * The performance counters don't differentiate between read * and write accesses/misses so this isn't strictly correct, * but it's the best we can do. Writes and reads get * combined. */ [C(OP_READ)] = { [C(RESULT_ACCESS)] = ARMV7_PERFCTR_DCACHE_ACCESS, [C(RESULT_MISS)] = ARMV7_PERFCTR_DCACHE_REFILL, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = ARMV7_PERFCTR_DCACHE_ACCESS, [C(RESULT_MISS)] = ARMV7_PERFCTR_DCACHE_REFILL, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED, }, }, [C(L1I)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = ARMV7_PERFCTR_L1_INST, [C(RESULT_MISS)] = ARMV7_PERFCTR_L1_INST_MISS, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = ARMV7_PERFCTR_L1_INST, [C(RESULT_MISS)] = ARMV7_PERFCTR_L1_INST_MISS, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED, }, }, [C(LL)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = ARMV7_PERFCTR_L2_ACCESS, [C(RESULT_MISS)] = ARMV7_PERFCTR_L2_CACH_MISS, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = ARMV7_PERFCTR_L2_ACCESS, [C(RESULT_MISS)] = ARMV7_PERFCTR_L2_CACH_MISS, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED, }, }, [C(DTLB)] = { /* * Only ITLB misses and DTLB refills are supported. * If users want the DTLB refills misses a raw counter * must be used. */ [C(OP_READ)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = ARMV7_PERFCTR_DTLB_REFILL, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = ARMV7_PERFCTR_DTLB_REFILL, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED, }, }, [C(ITLB)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = ARMV7_PERFCTR_ITLB_MISS, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = ARMV7_PERFCTR_ITLB_MISS, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED, }, }, [C(BPU)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = ARMV7_PERFCTR_PC_WRITE, [C(RESULT_MISS)] = ARMV7_PERFCTR_PC_BRANCH_MIS_PRED, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = ARMV7_PERFCTR_PC_WRITE, [C(RESULT_MISS)] = ARMV7_PERFCTR_PC_BRANCH_MIS_PRED, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED, }, }, }; /* * Cortex-A9 HW events mapping */ static const unsigned armv7_a9_perf_map[PERF_COUNT_HW_MAX] = { [PERF_COUNT_HW_CPU_CYCLES] = ARMV7_PERFCTR_CPU_CYCLES, [PERF_COUNT_HW_INSTRUCTIONS] = ARMV7_PERFCTR_INST_OUT_OF_RENAME_STAGE, [PERF_COUNT_HW_CACHE_REFERENCES] = ARMV7_PERFCTR_COHERENT_LINE_HIT, [PERF_COUNT_HW_CACHE_MISSES] = ARMV7_PERFCTR_COHERENT_LINE_MISS, [PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = ARMV7_PERFCTR_PC_WRITE, [PERF_COUNT_HW_BRANCH_MISSES] = ARMV7_PERFCTR_PC_BRANCH_MIS_PRED, [PERF_COUNT_HW_BUS_CYCLES] = ARMV7_PERFCTR_CLOCK_CYCLES, }; static const unsigned armv7_a9_perf_cache_map[PERF_COUNT_HW_CACHE_MAX] [PERF_COUNT_HW_CACHE_OP_MAX] [PERF_COUNT_HW_CACHE_RESULT_MAX] = { [C(L1D)] = { /* * The performance counters don't differentiate between read * and write accesses/misses so this isn't strictly correct, * but it's the best we can do. Writes and reads get * combined. */ [C(OP_READ)] = { [C(RESULT_ACCESS)] = ARMV7_PERFCTR_DCACHE_ACCESS, [C(RESULT_MISS)] = ARMV7_PERFCTR_DCACHE_REFILL, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = ARMV7_PERFCTR_DCACHE_ACCESS, [C(RESULT_MISS)] = ARMV7_PERFCTR_DCACHE_REFILL, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED, }, }, [C(L1I)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = ARMV7_PERFCTR_IFETCH_MISS, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = ARMV7_PERFCTR_IFETCH_MISS, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED, }, }, [C(LL)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED, }, }, [C(DTLB)] = { /* * Only ITLB misses and DTLB refills are supported. * If users want the DTLB refills misses a raw counter * must be used. */ [C(OP_READ)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = ARMV7_PERFCTR_DTLB_REFILL, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = ARMV7_PERFCTR_DTLB_REFILL, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED, }, }, [C(ITLB)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = ARMV7_PERFCTR_ITLB_MISS, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = ARMV7_PERFCTR_ITLB_MISS, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED, }, }, [C(BPU)] = { [C(OP_READ)] = { [C(RESULT_ACCESS)] = ARMV7_PERFCTR_PC_WRITE, [C(RESULT_MISS)] = ARMV7_PERFCTR_PC_BRANCH_MIS_PRED, }, [C(OP_WRITE)] = { [C(RESULT_ACCESS)] = ARMV7_PERFCTR_PC_WRITE, [C(RESULT_MISS)] = ARMV7_PERFCTR_PC_BRANCH_MIS_PRED, }, [C(OP_PREFETCH)] = { [C(RESULT_ACCESS)] = CACHE_OP_UNSUPPORTED, [C(RESULT_MISS)] = CACHE_OP_UNSUPPORTED, }, }, }; /* * Perf Events counters */ enum armv7_counters { ARMV7_CYCLE_COUNTER = 1, /* Cycle counter */ ARMV7_COUNTER0 = 2, /* First event counter */ }; /* * The cycle counter is ARMV7_CYCLE_COUNTER. * The first event counter is ARMV7_COUNTER0. * The last event counter is (ARMV7_COUNTER0 + armpmu->num_events - 1). */ #define ARMV7_COUNTER_LAST (ARMV7_COUNTER0 + armpmu->num_events - 1) /* * ARMv7 low level PMNC access */ /* * Per-CPU PMNC: config reg */ #define ARMV7_PMNC_E (1 << 0) /* Enable all counters */ #define ARMV7_PMNC_P (1 << 1) /* Reset all counters */ #define ARMV7_PMNC_C (1 << 2) /* Cycle counter reset */ #define ARMV7_PMNC_D (1 << 3) /* CCNT counts every 64th cpu cycle */ #define ARMV7_PMNC_X (1 << 4) /* Export to ETM */ #define ARMV7_PMNC_DP (1 << 5) /* Disable CCNT if non-invasive debug*/ #define ARMV7_PMNC_N_SHIFT 11 /* Number of counters supported */ #define ARMV7_PMNC_N_MASK 0x1f #define ARMV7_PMNC_MASK 0x3f /* Mask for writable bits */ /* * Available counters */ #define ARMV7_CNT0 0 /* First event counter */ #define ARMV7_CCNT 31 /* Cycle counter */ /* Perf Event to low level counters mapping */ #define ARMV7_EVENT_CNT_TO_CNTx (ARMV7_COUNTER0 - ARMV7_CNT0) /* * CNTENS: counters enable reg */ #define ARMV7_CNTENS_P(idx) (1 << (idx - ARMV7_EVENT_CNT_TO_CNTx)) #define ARMV7_CNTENS_C (1 << ARMV7_CCNT) /* * CNTENC: counters disable reg */ #define ARMV7_CNTENC_P(idx) (1 << (idx - ARMV7_EVENT_CNT_TO_CNTx)) #define ARMV7_CNTENC_C (1 << ARMV7_CCNT) /* * INTENS: counters overflow interrupt enable reg */ #define ARMV7_INTENS_P(idx) (1 << (idx - ARMV7_EVENT_CNT_TO_CNTx)) #define ARMV7_INTENS_C (1 << ARMV7_CCNT) /* * INTENC: counters overflow interrupt disable reg */ #define ARMV7_INTENC_P(idx) (1 << (idx - ARMV7_EVENT_CNT_TO_CNTx)) #define ARMV7_INTENC_C (1 << ARMV7_CCNT) /* * EVTSEL: Event selection reg */ #define ARMV7_EVTSEL_MASK 0xff /* Mask for writable bits */ /* * SELECT: Counter selection reg */ #define ARMV7_SELECT_MASK 0x1f /* Mask for writable bits */ /* * FLAG: counters overflow flag status reg */ #define ARMV7_FLAG_P(idx) (1 << (idx - ARMV7_EVENT_CNT_TO_CNTx)) #define ARMV7_FLAG_C (1 << ARMV7_CCNT) #define ARMV7_FLAG_MASK 0xffffffff /* Mask for writable bits */ #define ARMV7_OVERFLOWED_MASK ARMV7_FLAG_MASK static inline unsigned long armv7_pmnc_read(void) { u32 val; asm volatile("mrc p15, 0, %0, c9, c12, 0" : "=r"(val)); return val; } static inline void armv7_pmnc_write(unsigned long val) { val &= ARMV7_PMNC_MASK; isb(); asm volatile("mcr p15, 0, %0, c9, c12, 0" : : "r"(val)); } static inline int armv7_pmnc_has_overflowed(unsigned long pmnc) { return pmnc & ARMV7_OVERFLOWED_MASK; } static inline int armv7_pmnc_counter_has_overflowed(unsigned long pmnc, enum armv7_counters counter) { int ret = 0; if (counter == ARMV7_CYCLE_COUNTER) ret = pmnc & ARMV7_FLAG_C; else if ((counter >= ARMV7_COUNTER0) && (counter <= ARMV7_COUNTER_LAST)) ret = pmnc & ARMV7_FLAG_P(counter); else pr_err("CPU%u checking wrong counter %d overflow status\n", smp_processor_id(), counter); return ret; } static inline int armv7_pmnc_select_counter(unsigned int idx) { u32 val; if ((idx < ARMV7_COUNTER0) || (idx > ARMV7_COUNTER_LAST)) { pr_err("CPU%u selecting wrong PMNC counter" " %d\n", smp_processor_id(), idx); return -1; } val = (idx - ARMV7_EVENT_CNT_TO_CNTx) & ARMV7_SELECT_MASK; asm volatile("mcr p15, 0, %0, c9, c12, 5" : : "r" (val)); isb(); return idx; } static inline u32 armv7pmu_read_counter(int idx) { unsigned long value = 0; if (idx == ARMV7_CYCLE_COUNTER) asm volatile("mrc p15, 0, %0, c9, c13, 0" : "=r" (value)); else if ((idx >= ARMV7_COUNTER0) && (idx <= ARMV7_COUNTER_LAST)) { if (armv7_pmnc_select_counter(idx) == idx) asm volatile("mrc p15, 0, %0, c9, c13, 2" : "=r" (value)); } else pr_err("CPU%u reading wrong counter %d\n", smp_processor_id(), idx); return value; } static inline void armv7pmu_write_counter(int idx, u32 value) { if (idx == ARMV7_CYCLE_COUNTER) asm volatile("mcr p15, 0, %0, c9, c13, 0" : : "r" (value)); else if ((idx >= ARMV7_COUNTER0) && (idx <= ARMV7_COUNTER_LAST)) { if (armv7_pmnc_select_counter(idx) == idx) asm volatile("mcr p15, 0, %0, c9, c13, 2" : : "r" (value)); } else pr_err("CPU%u writing wrong counter %d\n", smp_processor_id(), idx); } static inline void armv7_pmnc_write_evtsel(unsigned int idx, u32 val) { if (armv7_pmnc_select_counter(idx) == idx) { val &= ARMV7_EVTSEL_MASK; asm volatile("mcr p15, 0, %0, c9, c13, 1" : : "r" (val)); } } static inline u32 armv7_pmnc_enable_counter(unsigned int idx) { u32 val; if ((idx != ARMV7_CYCLE_COUNTER) && ((idx < ARMV7_COUNTER0) || (idx > ARMV7_COUNTER_LAST))) { pr_err("CPU%u enabling wrong PMNC counter" " %d\n", smp_processor_id(), idx); return -1; } if (idx == ARMV7_CYCLE_COUNTER) val = ARMV7_CNTENS_C; else val = ARMV7_CNTENS_P(idx); asm volatile("mcr p15, 0, %0, c9, c12, 1" : : "r" (val)); return idx; } static inline u32 armv7_pmnc_disable_counter(unsigned int idx) { u32 val; if ((idx != ARMV7_CYCLE_COUNTER) && ((idx < ARMV7_COUNTER0) || (idx > ARMV7_COUNTER_LAST))) { pr_err("CPU%u disabling wrong PMNC counter" " %d\n", smp_processor_id(), idx); return -1; } if (idx == ARMV7_CYCLE_COUNTER) val = ARMV7_CNTENC_C; else val = ARMV7_CNTENC_P(idx); asm volatile("mcr p15, 0, %0, c9, c12, 2" : : "r" (val)); return idx; } static inline u32 armv7_pmnc_enable_intens(unsigned int idx) { u32 val; if ((idx != ARMV7_CYCLE_COUNTER) && ((idx < ARMV7_COUNTER0) || (idx > ARMV7_COUNTER_LAST))) { pr_err("CPU%u enabling wrong PMNC counter" " interrupt enable %d\n", smp_processor_id(), idx); return -1; } if (idx == ARMV7_CYCLE_COUNTER) val = ARMV7_INTENS_C; else val = ARMV7_INTENS_P(idx); asm volatile("mcr p15, 0, %0, c9, c14, 1" : : "r" (val)); return idx; } static inline u32 armv7_pmnc_disable_intens(unsigned int idx) { u32 val; if ((idx != ARMV7_CYCLE_COUNTER) && ((idx < ARMV7_COUNTER0) || (idx > ARMV7_COUNTER_LAST))) { pr_err("CPU%u disabling wrong PMNC counter" " interrupt enable %d\n", smp_processor_id(), idx); return -1; } if (idx == ARMV7_CYCLE_COUNTER) val = ARMV7_INTENC_C; else val = ARMV7_INTENC_P(idx); asm volatile("mcr p15, 0, %0, c9, c14, 2" : : "r" (val)); return idx; } static inline u32 armv7_pmnc_getreset_flags(void) { u32 val; /* Read */ asm volatile("mrc p15, 0, %0, c9, c12, 3" : "=r" (val)); /* Write to clear flags */ val &= ARMV7_FLAG_MASK; asm volatile("mcr p15, 0, %0, c9, c12, 3" : : "r" (val)); return val; } #ifdef DEBUG static void armv7_pmnc_dump_regs(void) { u32 val; unsigned int cnt; printk(KERN_INFO "PMNC registers dump:\n"); asm volatile("mrc p15, 0, %0, c9, c12, 0" : "=r" (val)); printk(KERN_INFO "PMNC =0x%08x\n", val); asm volatile("mrc p15, 0, %0, c9, c12, 1" : "=r" (val)); printk(KERN_INFO "CNTENS=0x%08x\n", val); asm volatile("mrc p15, 0, %0, c9, c14, 1" : "=r" (val)); printk(KERN_INFO "INTENS=0x%08x\n", val); asm volatile("mrc p15, 0, %0, c9, c12, 3" : "=r" (val)); printk(KERN_INFO "FLAGS =0x%08x\n", val); asm volatile("mrc p15, 0, %0, c9, c12, 5" : "=r" (val)); printk(KERN_INFO "SELECT=0x%08x\n", val); asm volatile("mrc p15, 0, %0, c9, c13, 0" : "=r" (val)); printk(KERN_INFO "CCNT =0x%08x\n", val); for (cnt = ARMV7_COUNTER0; cnt < ARMV7_COUNTER_LAST; cnt++) { armv7_pmnc_select_counter(cnt); asm volatile("mrc p15, 0, %0, c9, c13, 2" : "=r" (val)); printk(KERN_INFO "CNT[%d] count =0x%08x\n", cnt-ARMV7_EVENT_CNT_TO_CNTx, val); asm volatile("mrc p15, 0, %0, c9, c13, 1" : "=r" (val)); printk(KERN_INFO "CNT[%d] evtsel=0x%08x\n", cnt-ARMV7_EVENT_CNT_TO_CNTx, val); } } #endif static void armv7pmu_enable_event(struct hw_perf_event *hwc, int idx) { unsigned long flags; /* * Enable counter and interrupt, and set the counter to count * the event that we're interested in. */ raw_spin_lock_irqsave(&pmu_lock, flags); /* * Disable counter */ armv7_pmnc_disable_counter(idx); /* * Set event (if destined for PMNx counters) * We don't need to set the event if it's a cycle count */ if (idx != ARMV7_CYCLE_COUNTER) armv7_pmnc_write_evtsel(idx, hwc->config_base); /* * Enable interrupt for this counter */ armv7_pmnc_enable_intens(idx); /* * Enable counter */ armv7_pmnc_enable_counter(idx); raw_spin_unlock_irqrestore(&pmu_lock, flags); } static void armv7pmu_disable_event(struct hw_perf_event *hwc, int idx) { unsigned long flags; /* * Disable counter and interrupt */ raw_spin_lock_irqsave(&pmu_lock, flags); /* * Disable counter */ armv7_pmnc_disable_counter(idx); /* * Disable interrupt for this counter */ armv7_pmnc_disable_intens(idx); raw_spin_unlock_irqrestore(&pmu_lock, flags); } static irqreturn_t armv7pmu_handle_irq(int irq_num, void *dev) { unsigned long pmnc; struct perf_sample_data data; struct cpu_hw_events *cpuc; struct pt_regs *regs; int idx; /* * Get and reset the IRQ flags */ pmnc = armv7_pmnc_getreset_flags(); /* * Did an overflow occur? */ if (!armv7_pmnc_has_overflowed(pmnc)) return IRQ_NONE; /* * Handle the counter(s) overflow(s) */ regs = get_irq_regs(); perf_sample_data_init(&data, 0); cpuc = &__get_cpu_var(cpu_hw_events); for (idx = 0; idx <= armpmu->num_events; ++idx) { struct perf_event *event = cpuc->events[idx]; struct hw_perf_event *hwc; if (!test_bit(idx, cpuc->active_mask)) continue; /* * We have a single interrupt for all counters. Check that * each counter has overflowed before we process it. */ if (!armv7_pmnc_counter_has_overflowed(pmnc, idx)) continue; hwc = &event->hw; armpmu_event_update(event, hwc, idx, 1); data.period = event->hw.last_period; if (!armpmu_event_set_period(event, hwc, idx)) continue; if (perf_event_overflow(event, 0, &data, regs)) armpmu->disable(hwc, idx); } /* * Handle the pending perf events. * * Note: this call *must* be run with interrupts disabled. For * platforms that can have the PMU interrupts raised as an NMI, this * will not work. */ irq_work_run(); return IRQ_HANDLED; } static void armv7pmu_start(void) { unsigned long flags; raw_spin_lock_irqsave(&pmu_lock, flags); /* Enable all counters */ armv7_pmnc_write(armv7_pmnc_read() | ARMV7_PMNC_E); raw_spin_unlock_irqrestore(&pmu_lock, flags); } static void armv7pmu_stop(void) { unsigned long flags; raw_spin_lock_irqsave(&pmu_lock, flags); /* Disable all counters */ armv7_pmnc_write(armv7_pmnc_read() & ~ARMV7_PMNC_E); raw_spin_unlock_irqrestore(&pmu_lock, flags); } static int armv7pmu_get_event_idx(struct cpu_hw_events *cpuc, struct hw_perf_event *event) { int idx; /* Always place a cycle counter into the cycle counter. */ if (event->config_base == ARMV7_PERFCTR_CPU_CYCLES) { if (test_and_set_bit(ARMV7_CYCLE_COUNTER, cpuc->used_mask)) return -EAGAIN; return ARMV7_CYCLE_COUNTER; } else { /* * For anything other than a cycle counter, try and use * the events counters */ for (idx = ARMV7_COUNTER0; idx <= armpmu->num_events; ++idx) { if (!test_and_set_bit(idx, cpuc->used_mask)) return idx; } /* The counters are all in use. */ return -EAGAIN; } } static void armv7pmu_reset(void *info) { u32 idx, nb_cnt = armpmu->num_events; /* The counter and interrupt enable registers are unknown at reset. */ for (idx = 1; idx < nb_cnt; ++idx) armv7pmu_disable_event(NULL, idx); /* Initialize & Reset PMNC: C and P bits */ armv7_pmnc_write(ARMV7_PMNC_P | ARMV7_PMNC_C); } static struct arm_pmu armv7pmu = { .handle_irq = armv7pmu_handle_irq, .enable = armv7pmu_enable_event, .disable = armv7pmu_disable_event, .read_counter = armv7pmu_read_counter, .write_counter = armv7pmu_write_counter, .get_event_idx = armv7pmu_get_event_idx, .start = armv7pmu_start, .stop = armv7pmu_stop, .reset = armv7pmu_reset, .raw_event_mask = 0xFF, .max_period = (1LLU << 32) - 1, }; static u32 __init armv7_read_num_pmnc_events(void) { u32 nb_cnt; /* Read the nb of CNTx counters supported from PMNC */ nb_cnt = (armv7_pmnc_read() >> ARMV7_PMNC_N_SHIFT) & ARMV7_PMNC_N_MASK; /* Add the CPU cycles counter and return */ return nb_cnt + 1; } static const struct arm_pmu *__init armv7_a8_pmu_init(void) { armv7pmu.id = ARM_PERF_PMU_ID_CA8; armv7pmu.name = "ARMv7 Cortex-A8"; armv7pmu.cache_map = &armv7_a8_perf_cache_map; armv7pmu.event_map = &armv7_a8_perf_map; armv7pmu.num_events = armv7_read_num_pmnc_events(); return &armv7pmu; } static const struct arm_pmu *__init armv7_a9_pmu_init(void) { armv7pmu.id = ARM_PERF_PMU_ID_CA9; armv7pmu.name = "ARMv7 Cortex-A9"; armv7pmu.cache_map = &armv7_a9_perf_cache_map; armv7pmu.event_map = &armv7_a9_perf_map; armv7pmu.num_events = armv7_read_num_pmnc_events(); return &armv7pmu; } #else static const struct arm_pmu *__init armv7_a8_pmu_init(void) { return NULL; } static const struct arm_pmu *__init armv7_a9_pmu_init(void) { return NULL; } #endif /* CONFIG_CPU_V7 */
./CrossVul/dataset_final_sorted/CWE-399/c/bad_3486_2
crossvul-cpp_data_bad_5318_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC AAA CCCC H H EEEEE % % C A A C H H E % % C AAAAA C HHHHH EEE % % C A A C H H E % % CCCC A A CCCC H H EEEEE % % % % % % MagickCore Pixel Cache Methods % % % % Software Design % % Cristy % % July 1999 % % % % % % Copyright 1999-2016 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/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/cache-private.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite-private.h" #include "magick/distribute-cache-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/list.h" #include "magick/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/memory-private.h" #include "magick/nt-base-private.h" #include "magick/option.h" #include "magick/pixel.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/policy.h" #include "magick/quantum.h" #include "magick/random_.h" #include "magick/registry.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/splay-tree.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/utility.h" #include "magick/utility-private.h" #if defined(MAGICKCORE_ZLIB_DELEGATE) #include "zlib.h" #endif /* Define declarations. */ #define CacheTick(offset,extent) QuantumTick((MagickOffsetType) offset,extent) #define IsFileDescriptorLimitExceeded() (GetMagickResource(FileResource) > \ GetMagickResourceLimit(FileResource) ? MagickTrue : MagickFalse) /* Typedef declarations. */ typedef struct _MagickModulo { ssize_t quotient, remainder; } MagickModulo; /* Forward declarations. */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static Cache GetImagePixelCache(Image *,const MagickBooleanType,ExceptionInfo *) magick_hot_spot; static const IndexPacket *GetVirtualIndexesFromCache(const Image *); static const PixelPacket *GetVirtualPixelCache(const Image *,const VirtualPixelMethod,const ssize_t, const ssize_t,const size_t,const size_t,ExceptionInfo *), *GetVirtualPixelsCache(const Image *); static MagickBooleanType GetOneAuthenticPixelFromCache(Image *,const ssize_t,const ssize_t, PixelPacket *,ExceptionInfo *), GetOneVirtualPixelFromCache(const Image *,const VirtualPixelMethod, const ssize_t,const ssize_t,PixelPacket *,ExceptionInfo *), OpenPixelCache(Image *,const MapMode,ExceptionInfo *), OpenPixelCacheOnDisk(CacheInfo *,const MapMode), ReadPixelCacheIndexes(CacheInfo *magick_restrict,NexusInfo *magick_restrict, ExceptionInfo *), ReadPixelCachePixels(CacheInfo *magick_restrict,NexusInfo *magick_restrict, ExceptionInfo *), SyncAuthenticPixelsCache(Image *,ExceptionInfo *), WritePixelCacheIndexes(CacheInfo *,NexusInfo *magick_restrict, ExceptionInfo *), WritePixelCachePixels(CacheInfo *,NexusInfo *magick_restrict, ExceptionInfo *); static PixelPacket *GetAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t, const size_t,ExceptionInfo *), *QueueAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t, const size_t,ExceptionInfo *), *SetPixelCacheNexusPixels(const CacheInfo *,const MapMode, const RectangleInfo *,const MagickBooleanType,NexusInfo *,ExceptionInfo *) magick_hot_spot; #if defined(__cplusplus) || defined(c_plusplus) } #endif /* Global declarations. */ static volatile MagickBooleanType instantiate_cache = MagickFalse; static SemaphoreInfo *cache_semaphore = (SemaphoreInfo *) NULL; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCache() acquires a pixel cache. % % The format of the AcquirePixelCache() method is: % % Cache AcquirePixelCache(const size_t number_threads) % % A description of each parameter follows: % % o number_threads: the number of nexus threads. % */ MagickExport Cache AcquirePixelCache(const size_t number_threads) { CacheInfo *magick_restrict cache_info; char *synchronize; cache_info=(CacheInfo *) AcquireQuantumMemory(1,sizeof(*cache_info)); if (cache_info == (CacheInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(cache_info,0,sizeof(*cache_info)); cache_info->type=UndefinedCache; cache_info->mode=IOMode; cache_info->colorspace=sRGBColorspace; cache_info->channels=4; cache_info->file=(-1); cache_info->id=GetMagickThreadId(); cache_info->number_threads=number_threads; if (GetOpenMPMaximumThreads() > cache_info->number_threads) cache_info->number_threads=GetOpenMPMaximumThreads(); if (GetMagickResourceLimit(ThreadResource) > cache_info->number_threads) cache_info->number_threads=(size_t) GetMagickResourceLimit(ThreadResource); if (cache_info->number_threads == 0) cache_info->number_threads=1; cache_info->nexus_info=AcquirePixelCacheNexus(cache_info->number_threads); if (cache_info->nexus_info == (NexusInfo **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); synchronize=GetEnvironmentValue("MAGICK_SYNCHRONIZE"); if (synchronize != (const char *) NULL) { cache_info->synchronize=IsStringTrue(synchronize); synchronize=DestroyString(synchronize); } cache_info->semaphore=AllocateSemaphoreInfo(); cache_info->reference_count=1; cache_info->file_semaphore=AllocateSemaphoreInfo(); cache_info->debug=IsEventLogging(); cache_info->signature=MagickSignature; return((Cache ) cache_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCacheNexus() allocates the NexusInfo structure. % % The format of the AcquirePixelCacheNexus method is: % % NexusInfo **AcquirePixelCacheNexus(const size_t number_threads) % % A description of each parameter follows: % % o number_threads: the number of nexus threads. % */ MagickExport NexusInfo **AcquirePixelCacheNexus(const size_t number_threads) { NexusInfo **magick_restrict nexus_info; register ssize_t i; nexus_info=(NexusInfo **) MagickAssumeAligned(AcquireAlignedMemory( number_threads,sizeof(*nexus_info))); if (nexus_info == (NexusInfo **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); nexus_info[0]=(NexusInfo *) AcquireQuantumMemory(number_threads, sizeof(**nexus_info)); if (nexus_info[0] == (NexusInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(nexus_info[0],0,number_threads*sizeof(**nexus_info)); for (i=0; i < (ssize_t) number_threads; i++) { nexus_info[i]=(&nexus_info[0][i]); nexus_info[i]->signature=MagickSignature; } return(nexus_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCachePixels() returns the pixels associated with the specified % image. % % The format of the AcquirePixelCachePixels() method is: % % const void *AcquirePixelCachePixels(const Image *image, % MagickSizeType *length,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o length: the pixel cache length. % % o exception: return any errors or warnings in this structure. % */ MagickExport const void *AcquirePixelCachePixels(const Image *image, MagickSizeType *length,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); (void) exception; *length=0; if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache)) return((const void *) NULL); *length=cache_info->length; return((const void *) cache_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a c h e C o m p o n e n t G e n e s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CacheComponentGenesis() instantiates the cache component. % % The format of the CacheComponentGenesis method is: % % MagickBooleanType CacheComponentGenesis(void) % */ MagickExport MagickBooleanType CacheComponentGenesis(void) { if (cache_semaphore == (SemaphoreInfo *) NULL) cache_semaphore=AllocateSemaphoreInfo(); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a c h e C o m p o n e n t T e r m i n u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CacheComponentTerminus() destroys the cache component. % % The format of the CacheComponentTerminus() method is: % % CacheComponentTerminus(void) % */ MagickExport void CacheComponentTerminus(void) { if (cache_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&cache_semaphore); LockSemaphoreInfo(cache_semaphore); instantiate_cache=MagickFalse; UnlockSemaphoreInfo(cache_semaphore); DestroySemaphoreInfo(&cache_semaphore); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l i p P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClipPixelCacheNexus() clips the cache nexus as defined by the image clip % mask. The method returns MagickTrue if the pixel region is clipped, % otherwise MagickFalse. % % The format of the ClipPixelCacheNexus() method is: % % MagickBooleanType ClipPixelCacheNexus(Image *image,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to clip. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ClipPixelCacheNexus(Image *image, NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickSizeType number_pixels; NexusInfo **magick_restrict clip_nexus, **magick_restrict image_nexus; register const PixelPacket *magick_restrict r; register IndexPacket *magick_restrict nexus_indexes, *magick_restrict indexes; register PixelPacket *magick_restrict p, *magick_restrict q; register ssize_t i; /* Apply clip mask. */ if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->clip_mask == (Image *) NULL) || (image->storage_class == PseudoClass)) return(MagickTrue); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return(MagickFalse); image_nexus=AcquirePixelCacheNexus(1); clip_nexus=AcquirePixelCacheNexus(1); if ((image_nexus == (NexusInfo **) NULL) || (clip_nexus == (NexusInfo **) NULL)) ThrowBinaryException(CacheError,"UnableToGetCacheNexus",image->filename); p=GetAuthenticPixelCacheNexus(image,nexus_info->region.x,nexus_info->region.y, nexus_info->region.width,nexus_info->region.height,image_nexus[0], exception); indexes=image_nexus[0]->indexes; q=nexus_info->pixels; nexus_indexes=nexus_info->indexes; r=GetVirtualPixelsFromNexus(image->clip_mask,MaskVirtualPixelMethod, nexus_info->region.x,nexus_info->region.y,nexus_info->region.width, nexus_info->region.height,clip_nexus[0],exception); number_pixels=(MagickSizeType) nexus_info->region.width* nexus_info->region.height; for (i=0; i < (ssize_t) number_pixels; i++) { if ((p == (PixelPacket *) NULL) || (r == (const PixelPacket *) NULL)) break; if (GetPixelIntensity(image,r) > (QuantumRange/2.0)) { SetPixelRed(q,GetPixelRed(p)); SetPixelGreen(q,GetPixelGreen(p)); SetPixelBlue(q,GetPixelBlue(p)); SetPixelOpacity(q,GetPixelOpacity(p)); if (cache_info->active_index_channel != MagickFalse) SetPixelIndex(nexus_indexes+i,GetPixelIndex(indexes+i)); } p++; q++; r++; } clip_nexus=DestroyPixelCacheNexus(clip_nexus,1); image_nexus=DestroyPixelCacheNexus(image_nexus,1); if (i < (ssize_t) number_pixels) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCache() clones a pixel cache. % % The format of the ClonePixelCache() method is: % % Cache ClonePixelCache(const Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ MagickExport Cache ClonePixelCache(const Cache cache) { CacheInfo *magick_restrict clone_info; const CacheInfo *magick_restrict cache_info; assert(cache != NULL); cache_info=(const CacheInfo *) cache; assert(cache_info->signature == MagickSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); clone_info=(CacheInfo *) AcquirePixelCache(cache_info->number_threads); if (clone_info == (Cache) NULL) return((Cache) NULL); clone_info->virtual_pixel_method=cache_info->virtual_pixel_method; return((Cache ) clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCacheMethods() clones the pixel cache methods from one cache to % another. % % The format of the ClonePixelCacheMethods() method is: % % void ClonePixelCacheMethods(Cache clone,const Cache cache) % % A description of each parameter follows: % % o clone: Specifies a pointer to a Cache structure. % % o cache: the pixel cache. % */ MagickExport void ClonePixelCacheMethods(Cache clone,const Cache cache) { CacheInfo *magick_restrict cache_info, *magick_restrict source_info; assert(clone != (Cache) NULL); source_info=(CacheInfo *) clone; assert(source_info->signature == MagickSignature); if (source_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", source_info->filename); assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickSignature); source_info->methods=cache_info->methods; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e R e p o s i t o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCacheRepository() clones the source pixel cache to the destination % cache. % % The format of the ClonePixelCacheRepository() method is: % % MagickBooleanType ClonePixelCacheRepository(CacheInfo *cache_info, % CacheInfo *source_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o source_info: the source pixel cache. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ClonePixelCacheOnDisk( CacheInfo *magick_restrict cache_info,CacheInfo *magick_restrict clone_info, ExceptionInfo *exception) { MagickSizeType extent; size_t quantum; ssize_t count; struct stat file_stats; unsigned char *buffer; /* Clone pixel cache on disk with identical morphology. */ if ((OpenPixelCacheOnDisk(cache_info,ReadMode) == MagickFalse) || (OpenPixelCacheOnDisk(clone_info,IOMode) == MagickFalse)) return(MagickFalse); quantum=(size_t) MagickMaxBufferExtent; if ((fstat(cache_info->file,&file_stats) == 0) && (file_stats.st_size > 0)) quantum=(size_t) MagickMin(file_stats.st_size,MagickMaxBufferExtent); buffer=(unsigned char *) AcquireQuantumMemory(quantum,sizeof(*buffer)); if (buffer == (unsigned char *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); extent=0; while ((count=read(cache_info->file,buffer,quantum)) > 0) { ssize_t number_bytes; number_bytes=write(clone_info->file,buffer,(size_t) count); if (number_bytes != count) break; extent+=number_bytes; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); if (extent != cache_info->length) return(MagickFalse); return(MagickTrue); } static MagickBooleanType ClonePixelCacheRepository( CacheInfo *magick_restrict clone_info,CacheInfo *magick_restrict cache_info, ExceptionInfo *exception) { #define MaxCacheThreads 2 #define cache_threads(source,destination) \ num_threads(((source)->type == DiskCache) || \ ((destination)->type == DiskCache) || (((source)->rows) < \ (16*GetMagickResourceLimit(ThreadResource))) ? 1 : \ GetMagickResourceLimit(ThreadResource) < MaxCacheThreads ? \ GetMagickResourceLimit(ThreadResource) : MaxCacheThreads) MagickBooleanType status; NexusInfo **magick_restrict cache_nexus, **magick_restrict clone_nexus; size_t length; ssize_t y; assert(cache_info != (CacheInfo *) NULL); assert(clone_info != (CacheInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); if (cache_info->type == PingCache) return(MagickTrue); if ((cache_info->columns == clone_info->columns) && (cache_info->rows == clone_info->rows) && (cache_info->active_index_channel == clone_info->active_index_channel)) { /* Identical pixel cache morphology. */ if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) && ((clone_info->type == MemoryCache) || (clone_info->type == MapCache))) { (void) memcpy(clone_info->pixels,cache_info->pixels, cache_info->columns*cache_info->rows*sizeof(*cache_info->pixels)); if ((cache_info->active_index_channel != MagickFalse) && (clone_info->active_index_channel != MagickFalse)) (void) memcpy(clone_info->indexes,cache_info->indexes, cache_info->columns*cache_info->rows* sizeof(*cache_info->indexes)); return(MagickTrue); } if ((cache_info->type == DiskCache) && (clone_info->type == DiskCache)) return(ClonePixelCacheOnDisk(cache_info,clone_info,exception)); } /* Mismatched pixel cache morphology. */ cache_nexus=AcquirePixelCacheNexus(MaxCacheThreads); clone_nexus=AcquirePixelCacheNexus(MaxCacheThreads); if ((cache_nexus == (NexusInfo **) NULL) || (clone_nexus == (NexusInfo **) NULL)) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); length=(size_t) MagickMin(cache_info->columns,clone_info->columns)* sizeof(*cache_info->pixels); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ cache_threads(cache_info,clone_info) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); PixelPacket *pixels; RectangleInfo region; if (status == MagickFalse) continue; if (y == (ssize_t) clone_info->rows) continue; region.width=cache_info->columns; region.height=1; region.x=0; region.y=y; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region,MagickTrue, cache_nexus[id],exception); if (pixels == (PixelPacket *) NULL) continue; status=ReadPixelCachePixels(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; region.width=clone_info->columns; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,&region,MagickTrue, clone_nexus[id],exception); if (pixels == (PixelPacket *) NULL) continue; (void) ResetMagickMemory(clone_nexus[id]->pixels,0,(size_t) clone_nexus[id]->length); (void) memcpy(clone_nexus[id]->pixels,cache_nexus[id]->pixels,length); status=WritePixelCachePixels(clone_info,clone_nexus[id],exception); } if ((cache_info->active_index_channel != MagickFalse) && (clone_info->active_index_channel != MagickFalse)) { /* Clone indexes. */ length=(size_t) MagickMin(cache_info->columns,clone_info->columns)* sizeof(*cache_info->indexes); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ cache_threads(cache_info,clone_info) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); PixelPacket *pixels; RectangleInfo region; if (status == MagickFalse) continue; if (y == (ssize_t) clone_info->rows) continue; region.width=cache_info->columns; region.height=1; region.x=0; region.y=y; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region,MagickTrue, cache_nexus[id],exception); if (pixels == (PixelPacket *) NULL) continue; status=ReadPixelCacheIndexes(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; region.width=clone_info->columns; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,&region,MagickTrue, clone_nexus[id],exception); if (pixels == (PixelPacket *) NULL) continue; (void) memcpy(clone_nexus[id]->indexes,cache_nexus[id]->indexes,length); status=WritePixelCacheIndexes(clone_info,clone_nexus[id],exception); } } cache_nexus=DestroyPixelCacheNexus(cache_nexus,MaxCacheThreads); clone_nexus=DestroyPixelCacheNexus(clone_nexus,MaxCacheThreads); if (cache_info->debug != MagickFalse) { char message[MaxTextExtent]; (void) FormatLocaleString(message,MaxTextExtent,"%s => %s", CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type), CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) clone_info->type)); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImagePixelCache() deallocates memory associated with the pixel cache. % % The format of the DestroyImagePixelCache() method is: % % void DestroyImagePixelCache(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void DestroyImagePixelCache(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->cache == (void *) NULL) return; image->cache=DestroyPixelCache(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImagePixels() deallocates memory associated with the pixel cache. % % The format of the DestroyImagePixels() method is: % % void DestroyImagePixels(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImagePixels(Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->methods.destroy_pixel_handler != (DestroyPixelHandler) NULL) { cache_info->methods.destroy_pixel_handler(image); return; } image->cache=DestroyPixelCache(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelCache() deallocates memory associated with the pixel cache. % % The format of the DestroyPixelCache() method is: % % Cache DestroyPixelCache(Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ static MagickBooleanType ClosePixelCacheOnDisk(CacheInfo *cache_info) { int status; status=(-1); if (cache_info->file != -1) { status=close(cache_info->file); cache_info->file=(-1); RelinquishMagickResource(FileResource,1); } return(status == -1 ? MagickFalse : MagickTrue); } static inline void RelinquishPixelCachePixels(CacheInfo *cache_info) { switch (cache_info->type) { case MemoryCache: { if (cache_info->mapped == MagickFalse) cache_info->pixels=(PixelPacket *) RelinquishAlignedMemory( cache_info->pixels); else { (void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length); cache_info->pixels=(PixelPacket *) NULL; } RelinquishMagickResource(MemoryResource,cache_info->length); break; } case MapCache: { (void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length); cache_info->pixels=(PixelPacket *) NULL; if (cache_info->mode != ReadMode) (void) RelinquishUniqueFileResource(cache_info->cache_filename); *cache_info->cache_filename='\0'; RelinquishMagickResource(MapResource,cache_info->length); } case DiskCache: { if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); if (cache_info->mode != ReadMode) (void) RelinquishUniqueFileResource(cache_info->cache_filename); *cache_info->cache_filename='\0'; RelinquishMagickResource(DiskResource,cache_info->length); break; } case DistributedCache: { *cache_info->cache_filename='\0'; (void) RelinquishDistributePixelCache((DistributeCacheInfo *) cache_info->server_info); break; } default: break; } cache_info->type=UndefinedCache; cache_info->mapped=MagickFalse; cache_info->indexes=(IndexPacket *) NULL; } MagickExport Cache DestroyPixelCache(Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count--; if (cache_info->reference_count != 0) { UnlockSemaphoreInfo(cache_info->semaphore); return((Cache) NULL); } UnlockSemaphoreInfo(cache_info->semaphore); if (cache_info->debug != MagickFalse) { char message[MaxTextExtent]; (void) FormatLocaleString(message,MaxTextExtent,"destroy %s", cache_info->filename); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } RelinquishPixelCachePixels(cache_info); if (cache_info->server_info != (DistributeCacheInfo *) NULL) cache_info->server_info=DestroyDistributeCacheInfo((DistributeCacheInfo *) cache_info->server_info); if (cache_info->nexus_info != (NexusInfo **) NULL) cache_info->nexus_info=DestroyPixelCacheNexus(cache_info->nexus_info, cache_info->number_threads); if (cache_info->random_info != (RandomInfo *) NULL) cache_info->random_info=DestroyRandomInfo(cache_info->random_info); if (cache_info->file_semaphore != (SemaphoreInfo *) NULL) DestroySemaphoreInfo(&cache_info->file_semaphore); if (cache_info->semaphore != (SemaphoreInfo *) NULL) DestroySemaphoreInfo(&cache_info->semaphore); cache_info->signature=(~MagickSignature); cache_info=(CacheInfo *) RelinquishMagickMemory(cache_info); cache=(Cache) NULL; return(cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelCacheNexus() destroys a pixel cache nexus. % % The format of the DestroyPixelCacheNexus() method is: % % NexusInfo **DestroyPixelCacheNexus(NexusInfo *nexus_info, % const size_t number_threads) % % A description of each parameter follows: % % o nexus_info: the nexus to destroy. % % o number_threads: the number of nexus threads. % */ static inline void RelinquishCacheNexusPixels(NexusInfo *nexus_info) { if (nexus_info->mapped == MagickFalse) (void) RelinquishAlignedMemory(nexus_info->cache); else (void) UnmapBlob(nexus_info->cache,(size_t) nexus_info->length); nexus_info->cache=(PixelPacket *) NULL; nexus_info->pixels=(PixelPacket *) NULL; nexus_info->indexes=(IndexPacket *) NULL; nexus_info->length=0; nexus_info->mapped=MagickFalse; } MagickExport NexusInfo **DestroyPixelCacheNexus(NexusInfo **nexus_info, const size_t number_threads) { register ssize_t i; assert(nexus_info != (NexusInfo **) NULL); for (i=0; i < (ssize_t) number_threads; i++) { if (nexus_info[i]->cache != (PixelPacket *) NULL) RelinquishCacheNexusPixels(nexus_info[i]); nexus_info[i]->signature=(~MagickSignature); } nexus_info[0]=(NexusInfo *) RelinquishMagickMemory(nexus_info[0]); nexus_info=(NexusInfo **) RelinquishAlignedMemory(nexus_info); return(nexus_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c I n d e x e s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticIndexesFromCache() returns the indexes associated with the last % call to QueueAuthenticPixelsCache() or GetAuthenticPixelsCache(). % % The format of the GetAuthenticIndexesFromCache() method is: % % IndexPacket *GetAuthenticIndexesFromCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static IndexPacket *GetAuthenticIndexesFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->indexes); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c I n d e x Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticIndexQueue() returns the authentic black channel or the colormap % indexes associated with the last call to QueueAuthenticPixels() or % GetVirtualPixels(). NULL is returned if the black channel or colormap % indexes are not available. % % The format of the GetAuthenticIndexQueue() method is: % % IndexPacket *GetAuthenticIndexQueue(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport IndexPacket *GetAuthenticIndexQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->methods.get_authentic_indexes_from_handler != (GetAuthenticIndexesFromHandler) NULL) return(cache_info->methods.get_authentic_indexes_from_handler(image)); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->indexes); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelCacheNexus() gets authentic pixels from the in-memory or % disk pixel cache as defined by the geometry parameters. A pointer to the % pixels is returned if the pixels are transferred, otherwise a NULL is % returned. % % The format of the GetAuthenticPixelCacheNexus() method is: % % PixelPacket *GetAuthenticPixelCacheNexus(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to return. % % o exception: return any errors or warnings in this structure. % */ MagickExport PixelPacket *GetAuthenticPixelCacheNexus(Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; PixelPacket *magick_restrict pixels; /* Transfer pixels from the cache. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickTrue, nexus_info,exception); if (pixels == (PixelPacket *) NULL) return((PixelPacket *) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (nexus_info->authentic_pixel_cache != MagickFalse) return(pixels); if (ReadPixelCachePixels(cache_info,nexus_info,exception) == MagickFalse) return((PixelPacket *) NULL); if (cache_info->active_index_channel != MagickFalse) if (ReadPixelCacheIndexes(cache_info,nexus_info,exception) == MagickFalse) return((PixelPacket *) NULL); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelsFromCache() returns the pixels associated with the last % call to the QueueAuthenticPixelsCache() or GetAuthenticPixelsCache() methods. % % The format of the GetAuthenticPixelsFromCache() method is: % % PixelPacket *GetAuthenticPixelsFromCache(const Image image) % % A description of each parameter follows: % % o image: the image. % */ static PixelPacket *GetAuthenticPixelsFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c P i x e l Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelQueue() returns the authentic pixels associated with the % last call to QueueAuthenticPixels() or GetAuthenticPixels(). % % The format of the GetAuthenticPixelQueue() method is: % % PixelPacket *GetAuthenticPixelQueue(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport PixelPacket *GetAuthenticPixelQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->methods.get_authentic_pixels_from_handler != (GetAuthenticPixelsFromHandler) NULL) return(cache_info->methods.get_authentic_pixels_from_handler(image)); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixels() obtains a pixel region for read/write access. If the % region is successfully accessed, a pointer to a PixelPacket array % representing the region is returned, otherwise NULL is returned. % % The returned pointer may point to a temporary working copy of the pixels % or it may point to the original pixels in memory. Performance is maximized % if the selected region is part of one row, or one or more full rows, since % then there is opportunity to access the pixels in-place (without a copy) % if the image is in memory, or in a memory-mapped file. The returned pointer % must *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % PixelPacket. If the image type is CMYK or if the storage class is % PseduoClass, call GetAuthenticIndexQueue() after invoking % GetAuthenticPixels() to obtain the black color component or colormap indexes % (of type IndexPacket) corresponding to the region. Once the PixelPacket % (and/or IndexPacket) array has been updated, the changes must be saved back % to the underlying image using SyncAuthenticPixels() or they may be lost. % % The format of the GetAuthenticPixels() method is: % % PixelPacket *GetAuthenticPixels(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport PixelPacket *GetAuthenticPixels(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->methods.get_authentic_pixels_handler != (GetAuthenticPixelsHandler) NULL) return(cache_info->methods.get_authentic_pixels_handler(image,x,y,columns, rows,exception)); assert(id < (int) cache_info->number_threads); return(GetAuthenticPixelCacheNexus(image,x,y,columns,rows, cache_info->nexus_info[id],exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l s C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelsCache() gets pixels from the in-memory or disk pixel cache % as defined by the geometry parameters. A pointer to the pixels is returned % if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetAuthenticPixelsCache() method is: % % PixelPacket *GetAuthenticPixelsCache(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static PixelPacket *GetAuthenticPixelsCache(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return((PixelPacket *) NULL); assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); return(GetAuthenticPixelCacheNexus(image,x,y,columns,rows, cache_info->nexus_info[id],exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageExtent() returns the extent of the pixels associated with the % last call to QueueAuthenticPixels() or GetAuthenticPixels(). % % The format of the GetImageExtent() method is: % % MagickSizeType GetImageExtent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickSizeType GetImageExtent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); return(GetPixelCacheNexusExtent(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixelCache() ensures that there is only a single reference to the % pixel cache to be modified, updating the provided cache pointer to point to % a clone of the original pixel cache if necessary. % % The format of the GetImagePixelCache method is: % % Cache GetImagePixelCache(Image *image,const MagickBooleanType clone, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o clone: any value other than MagickFalse clones the cache pixels. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType ValidatePixelCacheMorphology( const Image *magick_restrict image) { CacheInfo *magick_restrict cache_info; /* Does the image match the pixel cache morphology? */ cache_info=(CacheInfo *) image->cache; if ((image->storage_class != cache_info->storage_class) || (image->colorspace != cache_info->colorspace) || (image->channels != cache_info->channels) || (image->columns != cache_info->columns) || (image->rows != cache_info->rows) || (cache_info->nexus_info == (NexusInfo **) NULL)) return(MagickFalse); return(MagickTrue); } static Cache GetImagePixelCache(Image *image,const MagickBooleanType clone, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickBooleanType destroy, status; static MagickSizeType cpu_throttle = MagickResourceInfinity, cycles = 0, time_limit = 0; static time_t cache_timestamp = 0; status=MagickTrue; if (cpu_throttle == MagickResourceInfinity) cpu_throttle=GetMagickResourceLimit(ThrottleResource); if ((cpu_throttle != 0) && ((cycles++ % 32) == 0)) MagickDelay(cpu_throttle); if (time_limit == 0) { /* Set the expire time in seconds. */ time_limit=GetMagickResourceLimit(TimeResource); cache_timestamp=time((time_t *) NULL); } if ((time_limit != MagickResourceInfinity) && ((MagickSizeType) (time((time_t *) NULL)-cache_timestamp) >= time_limit)) { #if defined(ECANCELED) errno=ECANCELED; #endif ThrowFatalException(ResourceLimitFatalError,"TimeLimitExceeded"); } LockSemaphoreInfo(image->semaphore); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; destroy=MagickFalse; if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode)) { LockSemaphoreInfo(cache_info->semaphore); if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode)) { CacheInfo *clone_info; Image clone_image; /* Clone pixel cache. */ clone_image=(*image); clone_image.semaphore=AllocateSemaphoreInfo(); clone_image.reference_count=1; clone_image.cache=ClonePixelCache(cache_info); clone_info=(CacheInfo *) clone_image.cache; status=OpenPixelCache(&clone_image,IOMode,exception); if (status != MagickFalse) { if (clone != MagickFalse) status=ClonePixelCacheRepository(clone_info,cache_info, exception); if (status != MagickFalse) { if (cache_info->reference_count == 1) cache_info->nexus_info=(NexusInfo **) NULL; destroy=MagickTrue; image->cache=clone_image.cache; } } DestroySemaphoreInfo(&clone_image.semaphore); } UnlockSemaphoreInfo(cache_info->semaphore); } if (destroy != MagickFalse) cache_info=(CacheInfo *) DestroyPixelCache(cache_info); if (status != MagickFalse) { /* Ensure the image matches the pixel cache morphology. */ image->type=UndefinedType; if (ValidatePixelCacheMorphology(image) == MagickFalse) { status=OpenPixelCache(image,IOMode,exception); cache_info=(CacheInfo *) image->cache; if (cache_info->type == DiskCache) (void) ClosePixelCacheOnDisk(cache_info); } } UnlockSemaphoreInfo(image->semaphore); if (status == MagickFalse) return((Cache) NULL); return(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e P i x e l C a c h e T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixelCacheType() returns the pixel cache type: UndefinedCache, % DiskCache, MapCache, MemoryCache, or PingCache. % % The format of the GetImagePixelCacheType() method is: % % CacheType GetImagePixelCacheType(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport CacheType GetPixelCacheType(const Image *image) { return(GetImagePixelCacheType(image)); } MagickExport CacheType GetImagePixelCacheType(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); return(cache_info->type); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e A u t h e n t i c P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneAuthenticPixel() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. % % The format of the GetOneAuthenticPixel() method is: % % MagickBooleanType GetOneAuthenticPixel(const Image image,const ssize_t x, % const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneAuthenticPixel(Image *image, const ssize_t x,const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; PixelPacket *magick_restrict pixels; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); *pixel=image->background_color; if (cache_info->methods.get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) return(cache_info->methods.get_one_authentic_pixel_from_handler(image,x,y, pixel,exception)); pixels=GetAuthenticPixelsCache(image,x,y,1UL,1UL,exception); if (pixels == (PixelPacket *) NULL) return(MagickFalse); *pixel=(*pixels); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O n e A u t h e n t i c P i x e l F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneAuthenticPixelFromCache() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. % % The format of the GetOneAuthenticPixelFromCache() method is: % % MagickBooleanType GetOneAuthenticPixelFromCache(const Image image, % const ssize_t x,const ssize_t y,PixelPacket *pixel, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetOneAuthenticPixelFromCache(Image *image, const ssize_t x,const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); PixelPacket *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); *pixel=image->background_color; assert(id < (int) cache_info->number_threads); pixels=GetAuthenticPixelCacheNexus(image,x,y,1UL,1UL, cache_info->nexus_info[id],exception); if (pixels == (PixelPacket *) NULL) return(MagickFalse); *pixel=(*pixels); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l M a g i c k P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualMagickPixel() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. If % you plan to modify the pixel, use GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualMagickPixel() method is: % % MagickBooleanType GetOneVirtualMagickPixel(const Image image, % const ssize_t x,const ssize_t y,MagickPixelPacket *pixel, % ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: these values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualMagickPixel(const Image *image, const ssize_t x,const ssize_t y,MagickPixelPacket *pixel, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); pixels=GetVirtualPixelsFromNexus(image,GetPixelCacheVirtualMethod(image),x,y, 1UL,1UL,cache_info->nexus_info[id],exception); GetMagickPixelPacket(image,pixel); if (pixels == (const PixelPacket *) NULL) return(MagickFalse); indexes=GetVirtualIndexesFromNexus(cache_info,cache_info->nexus_info[id]); SetMagickPixelPacket(image,pixels,indexes,pixel); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l M e t h o d P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualMethodPixel() returns a single pixel at the specified (x,y) % location as defined by specified pixel method. The image background color % is returned if an error occurs. If you plan to modify the pixel, use % GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualMethodPixel() method is: % % MagickBooleanType GetOneVirtualMethodPixel(const Image image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,Pixelpacket *pixel,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualMethodPixel(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, PixelPacket *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const PixelPacket *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); *pixel=image->background_color; if (cache_info->methods.get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) return(cache_info->methods.get_one_virtual_pixel_from_handler(image, virtual_pixel_method,x,y,pixel,exception)); assert(id < (int) cache_info->number_threads); pixels=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x,y,1UL,1UL, cache_info->nexus_info[id],exception); if (pixels == (const PixelPacket *) NULL) return(MagickFalse); *pixel=(*pixels); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixel() returns a single virtual pixel at the specified % (x,y) location. The image background color is returned if an error occurs. % If you plan to modify the pixel, use GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualPixel() method is: % % MagickBooleanType GetOneVirtualPixel(const Image image,const ssize_t x, % const ssize_t y,PixelPacket *pixel,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualPixel(const Image *image, const ssize_t x,const ssize_t y,PixelPacket *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const PixelPacket *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); *pixel=image->background_color; if (cache_info->methods.get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) return(cache_info->methods.get_one_virtual_pixel_from_handler(image, GetPixelCacheVirtualMethod(image),x,y,pixel,exception)); assert(id < (int) cache_info->number_threads); pixels=GetVirtualPixelsFromNexus(image,GetPixelCacheVirtualMethod(image),x,y, 1UL,1UL,cache_info->nexus_info[id],exception); if (pixels == (const PixelPacket *) NULL) return(MagickFalse); *pixel=(*pixels); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O n e V i r t u a l P i x e l F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixelFromCache() returns a single virtual pixel at the % specified (x,y) location. The image background color is returned if an % error occurs. % % The format of the GetOneVirtualPixelFromCache() method is: % % MagickBooleanType GetOneVirtualPixelFromCache(const Image image, % const VirtualPixelPacket method,const ssize_t x,const ssize_t y, % PixelPacket *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetOneVirtualPixelFromCache(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, PixelPacket *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const PixelPacket *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); *pixel=image->background_color; pixels=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x,y,1UL,1UL, cache_info->nexus_info[id],exception); if (pixels == (const PixelPacket *) NULL) return(MagickFalse); *pixel=(*pixels); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e C h a n n e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheChannels() returns the number of pixel channels associated % with this instance of the pixel cache. % % The format of the GetPixelCacheChannels() method is: % % size_t GetPixelCacheChannels(Cache cache) % % A description of each parameter follows: % % o type: GetPixelCacheChannels returns DirectClass or PseudoClass. % % o cache: the pixel cache. % */ MagickExport size_t GetPixelCacheChannels(const Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->channels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e C o l o r s p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheColorspace() returns the class type of the pixel cache. % % The format of the GetPixelCacheColorspace() method is: % % Colorspace GetPixelCacheColorspace(Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ MagickExport ColorspaceType GetPixelCacheColorspace(const Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->colorspace); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheMethods() initializes the CacheMethods structure. % % The format of the GetPixelCacheMethods() method is: % % void GetPixelCacheMethods(CacheMethods *cache_methods) % % A description of each parameter follows: % % o cache_methods: Specifies a pointer to a CacheMethods structure. % */ MagickExport void GetPixelCacheMethods(CacheMethods *cache_methods) { assert(cache_methods != (CacheMethods *) NULL); (void) ResetMagickMemory(cache_methods,0,sizeof(*cache_methods)); cache_methods->get_virtual_pixel_handler=GetVirtualPixelCache; cache_methods->get_virtual_pixels_handler=GetVirtualPixelsCache; cache_methods->get_virtual_indexes_from_handler=GetVirtualIndexesFromCache; cache_methods->get_one_virtual_pixel_from_handler=GetOneVirtualPixelFromCache; cache_methods->get_authentic_pixels_handler=GetAuthenticPixelsCache; cache_methods->get_authentic_indexes_from_handler= GetAuthenticIndexesFromCache; cache_methods->get_authentic_pixels_from_handler=GetAuthenticPixelsFromCache; cache_methods->get_one_authentic_pixel_from_handler= GetOneAuthenticPixelFromCache; cache_methods->queue_authentic_pixels_handler=QueueAuthenticPixelsCache; cache_methods->sync_authentic_pixels_handler=SyncAuthenticPixelsCache; cache_methods->destroy_pixel_handler=DestroyImagePixelCache; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e N e x u s E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheNexusExtent() returns the extent of the pixels associated with % the last call to SetPixelCacheNexusPixels() or GetPixelCacheNexusPixels(). % % The format of the GetPixelCacheNexusExtent() method is: % % MagickSizeType GetPixelCacheNexusExtent(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o nexus_info: the nexus info. % */ MagickExport MagickSizeType GetPixelCacheNexusExtent(const Cache cache, NexusInfo *nexus_info) { CacheInfo *magick_restrict cache_info; MagickSizeType extent; assert(cache != NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickSignature); extent=(MagickSizeType) nexus_info->region.width*nexus_info->region.height; if (extent == 0) return((MagickSizeType) cache_info->columns*cache_info->rows); return(extent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCachePixels() returns the pixels associated with the specified image. % % The format of the GetPixelCachePixels() method is: % % void *GetPixelCachePixels(Image *image,MagickSizeType *length, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o length: the pixel cache length. % % o exception: return any errors or warnings in this structure. % */ MagickExport void *GetPixelCachePixels(Image *image,MagickSizeType *length, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); assert(length != (MagickSizeType *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); (void) exception; *length=0; if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache)) return((void *) NULL); *length=cache_info->length; return((void *) cache_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e S t o r a g e C l a s s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheStorageClass() returns the class type of the pixel cache. % % The format of the GetPixelCacheStorageClass() method is: % % ClassType GetPixelCacheStorageClass(Cache cache) % % A description of each parameter follows: % % o type: GetPixelCacheStorageClass returns DirectClass or PseudoClass. % % o cache: the pixel cache. % */ MagickExport ClassType GetPixelCacheStorageClass(const Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->storage_class); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e T i l e S i z e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheTileSize() returns the pixel cache tile size. % % The format of the GetPixelCacheTileSize() method is: % % void GetPixelCacheTileSize(const Image *image,size_t *width, % size_t *height) % % A description of each parameter follows: % % o image: the image. % % o width: the optimize cache tile width in pixels. % % o height: the optimize cache tile height in pixels. % */ MagickExport void GetPixelCacheTileSize(const Image *image,size_t *width, size_t *height) { assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); *width=2048UL/sizeof(PixelPacket); if (GetImagePixelCacheType(image) == DiskCache) *width=8192UL/sizeof(PixelPacket); *height=(*width); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e V i r t u a l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheVirtualMethod() gets the "virtual pixels" method for the % pixel cache. A virtual pixel is any pixel access that is outside the % boundaries of the image cache. % % The format of the GetPixelCacheVirtualMethod() method is: % % VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); return(cache_info->virtual_pixel_method); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l I n d e x e s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualIndexesFromCache() returns the indexes associated with the last % call to QueueAuthenticPixelsCache() or GetVirtualPixelCache(). % % The format of the GetVirtualIndexesFromCache() method is: % % IndexPacket *GetVirtualIndexesFromCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static const IndexPacket *GetVirtualIndexesFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); return(GetVirtualIndexesFromNexus(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l I n d e x e s F r o m N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualIndexesFromNexus() returns the indexes associated with the % specified cache nexus. % % The format of the GetVirtualIndexesFromNexus() method is: % % const IndexPacket *GetVirtualIndexesFromNexus(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o cache: the pixel cache. % % o nexus_info: the cache nexus to return the colormap indexes. % */ MagickExport const IndexPacket *GetVirtualIndexesFromNexus(const Cache cache, NexusInfo *nexus_info) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickSignature); if (cache_info->storage_class == UndefinedClass) return((IndexPacket *) NULL); return(nexus_info->indexes); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l I n d e x Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualIndexQueue() returns the virtual black channel or the % colormap indexes associated with the last call to QueueAuthenticPixels() or % GetVirtualPixels(). NULL is returned if the black channel or colormap % indexes are not available. % % The format of the GetVirtualIndexQueue() method is: % % const IndexPacket *GetVirtualIndexQueue(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const IndexPacket *GetVirtualIndexQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->methods.get_virtual_indexes_from_handler != (GetVirtualIndexesFromHandler) NULL) return(cache_info->methods.get_virtual_indexes_from_handler(image)); assert(id < (int) cache_info->number_threads); return(GetVirtualIndexesFromNexus(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s F r o m N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsFromNexus() gets virtual pixels from the in-memory or disk % pixel cache as defined by the geometry parameters. A pointer to the pixels % is returned if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetVirtualPixelsFromNexus() method is: % % PixelPacket *GetVirtualPixelsFromNexus(const Image *image, % const VirtualPixelMethod method,const ssize_t x,const ssize_t y, % const size_t columns,const size_t rows,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to acquire. % % o exception: return any errors or warnings in this structure. % */ static ssize_t DitherMatrix[64] = { 0, 48, 12, 60, 3, 51, 15, 63, 32, 16, 44, 28, 35, 19, 47, 31, 8, 56, 4, 52, 11, 59, 7, 55, 40, 24, 36, 20, 43, 27, 39, 23, 2, 50, 14, 62, 1, 49, 13, 61, 34, 18, 46, 30, 33, 17, 45, 29, 10, 58, 6, 54, 9, 57, 5, 53, 42, 26, 38, 22, 41, 25, 37, 21 }; static inline ssize_t DitherX(const ssize_t x,const size_t columns) { ssize_t index; index=x+DitherMatrix[x & 0x07]-32L; if (index < 0L) return(0L); if (index >= (ssize_t) columns) return((ssize_t) columns-1L); return(index); } static inline ssize_t DitherY(const ssize_t y,const size_t rows) { ssize_t index; index=y+DitherMatrix[y & 0x07]-32L; if (index < 0L) return(0L); if (index >= (ssize_t) rows) return((ssize_t) rows-1L); return(index); } static inline ssize_t EdgeX(const ssize_t x,const size_t columns) { if (x < 0L) return(0L); if (x >= (ssize_t) columns) return((ssize_t) (columns-1)); return(x); } static inline ssize_t EdgeY(const ssize_t y,const size_t rows) { if (y < 0L) return(0L); if (y >= (ssize_t) rows) return((ssize_t) (rows-1)); return(y); } static inline ssize_t RandomX(RandomInfo *random_info,const size_t columns) { return((ssize_t) (columns*GetPseudoRandomValue(random_info))); } static inline ssize_t RandomY(RandomInfo *random_info,const size_t rows) { return((ssize_t) (rows*GetPseudoRandomValue(random_info))); } /* VirtualPixelModulo() computes the remainder of dividing offset by extent. It returns not only the quotient (tile the offset falls in) but also the positive remainer within that tile such that 0 <= remainder < extent. This method is essentially a ldiv() using a floored modulo division rather than the normal default truncated modulo division. */ static inline MagickModulo VirtualPixelModulo(const ssize_t offset, const size_t extent) { MagickModulo modulo; modulo.quotient=offset/(ssize_t) extent; if (offset < 0L) modulo.quotient--; modulo.remainder=offset-modulo.quotient*(ssize_t) extent; return(modulo); } MagickExport const PixelPacket *GetVirtualPixelsFromNexus(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; IndexPacket virtual_index; MagickOffsetType offset; MagickSizeType length, number_pixels; NexusInfo **magick_restrict virtual_nexus; PixelPacket *magick_restrict pixels, virtual_pixel; RectangleInfo region; register const IndexPacket *magick_restrict virtual_indexes; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t u, v; /* Acquire pixels. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->type == UndefinedCache) return((const PixelPacket *) NULL); region.x=x; region.y=y; region.width=columns; region.height=rows; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region, (image->clip_mask != (Image *) NULL) || (image->mask != (Image *) NULL) ? MagickTrue : MagickFalse,nexus_info,exception); if (pixels == (PixelPacket *) NULL) return((const PixelPacket *) NULL); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) (nexus_info->region.height-1L)*cache_info->columns+ nexus_info->region.width-1L; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; if ((offset >= 0) && (((MagickSizeType) offset+length) < number_pixels)) if ((x >= 0) && ((ssize_t) (x+columns) <= (ssize_t) cache_info->columns) && (y >= 0) && ((ssize_t) (y+rows) <= (ssize_t) cache_info->rows)) { MagickBooleanType status; /* Pixel request is inside cache extents. */ if (nexus_info->authentic_pixel_cache != MagickFalse) return(pixels); status=ReadPixelCachePixels(cache_info,nexus_info,exception); if (status == MagickFalse) return((const PixelPacket *) NULL); if ((cache_info->storage_class == PseudoClass) || (cache_info->colorspace == CMYKColorspace)) { status=ReadPixelCacheIndexes(cache_info,nexus_info,exception); if (status == MagickFalse) return((const PixelPacket *) NULL); } return(pixels); } /* Pixel request is outside cache extents. */ q=pixels; indexes=nexus_info->indexes; virtual_nexus=AcquirePixelCacheNexus(1); if (virtual_nexus == (NexusInfo **) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "UnableToGetCacheNexus","`%s'",image->filename); return((const PixelPacket *) NULL); } switch (virtual_pixel_method) { case BlackVirtualPixelMethod: { SetPixelRed(&virtual_pixel,0); SetPixelGreen(&virtual_pixel,0); SetPixelBlue(&virtual_pixel,0); SetPixelOpacity(&virtual_pixel,OpaqueOpacity); break; } case GrayVirtualPixelMethod: { SetPixelRed(&virtual_pixel,QuantumRange/2); SetPixelGreen(&virtual_pixel,QuantumRange/2); SetPixelBlue(&virtual_pixel,QuantumRange/2); SetPixelOpacity(&virtual_pixel,OpaqueOpacity); break; } case TransparentVirtualPixelMethod: { SetPixelRed(&virtual_pixel,0); SetPixelGreen(&virtual_pixel,0); SetPixelBlue(&virtual_pixel,0); SetPixelOpacity(&virtual_pixel,TransparentOpacity); break; } case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: { SetPixelRed(&virtual_pixel,QuantumRange); SetPixelGreen(&virtual_pixel,QuantumRange); SetPixelBlue(&virtual_pixel,QuantumRange); SetPixelOpacity(&virtual_pixel,OpaqueOpacity); break; } default: { virtual_pixel=image->background_color; break; } } virtual_index=0; for (v=0; v < (ssize_t) rows; v++) { ssize_t y_offset; y_offset=y+v; if ((virtual_pixel_method == EdgeVirtualPixelMethod) || (virtual_pixel_method == UndefinedVirtualPixelMethod)) y_offset=EdgeY(y_offset,cache_info->rows); for (u=0; u < (ssize_t) columns; u+=length) { ssize_t x_offset; x_offset=x+u; length=(MagickSizeType) MagickMin(cache_info->columns-x_offset,columns-u); if (((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) || ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) || (length == 0)) { MagickModulo x_modulo, y_modulo; /* Transfer a single pixel. */ length=(MagickSizeType) 1; switch (virtual_pixel_method) { case BackgroundVirtualPixelMethod: case ConstantVirtualPixelMethod: case BlackVirtualPixelMethod: case GrayVirtualPixelMethod: case TransparentVirtualPixelMethod: case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: { p=(&virtual_pixel); virtual_indexes=(&virtual_index); break; } case EdgeVirtualPixelMethod: default: { p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, EdgeX(x_offset,cache_info->columns), EdgeY(y_offset,cache_info->rows),1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case RandomVirtualPixelMethod: { if (cache_info->random_info == (RandomInfo *) NULL) cache_info->random_info=AcquireRandomInfo(); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, RandomX(cache_info->random_info,cache_info->columns), RandomY(cache_info->random_info,cache_info->rows),1UL,1UL, *virtual_nexus,exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case DitherVirtualPixelMethod: { p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, DitherX(x_offset,cache_info->columns), DitherY(y_offset,cache_info->rows),1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case TileVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case MirrorVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); if ((x_modulo.quotient & 0x01) == 1L) x_modulo.remainder=(ssize_t) cache_info->columns- x_modulo.remainder-1L; y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); if ((y_modulo.quotient & 0x01) == 1L) y_modulo.remainder=(ssize_t) cache_info->rows- y_modulo.remainder-1L; p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case CheckerTileVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); if (((x_modulo.quotient ^ y_modulo.quotient) & 0x01) != 0L) { p=(&virtual_pixel); virtual_indexes=(&virtual_index); break; } p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case HorizontalTileVirtualPixelMethod: { if ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) { p=(&virtual_pixel); virtual_indexes=(&virtual_index); break; } x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case VerticalTileVirtualPixelMethod: { if ((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) { p=(&virtual_pixel); virtual_indexes=(&virtual_index); break; } x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case HorizontalTileEdgeVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, x_modulo.remainder,EdgeY(y_offset,cache_info->rows),1UL,1UL, *virtual_nexus,exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } case VerticalTileEdgeVirtualPixelMethod: { y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelsFromNexus(image,virtual_pixel_method, EdgeX(x_offset,cache_info->columns),y_modulo.remainder,1UL,1UL, *virtual_nexus,exception); virtual_indexes=GetVirtualIndexesFromNexus(cache_info, *virtual_nexus); break; } } if (p == (const PixelPacket *) NULL) break; *q++=(*p); if ((indexes != (IndexPacket *) NULL) && (virtual_indexes != (const IndexPacket *) NULL)) *indexes++=(*virtual_indexes); continue; } /* Transfer a run of pixels. */ p=GetVirtualPixelsFromNexus(image,virtual_pixel_method,x_offset,y_offset, (size_t) length,1UL,*virtual_nexus,exception); if (p == (const PixelPacket *) NULL) break; virtual_indexes=GetVirtualIndexesFromNexus(cache_info,*virtual_nexus); (void) memcpy(q,p,(size_t) length*sizeof(*p)); q+=length; if ((indexes != (IndexPacket *) NULL) && (virtual_indexes != (const IndexPacket *) NULL)) { (void) memcpy(indexes,virtual_indexes,(size_t) length* sizeof(*virtual_indexes)); indexes+=length; } } } virtual_nexus=DestroyPixelCacheNexus(virtual_nexus,1); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelCache() get virtual pixels from the in-memory or disk pixel % cache as defined by the geometry parameters. A pointer to the pixels % is returned if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetVirtualPixelCache() method is: % % const PixelPacket *GetVirtualPixelCache(const Image *image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static const PixelPacket *GetVirtualPixelCache(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsFromNexus(image,virtual_pixel_method,x,y,columns,rows, cache_info->nexus_info[id],exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l P i x e l Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelQueue() returns the virtual pixels associated with the % last call to QueueAuthenticPixels() or GetVirtualPixels(). % % The format of the GetVirtualPixelQueue() method is: % % const PixelPacket *GetVirtualPixelQueue(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const PixelPacket *GetVirtualPixelQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->methods.get_virtual_pixels_handler != (GetVirtualPixelsHandler) NULL) return(cache_info->methods.get_virtual_pixels_handler(image)); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsNexus(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixels() returns an immutable pixel region. If the % region is successfully accessed, a pointer to it is returned, otherwise % NULL is returned. The returned pointer may point to a temporary working % copy of the pixels or it may point to the original pixels in memory. % Performance is maximized if the selected region is part of one row, or one % or more full rows, since there is opportunity to access the pixels in-place % (without a copy) if the image is in memory, or in a memory-mapped file. The % returned pointer must *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % PixelPacket. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticIndexQueue() after invoking GetAuthenticPixels() to access % the black color component or to obtain the colormap indexes (of type % IndexPacket) corresponding to the region. % % If you plan to modify the pixels, use GetAuthenticPixels() instead. % % Note, the GetVirtualPixels() and GetAuthenticPixels() methods are not thread- % safe. In a threaded environment, use GetCacheViewVirtualPixels() or % GetCacheViewAuthenticPixels() instead. % % The format of the GetVirtualPixels() method is: % % const PixelPacket *GetVirtualPixels(const Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport const PixelPacket *GetVirtualPixels(const Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->methods.get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL) return(cache_info->methods.get_virtual_pixel_handler(image, GetPixelCacheVirtualMethod(image),x,y,columns,rows,exception)); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsFromNexus(image,GetPixelCacheVirtualMethod(image),x,y, columns,rows,cache_info->nexus_info[id],exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsCache() returns the pixels associated with the last call % to QueueAuthenticPixelsCache() or GetVirtualPixelCache(). % % The format of the GetVirtualPixelsCache() method is: % % PixelPacket *GetVirtualPixelsCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static const PixelPacket *GetVirtualPixelsCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsNexus(image->cache,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsNexus() returns the pixels associated with the specified % cache nexus. % % The format of the GetVirtualPixelsNexus() method is: % % const IndexPacket *GetVirtualPixelsNexus(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o cache: the pixel cache. % % o nexus_info: the cache nexus to return the colormap pixels. % */ MagickExport const PixelPacket *GetVirtualPixelsNexus(const Cache cache, NexusInfo *nexus_info) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickSignature); if (cache_info->storage_class == UndefinedClass) return((PixelPacket *) NULL); return((const PixelPacket *) nexus_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + M a s k P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MaskPixelCacheNexus() masks the cache nexus as defined by the image mask. % The method returns MagickTrue if the pixel region is masked, otherwise % MagickFalse. % % The format of the MaskPixelCacheNexus() method is: % % MagickBooleanType MaskPixelCacheNexus(Image *image, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to clip. % % o exception: return any errors or warnings in this structure. % */ static inline void MagickPixelCompositeMask(const MagickPixelPacket *p, const MagickRealType alpha,const MagickPixelPacket *q, const MagickRealType beta,MagickPixelPacket *composite) { double gamma; if (alpha == TransparentOpacity) { *composite=(*q); return; } gamma=1.0-QuantumScale*QuantumScale*alpha*beta; gamma=PerceptibleReciprocal(gamma); composite->red=gamma*MagickOver_(p->red,alpha,q->red,beta); composite->green=gamma*MagickOver_(p->green,alpha,q->green,beta); composite->blue=gamma*MagickOver_(p->blue,alpha,q->blue,beta); if ((p->colorspace == CMYKColorspace) && (q->colorspace == CMYKColorspace)) composite->index=gamma*MagickOver_(p->index,alpha,q->index,beta); } static MagickBooleanType MaskPixelCacheNexus(Image *image,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickPixelPacket alpha, beta; MagickSizeType number_pixels; NexusInfo **magick_restrict clip_nexus, **magick_restrict image_nexus; register const PixelPacket *magick_restrict r; register IndexPacket *magick_restrict nexus_indexes, *magick_restrict indexes; register PixelPacket *magick_restrict p, *magick_restrict q; register ssize_t i; /* Apply clip mask. */ if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->mask == (Image *) NULL) || (image->storage_class == PseudoClass)) return(MagickTrue); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return(MagickFalse); image_nexus=AcquirePixelCacheNexus(1); clip_nexus=AcquirePixelCacheNexus(1); if ((image_nexus == (NexusInfo **) NULL) || (clip_nexus == (NexusInfo **) NULL)) ThrowBinaryException(CacheError,"UnableToGetCacheNexus",image->filename); p=GetAuthenticPixelCacheNexus(image,nexus_info->region.x, nexus_info->region.y,nexus_info->region.width,nexus_info->region.height, image_nexus[0],exception); indexes=image_nexus[0]->indexes; q=nexus_info->pixels; nexus_indexes=nexus_info->indexes; r=GetVirtualPixelsFromNexus(image->mask,MaskVirtualPixelMethod, nexus_info->region.x,nexus_info->region.y,nexus_info->region.width, nexus_info->region.height,clip_nexus[0],&image->exception); GetMagickPixelPacket(image,&alpha); GetMagickPixelPacket(image,&beta); number_pixels=(MagickSizeType) nexus_info->region.width* nexus_info->region.height; for (i=0; i < (ssize_t) number_pixels; i++) { if ((p == (PixelPacket *) NULL) || (r == (const PixelPacket *) NULL)) break; SetMagickPixelPacket(image,p,indexes+i,&alpha); SetMagickPixelPacket(image,q,nexus_indexes+i,&beta); MagickPixelCompositeMask(&beta,GetPixelIntensity(image,r),&alpha, alpha.opacity,&beta); SetPixelRed(q,ClampToQuantum(beta.red)); SetPixelGreen(q,ClampToQuantum(beta.green)); SetPixelBlue(q,ClampToQuantum(beta.blue)); SetPixelOpacity(q,ClampToQuantum(beta.opacity)); if (cache_info->active_index_channel != MagickFalse) SetPixelIndex(nexus_indexes+i,GetPixelIndex(indexes+i)); p++; q++; r++; } clip_nexus=DestroyPixelCacheNexus(clip_nexus,1); image_nexus=DestroyPixelCacheNexus(image_nexus,1); if (i < (ssize_t) number_pixels) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p e n P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpenPixelCache() allocates the pixel cache. This includes defining the cache % dimensions, allocating space for the image pixels and optionally the % colormap indexes, and memory mapping the cache if it is disk based. The % cache nexus array is initialized as well. % % The format of the OpenPixelCache() method is: % % MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o mode: ReadMode, WriteMode, or IOMode. % % o exception: return any errors or warnings in this structure. % */ static inline void AllocatePixelCachePixels(CacheInfo *cache_info) { cache_info->mapped=MagickFalse; cache_info->pixels=(PixelPacket *) MagickAssumeAligned( AcquireAlignedMemory(1,(size_t) cache_info->length)); if (cache_info->pixels == (PixelPacket *) NULL) { cache_info->mapped=MagickTrue; cache_info->pixels=(PixelPacket *) MapBlob(-1,IOMode,0,(size_t) cache_info->length); } } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #if defined(SIGBUS) static void CacheSignalHandler(int status) { ThrowFatalException(CacheFatalError,"UnableToExtendPixelCache"); } #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif static MagickBooleanType OpenPixelCacheOnDisk(CacheInfo *cache_info, const MapMode mode) { int file; /* Open pixel cache on disk. */ if ((cache_info->file != -1) && (cache_info->mode == mode)) return(MagickTrue); /* cache already open and in the proper mode */ if (*cache_info->cache_filename == '\0') file=AcquireUniqueFileResource(cache_info->cache_filename); else switch (mode) { case ReadMode: { file=open_utf8(cache_info->cache_filename,O_RDONLY | O_BINARY,0); break; } case WriteMode: { file=open_utf8(cache_info->cache_filename,O_WRONLY | O_CREAT | O_BINARY | O_EXCL,S_MODE); if (file == -1) file=open_utf8(cache_info->cache_filename,O_WRONLY | O_BINARY,S_MODE); break; } case IOMode: default: { file=open_utf8(cache_info->cache_filename,O_RDWR | O_CREAT | O_BINARY | O_EXCL,S_MODE); if (file == -1) file=open_utf8(cache_info->cache_filename,O_RDWR | O_BINARY,S_MODE); break; } } if (file == -1) return(MagickFalse); (void) AcquireMagickResource(FileResource,1); if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); cache_info->file=file; cache_info->mode=mode; return(MagickTrue); } static inline MagickOffsetType WritePixelCacheRegion( const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset, const MagickSizeType length,const unsigned char *magick_restrict buffer) { register MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PWRITE) if (lseek(cache_info->file,offset,SEEK_SET) < 0) return((MagickOffsetType) -1); #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PWRITE) count=write(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX)); #else count=pwrite(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX),(off_t) (offset+i)); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } return(i); } static MagickBooleanType SetPixelCacheExtent(Image *image,MagickSizeType length) { CacheInfo *magick_restrict cache_info; MagickOffsetType count, extent, offset; cache_info=(CacheInfo *) image->cache; if (image->debug != MagickFalse) { char format[MaxTextExtent], message[MaxTextExtent]; (void) FormatMagickSize(length,MagickFalse,format); (void) FormatLocaleString(message,MaxTextExtent, "extend %s (%s[%d], disk, %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_END); if (offset < 0) return(MagickFalse); if ((MagickSizeType) offset >= length) count=(MagickOffsetType) 1; else { extent=(MagickOffsetType) length-1; count=WritePixelCacheRegion(cache_info,extent,1,(const unsigned char *) ""); #if defined(MAGICKCORE_HAVE_POSIX_FALLOCATE) if (cache_info->synchronize != MagickFalse) (void) posix_fallocate(cache_info->file,offset+1,extent-offset); #endif #if defined(SIGBUS) (void) signal(SIGBUS,CacheSignalHandler); #endif } offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_SET); if (offset < 0) return(MagickFalse); return(count != (MagickOffsetType) 1 ? MagickFalse : MagickTrue); } static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, source_info; char format[MaxTextExtent], message[MaxTextExtent]; const char *type; MagickSizeType length, number_pixels; MagickStatusType status; size_t columns, packet_size; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->columns == 0) || (image->rows == 0)) ThrowBinaryException(CacheError,"NoPixelsDefinedInCache",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) || (AcquireMagickResource(HeightResource,image->rows) == MagickFalse)) ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed", image->filename); source_info=(*cache_info); source_info.file=(-1); (void) FormatLocaleString(cache_info->filename,MaxTextExtent,"%s[%.20g]", image->filename,(double) GetImageIndexInList(image)); cache_info->mode=mode; cache_info->rows=image->rows; cache_info->columns=image->columns; cache_info->channels=image->channels; cache_info->active_index_channel=((image->storage_class == PseudoClass) || (image->colorspace == CMYKColorspace)) ? MagickTrue : MagickFalse; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; packet_size=sizeof(PixelPacket); if (cache_info->active_index_channel != MagickFalse) packet_size+=sizeof(IndexPacket); length=number_pixels*packet_size; columns=(size_t) (length/cache_info->rows/packet_size); if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) || ((ssize_t) cache_info->rows < 0)) ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed", image->filename); cache_info->length=length; if (image->ping != MagickFalse) { cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->type=PingCache; return(MagickTrue); } status=AcquireMagickResource(AreaResource,cache_info->length); length=number_pixels*(sizeof(PixelPacket)+sizeof(IndexPacket)); if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length))) { status=AcquireMagickResource(MemoryResource,cache_info->length); if (((cache_info->type == UndefinedCache) && (status != MagickFalse)) || (cache_info->type == MemoryCache)) { AllocatePixelCachePixels(cache_info); if (cache_info->pixels == (PixelPacket *) NULL) cache_info->pixels=source_info.pixels; else { /* Create memory pixel cache. */ cache_info->colorspace=image->colorspace; cache_info->type=MemoryCache; cache_info->indexes=(IndexPacket *) NULL; if (cache_info->active_index_channel != MagickFalse) cache_info->indexes=(IndexPacket *) (cache_info->pixels+ number_pixels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status&=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, "open %s (%s %s, %.20gx%.20g %s)",cache_info->filename, cache_info->mapped != MagickFalse ? "Anonymous" : "Heap", type,(double) cache_info->columns,(double) cache_info->rows, format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } cache_info->storage_class=image->storage_class; return(MagickTrue); } } RelinquishMagickResource(MemoryResource,cache_info->length); } /* Create pixel cache on disk. */ status=AcquireMagickResource(DiskResource,cache_info->length); if ((status == MagickFalse) || (cache_info->type == DistributedCache)) { DistributeCacheInfo *server_info; if (cache_info->type == DistributedCache) RelinquishMagickResource(DiskResource,cache_info->length); server_info=AcquireDistributeCacheInfo(exception); if (server_info != (DistributeCacheInfo *) NULL) { status=OpenDistributePixelCache(server_info,image); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", GetDistributeCacheHostname(server_info)); server_info=DestroyDistributeCacheInfo(server_info); } else { /* Create a distributed pixel cache. */ cache_info->type=DistributedCache; cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->server_info=server_info; (void) FormatLocaleString(cache_info->cache_filename, MaxTextExtent,"%s:%d",GetDistributeCacheHostname( (DistributeCacheInfo *) cache_info->server_info), GetDistributeCachePort((DistributeCacheInfo *) cache_info->server_info)); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse, format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, "open %s (%s[%d], %s, %.20gx%.20g %s)",cache_info->filename, cache_info->cache_filename,GetDistributeCacheFile( (DistributeCacheInfo *) cache_info->server_info),type, (double) cache_info->columns,(double) cache_info->rows, format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(MagickTrue); } } RelinquishMagickResource(DiskResource,cache_info->length); (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { (void) ClosePixelCacheOnDisk(cache_info); *cache_info->cache_filename='\0'; } if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse) { RelinquishMagickResource(DiskResource,cache_info->length); ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", image->filename); return(MagickFalse); } status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+ cache_info->length); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToExtendCache", image->filename); return(MagickFalse); } cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; length=number_pixels*(sizeof(PixelPacket)+sizeof(IndexPacket)); if (length != (MagickSizeType) ((size_t) length)) cache_info->type=DiskCache; else { status=AcquireMagickResource(MapResource,cache_info->length); if ((status == MagickFalse) && (cache_info->type != MapCache) && (cache_info->type != MemoryCache)) cache_info->type=DiskCache; else { cache_info->pixels=(PixelPacket *) MapBlob(cache_info->file,mode, cache_info->offset,(size_t) cache_info->length); if (cache_info->pixels == (PixelPacket *) NULL) { cache_info->pixels=source_info.pixels; cache_info->type=DiskCache; } else { /* Create file-backed memory-mapped pixel cache. */ (void) ClosePixelCacheOnDisk(cache_info); cache_info->type=MapCache; cache_info->mapped=MagickTrue; cache_info->indexes=(IndexPacket *) NULL; if (cache_info->active_index_channel != MagickFalse) cache_info->indexes=(IndexPacket *) (cache_info->pixels+ number_pixels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, "open %s (%s[%d], %s, %.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(MagickTrue); } } RelinquishMagickResource(MapResource,cache_info->length); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info,exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MaxTextExtent, "open %s (%s[%d], %s, %.20gx%.20g %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P e r s i s t P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PersistPixelCache() attaches to or initializes a persistent pixel cache. A % persistent pixel cache is one that resides on disk and is not destroyed % when the program exits. % % The format of the PersistPixelCache() method is: % % MagickBooleanType PersistPixelCache(Image *image,const char *filename, % const MagickBooleanType attach,MagickOffsetType *offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o filename: the persistent pixel cache filename. % % o attach: A value other than zero initializes the persistent pixel cache. % % o initialize: A value other than zero initializes the persistent pixel % cache. % % o offset: the offset in the persistent cache to store pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType PersistPixelCache(Image *image, const char *filename,const MagickBooleanType attach,MagickOffsetType *offset, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, *magick_restrict clone_info; Image clone_image; MagickBooleanType status; ssize_t page_size; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (void *) NULL); assert(filename != (const char *) NULL); assert(offset != (MagickOffsetType *) NULL); page_size=GetMagickPageSize(); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (attach != MagickFalse) { /* Attach existing persistent pixel cache. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "attach persistent cache"); (void) CopyMagickString(cache_info->cache_filename,filename, MaxTextExtent); cache_info->type=DiskCache; cache_info->offset=(*offset); if (OpenPixelCache(image,ReadMode,exception) == MagickFalse) return(MagickFalse); *offset+=cache_info->length+page_size-(cache_info->length % page_size); return(MagickTrue); } if ((cache_info->mode != ReadMode) && (cache_info->type != MemoryCache) && (cache_info->reference_count == 1)) { LockSemaphoreInfo(cache_info->semaphore); if ((cache_info->mode != ReadMode) && (cache_info->type != MemoryCache) && (cache_info->reference_count == 1)) { int status; /* Usurp existing persistent pixel cache. */ status=rename_utf8(cache_info->cache_filename,filename); if (status == 0) { (void) CopyMagickString(cache_info->cache_filename,filename, MaxTextExtent); *offset+=cache_info->length+page_size-(cache_info->length % page_size); UnlockSemaphoreInfo(cache_info->semaphore); cache_info=(CacheInfo *) ReferencePixelCache(cache_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "Usurp resident persistent cache"); return(MagickTrue); } } UnlockSemaphoreInfo(cache_info->semaphore); } /* Clone persistent pixel cache. */ clone_image=(*image); clone_info=(CacheInfo *) clone_image.cache; image->cache=ClonePixelCache(cache_info); cache_info=(CacheInfo *) ReferencePixelCache(image->cache); (void) CopyMagickString(cache_info->cache_filename,filename,MaxTextExtent); cache_info->type=DiskCache; cache_info->offset=(*offset); cache_info=(CacheInfo *) image->cache; status=OpenPixelCache(image,IOMode,exception); if (status != MagickFalse) status=ClonePixelCacheRepository(cache_info,clone_info,&image->exception); *offset+=cache_info->length+page_size-(cache_info->length % page_size); clone_info=(CacheInfo *) DestroyPixelCache(clone_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u e u e A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixelCacheNexus() allocates an region to store image pixels as % defined by the region rectangle and returns a pointer to the region. This % region is subsequently transferred from the pixel cache with % SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the % pixels are transferred, otherwise a NULL is returned. % % The format of the QueueAuthenticPixelCacheNexus() method is: % % PixelPacket *QueueAuthenticPixelCacheNexus(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % const MagickBooleanType clone,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to set. % % o clone: clone the pixel cache. % % o exception: return any errors or warnings in this structure. % */ MagickExport PixelPacket *QueueAuthenticPixel(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, const MagickBooleanType clone,NexusInfo *nexus_info, ExceptionInfo *exception) { return(QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,clone,nexus_info, exception)); } MagickExport PixelPacket *QueueAuthenticPixelCacheNexus(Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, const MagickBooleanType clone,NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickOffsetType offset; MagickSizeType number_pixels; PixelPacket *magick_restrict pixels; RectangleInfo region; /* Validate pixel cache geometry. */ assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,clone,exception); if (cache_info == (Cache) NULL) return((PixelPacket *) NULL); assert(cache_info->signature == MagickSignature); if ((cache_info->columns == 0) || (cache_info->rows == 0) || (x < 0) || (y < 0) || (x >= (ssize_t) cache_info->columns) || (y >= (ssize_t) cache_info->rows)) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "PixelsAreNotAuthentic","`%s'",image->filename); return((PixelPacket *) NULL); } offset=(MagickOffsetType) y*cache_info->columns+x; if (offset < 0) return((PixelPacket *) NULL); number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; offset+=(MagickOffsetType) (rows-1)*cache_info->columns+columns-1; if ((MagickSizeType) offset >= number_pixels) return((PixelPacket *) NULL); /* Return pixel cache. */ region.x=x; region.y=y; region.width=columns; region.height=rows; pixels=SetPixelCacheNexusPixels(cache_info,WriteMode,&region, (image->clip_mask != (Image *) NULL) || (image->mask != (Image *) NULL) ? MagickTrue : MagickFalse,nexus_info,exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u e u e A u t h e n t i c P i x e l s C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixelsCache() allocates an region to store image pixels as % defined by the region rectangle and returns a pointer to the region. This % region is subsequently transferred from the pixel cache with % SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the % pixels are transferred, otherwise a NULL is returned. % % The format of the QueueAuthenticPixelsCache() method is: % % PixelPacket *QueueAuthenticPixelsCache(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static PixelPacket *QueueAuthenticPixelsCache(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); return(QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse, cache_info->nexus_info[id],exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u e u e A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixels() queues a mutable pixel region. If the region is % successfully initialized a pointer to a PixelPacket array representing the % region is returned, otherwise NULL is returned. The returned pointer may % point to a temporary working buffer for the pixels or it may point to the % final location of the pixels in memory. % % Write-only access means that any existing pixel values corresponding to % the region are ignored. This is useful if the initial image is being % created from scratch, or if the existing pixel values are to be % completely replaced without need to refer to their pre-existing values. % The application is free to read and write the pixel buffer returned by % QueueAuthenticPixels() any way it pleases. QueueAuthenticPixels() does not % initialize the pixel array values. Initializing pixel array values is the % application's responsibility. % % Performance is maximized if the selected region is part of one row, or % one or more full rows, since then there is opportunity to access the % pixels in-place (without a copy) if the image is in memory, or in a % memory-mapped file. The returned pointer must *never* be deallocated % by the user. % % Pixels accessed via the returned pointer represent a simple array of type % PixelPacket. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticIndexQueue() after invoking GetAuthenticPixels() to obtain % the black color component or the colormap indexes (of type IndexPacket) % corresponding to the region. Once the PixelPacket (and/or IndexPacket) % array has been updated, the changes must be saved back to the underlying % image using SyncAuthenticPixels() or they may be lost. % % The format of the QueueAuthenticPixels() method is: % % PixelPacket *QueueAuthenticPixels(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport PixelPacket *QueueAuthenticPixels(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->methods.queue_authentic_pixels_handler != (QueueAuthenticPixelsHandler) NULL) return(cache_info->methods.queue_authentic_pixels_handler(image,x,y,columns, rows,exception)); assert(id < (int) cache_info->number_threads); return(QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse, cache_info->nexus_info[id],exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d P i x e l C a c h e I n d e x e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPixelCacheIndexes() reads colormap indexes from the specified region of % the pixel cache. % % The format of the ReadPixelCacheIndexes() method is: % % MagickBooleanType ReadPixelCacheIndexes(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to read the colormap indexes. % % o exception: return any errors or warnings in this structure. % */ static inline MagickOffsetType ReadPixelCacheRegion( const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset, const MagickSizeType length,unsigned char *magick_restrict buffer) { register MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PREAD) if (lseek(cache_info->file,offset,SEEK_SET) < 0) return((MagickOffsetType) -1); #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PREAD) count=read(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX)); #else count=pread(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX),(off_t) (offset+i)); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } return(i); } static MagickBooleanType ReadPixelCacheIndexes( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register IndexPacket *magick_restrict q; register ssize_t y; size_t rows; if (cache_info->active_index_channel == MagickFalse) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width*sizeof(IndexPacket); rows=nexus_info->region.height; extent=length*rows; q=nexus_info->indexes; y=0; switch (cache_info->type) { case MemoryCache: case MapCache: { register IndexPacket *magick_restrict p; /* Read indexes from memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } p=cache_info->indexes+offset; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->columns; q+=nexus_info->region.width; } break; } case DiskCache: { /* Read indexes from disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } extent=(MagickSizeType) cache_info->columns*cache_info->rows; for (y=0; y < (ssize_t) rows; y++) { count=ReadPixelCacheRegion(cache_info,cache_info->offset+extent* sizeof(PixelPacket)+offset*sizeof(*q),length,(unsigned char *) q); if ((MagickSizeType) count < length) break; offset+=cache_info->columns; q+=nexus_info->region.width; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Read indexes from distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadDistributePixelCacheIndexes((DistributeCacheInfo *) cache_info->server_info,&region,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; q+=nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToReadPixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPixelCachePixels() reads pixels from the specified region of the pixel % cache. % % The format of the ReadPixelCachePixels() method is: % % MagickBooleanType ReadPixelCachePixels(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to read the pixels. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ReadPixelCachePixels( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register PixelPacket *magick_restrict q; register ssize_t y; size_t rows; if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns; if ((ssize_t) (offset/cache_info->columns) != nexus_info->region.y) return(MagickFalse); offset+=nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width*sizeof(PixelPacket); if ((length/sizeof(PixelPacket)) != nexus_info->region.width) return(MagickFalse); rows=nexus_info->region.height; extent=length*rows; if ((extent == 0) || ((extent/length) != rows)) return(MagickFalse); q=nexus_info->pixels; y=0; switch (cache_info->type) { case MemoryCache: case MapCache: { register PixelPacket *magick_restrict p; /* Read pixels from memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } p=cache_info->pixels+offset; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->columns; q+=nexus_info->region.width; } break; } case DiskCache: { /* Read pixels from disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadPixelCacheRegion(cache_info,cache_info->offset+offset* sizeof(*q),length,(unsigned char *) q); if ((MagickSizeType) count < length) break; offset+=cache_info->columns; q+=nexus_info->region.width; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Read pixels from distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadDistributePixelCachePixels((DistributeCacheInfo *) cache_info->server_info,&region,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; q+=nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToReadPixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e f e r e n c e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReferencePixelCache() increments the reference count associated with the % pixel cache returning a pointer to the cache. % % The format of the ReferencePixelCache method is: % % Cache ReferencePixelCache(Cache cache_info) % % A description of each parameter follows: % % o cache_info: the pixel cache. % */ MagickExport Cache ReferencePixelCache(Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickSignature); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count++; UnlockSemaphoreInfo(cache_info->semaphore); return(cache_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheMethods() sets the image pixel methods to the specified ones. % % The format of the SetPixelCacheMethods() method is: % % SetPixelCacheMethods(Cache *,CacheMethods *cache_methods) % % A description of each parameter follows: % % o cache: the pixel cache. % % o cache_methods: Specifies a pointer to a CacheMethods structure. % */ MagickExport void SetPixelCacheMethods(Cache cache,CacheMethods *cache_methods) { CacheInfo *magick_restrict cache_info; GetOneAuthenticPixelFromHandler get_one_authentic_pixel_from_handler; GetOneVirtualPixelFromHandler get_one_virtual_pixel_from_handler; /* Set cache pixel methods. */ assert(cache != (Cache) NULL); assert(cache_methods != (CacheMethods *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); if (cache_methods->get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL) cache_info->methods.get_virtual_pixel_handler= cache_methods->get_virtual_pixel_handler; if (cache_methods->destroy_pixel_handler != (DestroyPixelHandler) NULL) cache_info->methods.destroy_pixel_handler= cache_methods->destroy_pixel_handler; if (cache_methods->get_virtual_indexes_from_handler != (GetVirtualIndexesFromHandler) NULL) cache_info->methods.get_virtual_indexes_from_handler= cache_methods->get_virtual_indexes_from_handler; if (cache_methods->get_authentic_pixels_handler != (GetAuthenticPixelsHandler) NULL) cache_info->methods.get_authentic_pixels_handler= cache_methods->get_authentic_pixels_handler; if (cache_methods->queue_authentic_pixels_handler != (QueueAuthenticPixelsHandler) NULL) cache_info->methods.queue_authentic_pixels_handler= cache_methods->queue_authentic_pixels_handler; if (cache_methods->sync_authentic_pixels_handler != (SyncAuthenticPixelsHandler) NULL) cache_info->methods.sync_authentic_pixels_handler= cache_methods->sync_authentic_pixels_handler; if (cache_methods->get_authentic_pixels_from_handler != (GetAuthenticPixelsFromHandler) NULL) cache_info->methods.get_authentic_pixels_from_handler= cache_methods->get_authentic_pixels_from_handler; if (cache_methods->get_authentic_indexes_from_handler != (GetAuthenticIndexesFromHandler) NULL) cache_info->methods.get_authentic_indexes_from_handler= cache_methods->get_authentic_indexes_from_handler; get_one_virtual_pixel_from_handler= cache_info->methods.get_one_virtual_pixel_from_handler; if (get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) cache_info->methods.get_one_virtual_pixel_from_handler= cache_methods->get_one_virtual_pixel_from_handler; get_one_authentic_pixel_from_handler= cache_methods->get_one_authentic_pixel_from_handler; if (get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) cache_info->methods.get_one_authentic_pixel_from_handler= cache_methods->get_one_authentic_pixel_from_handler; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t P i x e l C a c h e N e x u s P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheNexusPixels() defines the region of the cache for the % specified cache nexus. % % The format of the SetPixelCacheNexusPixels() method is: % % PixelPacket SetPixelCacheNexusPixels(const CacheInfo *cache_info, % const MapMode mode,const RectangleInfo *region, % const MagickBooleanType buffered,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o mode: ReadMode, WriteMode, or IOMode. % % o region: A pointer to the RectangleInfo structure that defines the % region of this particular cache nexus. % % o buffered: pixels are buffered. % % o nexus_info: the cache nexus to set. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType AcquireCacheNexusPixels( const CacheInfo *magick_restrict cache_info,NexusInfo *nexus_info, ExceptionInfo *exception) { if (nexus_info->length != (MagickSizeType) ((size_t) nexus_info->length)) return(MagickFalse); nexus_info->mapped=MagickFalse; nexus_info->cache=(PixelPacket *) MagickAssumeAligned(AcquireAlignedMemory(1, (size_t) nexus_info->length)); if (nexus_info->cache == (PixelPacket *) NULL) { nexus_info->mapped=MagickTrue; nexus_info->cache=(PixelPacket *) MapBlob(-1,IOMode,0,(size_t) nexus_info->length); } if (nexus_info->cache == (PixelPacket *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", cache_info->filename); return(MagickFalse); } return(MagickTrue); } static inline MagickBooleanType IsAuthenticPixelCache( const CacheInfo *magick_restrict cache_info, const NexusInfo *magick_restrict nexus_info) { MagickBooleanType status; MagickOffsetType offset; /* Does nexus pixels point directly to in-core cache pixels or is it buffered? */ if (cache_info->type == PingCache) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; status=nexus_info->pixels == (cache_info->pixels+offset) ? MagickTrue : MagickFalse; return(status); } static inline void PrefetchPixelCacheNexusPixels(const NexusInfo *nexus_info, const MapMode mode) { magick_unreferenced(nexus_info); magick_unreferenced(mode); if (mode == ReadMode) { MagickCachePrefetch((unsigned char *) nexus_info->pixels,0,1); return; } MagickCachePrefetch((unsigned char *) nexus_info->pixels,1,1); } static PixelPacket *SetPixelCacheNexusPixels(const CacheInfo *cache_info, const MapMode mode,const RectangleInfo *region, const MagickBooleanType buffered,NexusInfo *nexus_info, ExceptionInfo *exception) { MagickBooleanType status; MagickSizeType length, number_pixels; assert(cache_info != (const CacheInfo *) NULL); assert(cache_info->signature == MagickSignature); if (cache_info->type == UndefinedCache) return((PixelPacket *) NULL); nexus_info->region=(*region); if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) && (buffered == MagickFalse)) { ssize_t x, y; x=nexus_info->region.x+(ssize_t) nexus_info->region.width-1; y=nexus_info->region.y+(ssize_t) nexus_info->region.height-1; if (((nexus_info->region.x >= 0) && (x < (ssize_t) cache_info->columns) && (nexus_info->region.y >= 0) && (y < (ssize_t) cache_info->rows)) && ((nexus_info->region.height == 1UL) || ((nexus_info->region.x == 0) && ((nexus_info->region.width == cache_info->columns) || ((nexus_info->region.width % cache_info->columns) == 0))))) { MagickOffsetType offset; /* Pixels are accessed directly from memory. */ offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; nexus_info->pixels=cache_info->pixels+offset; nexus_info->indexes=(IndexPacket *) NULL; if (cache_info->active_index_channel != MagickFalse) nexus_info->indexes=cache_info->indexes+offset; PrefetchPixelCacheNexusPixels(nexus_info,mode); nexus_info->authentic_pixel_cache=IsAuthenticPixelCache(cache_info, nexus_info); return(nexus_info->pixels); } } /* Pixels are stored in a staging region until they are synced to the cache. */ number_pixels=(MagickSizeType) nexus_info->region.width* nexus_info->region.height; length=number_pixels*sizeof(PixelPacket); if (cache_info->active_index_channel != MagickFalse) length+=number_pixels*sizeof(IndexPacket); if (nexus_info->cache == (PixelPacket *) NULL) { nexus_info->length=length; status=AcquireCacheNexusPixels(cache_info,nexus_info,exception); if (status == MagickFalse) { nexus_info->length=0; return((PixelPacket *) NULL); } } else if (nexus_info->length < length) { RelinquishCacheNexusPixels(nexus_info); nexus_info->length=length; status=AcquireCacheNexusPixels(cache_info,nexus_info,exception); if (status == MagickFalse) { nexus_info->length=0; return((PixelPacket *) NULL); } } nexus_info->pixels=nexus_info->cache; nexus_info->indexes=(IndexPacket *) NULL; if (cache_info->active_index_channel != MagickFalse) nexus_info->indexes=(IndexPacket *) (nexus_info->pixels+number_pixels); PrefetchPixelCacheNexusPixels(nexus_info,mode); nexus_info->authentic_pixel_cache=IsAuthenticPixelCache(cache_info, nexus_info); return(nexus_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t P i x e l C a c h e V i r t u a l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheVirtualMethod() sets the "virtual pixels" method for the % pixel cache and returns the previous setting. A virtual pixel is any pixel % access that is outside the boundaries of the image cache. % % The format of the SetPixelCacheVirtualMethod() method is: % % VirtualPixelMethod SetPixelCacheVirtualMethod(const Image *image, % const VirtualPixelMethod virtual_pixel_method) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: choose the type of virtual pixel. % */ static MagickBooleanType SetCacheAlphaChannel(Image *image, const Quantum opacity) { CacheInfo *magick_restrict cache_info; CacheView *magick_restrict image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); image->matte=MagickTrue; status=MagickTrue; image_view=AcquireVirtualCacheView(image,&image->exception); /* must be virtual */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, &image->exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { q->opacity=opacity; q++; } status=SyncCacheViewAuthenticPixels(image_view,&image->exception); } image_view=DestroyCacheView(image_view); return(status); } MagickExport VirtualPixelMethod SetPixelCacheVirtualMethod(const Image *image, const VirtualPixelMethod virtual_pixel_method) { CacheInfo *magick_restrict cache_info; VirtualPixelMethod method; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); method=cache_info->virtual_pixel_method; cache_info->virtual_pixel_method=virtual_pixel_method; if ((image->columns != 0) && (image->rows != 0)) switch (virtual_pixel_method) { case BackgroundVirtualPixelMethod: { if ((image->background_color.opacity != OpaqueOpacity) && (image->matte == MagickFalse)) (void) SetCacheAlphaChannel((Image *) image,OpaqueOpacity); if ((IsPixelGray(&image->background_color) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) SetImageColorspace((Image *) image,sRGBColorspace); break; } case TransparentVirtualPixelMethod: { if (image->matte == MagickFalse) (void) SetCacheAlphaChannel((Image *) image,OpaqueOpacity); break; } default: break; } return(method); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixelCacheNexus() saves the authentic image pixels to the % in-memory or disk cache. The method returns MagickTrue if the pixel region % is synced, otherwise MagickFalse. % % The format of the SyncAuthenticPixelCacheNexus() method is: % % MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to sync. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickBooleanType status; /* Transfer pixels to the cache. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->cache == (Cache) NULL) ThrowBinaryException(CacheError,"PixelCacheIsNotOpen",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->type == UndefinedCache) return(MagickFalse); if ((image->storage_class == DirectClass) && (image->clip_mask != (Image *) NULL) && (ClipPixelCacheNexus(image,nexus_info,exception) == MagickFalse)) return(MagickFalse); if ((image->storage_class == DirectClass) && (image->mask != (Image *) NULL) && (MaskPixelCacheNexus(image,nexus_info,exception) == MagickFalse)) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) { image->taint=MagickTrue; return(MagickTrue); } assert(cache_info->signature == MagickSignature); status=WritePixelCachePixels(cache_info,nexus_info,exception); if ((cache_info->active_index_channel != MagickFalse) && (WritePixelCacheIndexes(cache_info,nexus_info,exception) == MagickFalse)) return(MagickFalse); if (status != MagickFalse) image->taint=MagickTrue; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixelsCache() saves the authentic image pixels to the in-memory % or disk cache. The method returns MagickTrue if the pixel region is synced, % otherwise MagickFalse. % % The format of the SyncAuthenticPixelsCache() method is: % % MagickBooleanType SyncAuthenticPixelsCache(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType SyncAuthenticPixelsCache(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); assert(id < (int) cache_info->number_threads); status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id], exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixels() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is flushed, otherwise % MagickFalse. % % The format of the SyncAuthenticPixels() method is: % % MagickBooleanType SyncAuthenticPixels(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SyncAuthenticPixels(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickSignature); if (cache_info->methods.sync_authentic_pixels_handler != (SyncAuthenticPixelsHandler) NULL) return(cache_info->methods.sync_authentic_pixels_handler(image,exception)); assert(id < (int) cache_info->number_threads); status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id], exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImagePixelCache() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is flushed, otherwise % MagickFalse. % % The format of the SyncImagePixelCache() method is: % % MagickBooleanType SyncImagePixelCache(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate MagickBooleanType SyncImagePixelCache(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(exception != (ExceptionInfo *) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,MagickTrue,exception); return(cache_info == (CacheInfo *) NULL ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + W r i t e P i x e l C a c h e I n d e x e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePixelCacheIndexes() writes the colormap indexes to the specified % region of the pixel cache. % % The format of the WritePixelCacheIndexes() method is: % % MagickBooleanType WritePixelCacheIndexes(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to write the colormap indexes. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePixelCacheIndexes(CacheInfo *cache_info, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register const IndexPacket *magick_restrict p; register ssize_t y; size_t rows; if (cache_info->active_index_channel == MagickFalse) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width*sizeof(IndexPacket); rows=nexus_info->region.height; extent=(MagickSizeType) length*rows; p=nexus_info->indexes; y=0; switch (cache_info->type) { case MemoryCache: case MapCache: { register IndexPacket *magick_restrict q; /* Write indexes to memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } q=cache_info->indexes+offset; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=nexus_info->region.width; q+=cache_info->columns; } break; } case DiskCache: { /* Write indexes to disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } extent=(MagickSizeType) cache_info->columns*cache_info->rows; for (y=0; y < (ssize_t) rows; y++) { count=WritePixelCacheRegion(cache_info,cache_info->offset+extent* sizeof(PixelPacket)+offset*sizeof(*p),length,(const unsigned char *) p); if ((MagickSizeType) count < length) break; p+=nexus_info->region.width; offset+=cache_info->columns; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Write indexes to distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WriteDistributePixelCacheIndexes((DistributeCacheInfo *) cache_info->server_info,&region,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToWritePixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + W r i t e P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePixelCachePixels() writes image pixels to the specified region of the % pixel cache. % % The format of the WritePixelCachePixels() method is: % % MagickBooleanType WritePixelCachePixels(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to write the pixels. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePixelCachePixels(CacheInfo *cache_info, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register const PixelPacket *magick_restrict p; register ssize_t y; size_t rows; if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width*sizeof(PixelPacket); rows=nexus_info->region.height; extent=length*rows; p=nexus_info->pixels; y=0; switch (cache_info->type) { case MemoryCache: case MapCache: { register PixelPacket *magick_restrict q; /* Write pixels to memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } q=cache_info->pixels+offset; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=nexus_info->region.width; q+=cache_info->columns; } break; } case DiskCache: { /* Write pixels to disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WritePixelCacheRegion(cache_info,cache_info->offset+offset* sizeof(*p),length,(const unsigned char *) p); if ((MagickSizeType) count < length) break; p+=nexus_info->region.width; offset+=cache_info->columns; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Write pixels to distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WriteDistributePixelCachePixels((DistributeCacheInfo *) cache_info->server_info,&region,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToWritePixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-399/c/bad_5318_0
crossvul-cpp_data_bad_2059_0
/* * wanXL serial card driver for Linux * host part * * Copyright (C) 2003 Krzysztof Halasa <khc@pm.waw.pl> * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License * as published by the Free Software Foundation. * * Status: * - Only DTE (external clock) support with NRZ and NRZI encodings * - wanXL100 will require minor driver modifications, no access to hw */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/sched.h> #include <linux/types.h> #include <linux/fcntl.h> #include <linux/string.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/netdevice.h> #include <linux/hdlc.h> #include <linux/pci.h> #include <linux/dma-mapping.h> #include <linux/delay.h> #include <asm/io.h> #include "wanxl.h" static const char* version = "wanXL serial card driver version: 0.48"; #define PLX_CTL_RESET 0x40000000 /* adapter reset */ #undef DEBUG_PKT #undef DEBUG_PCI /* MAILBOX #1 - PUTS COMMANDS */ #define MBX1_CMD_ABORTJ 0x85000000 /* Abort and Jump */ #ifdef __LITTLE_ENDIAN #define MBX1_CMD_BSWAP 0x8C000001 /* little-endian Byte Swap Mode */ #else #define MBX1_CMD_BSWAP 0x8C000000 /* big-endian Byte Swap Mode */ #endif /* MAILBOX #2 - DRAM SIZE */ #define MBX2_MEMSZ_MASK 0xFFFF0000 /* PUTS Memory Size Register mask */ typedef struct { struct net_device *dev; struct card_t *card; spinlock_t lock; /* for wanxl_xmit */ int node; /* physical port #0 - 3 */ unsigned int clock_type; int tx_in, tx_out; struct sk_buff *tx_skbs[TX_BUFFERS]; }port_t; typedef struct { desc_t rx_descs[RX_QUEUE_LENGTH]; port_status_t port_status[4]; }card_status_t; typedef struct card_t { int n_ports; /* 1, 2 or 4 ports */ u8 irq; u8 __iomem *plx; /* PLX PCI9060 virtual base address */ struct pci_dev *pdev; /* for pci_name(pdev) */ int rx_in; struct sk_buff *rx_skbs[RX_QUEUE_LENGTH]; card_status_t *status; /* shared between host and card */ dma_addr_t status_address; port_t ports[0]; /* 1 - 4 port_t structures follow */ }card_t; static inline port_t* dev_to_port(struct net_device *dev) { return (port_t *)dev_to_hdlc(dev)->priv; } static inline port_status_t* get_status(port_t *port) { return &port->card->status->port_status[port->node]; } #ifdef DEBUG_PCI static inline dma_addr_t pci_map_single_debug(struct pci_dev *pdev, void *ptr, size_t size, int direction) { dma_addr_t addr = pci_map_single(pdev, ptr, size, direction); if (addr + size > 0x100000000LL) pr_crit("%s: pci_map_single() returned memory at 0x%llx!\n", pci_name(pdev), (unsigned long long)addr); return addr; } #undef pci_map_single #define pci_map_single pci_map_single_debug #endif /* Cable and/or personality module change interrupt service */ static inline void wanxl_cable_intr(port_t *port) { u32 value = get_status(port)->cable; int valid = 1; const char *cable, *pm, *dte = "", *dsr = "", *dcd = ""; switch(value & 0x7) { case STATUS_CABLE_V35: cable = "V.35"; break; case STATUS_CABLE_X21: cable = "X.21"; break; case STATUS_CABLE_V24: cable = "V.24"; break; case STATUS_CABLE_EIA530: cable = "EIA530"; break; case STATUS_CABLE_NONE: cable = "no"; break; default: cable = "invalid"; } switch((value >> STATUS_CABLE_PM_SHIFT) & 0x7) { case STATUS_CABLE_V35: pm = "V.35"; break; case STATUS_CABLE_X21: pm = "X.21"; break; case STATUS_CABLE_V24: pm = "V.24"; break; case STATUS_CABLE_EIA530: pm = "EIA530"; break; case STATUS_CABLE_NONE: pm = "no personality"; valid = 0; break; default: pm = "invalid personality"; valid = 0; } if (valid) { if ((value & 7) == ((value >> STATUS_CABLE_PM_SHIFT) & 7)) { dsr = (value & STATUS_CABLE_DSR) ? ", DSR ON" : ", DSR off"; dcd = (value & STATUS_CABLE_DCD) ? ", carrier ON" : ", carrier off"; } dte = (value & STATUS_CABLE_DCE) ? " DCE" : " DTE"; } netdev_info(port->dev, "%s%s module, %s cable%s%s\n", pm, dte, cable, dsr, dcd); if (value & STATUS_CABLE_DCD) netif_carrier_on(port->dev); else netif_carrier_off(port->dev); } /* Transmit complete interrupt service */ static inline void wanxl_tx_intr(port_t *port) { struct net_device *dev = port->dev; while (1) { desc_t *desc = &get_status(port)->tx_descs[port->tx_in]; struct sk_buff *skb = port->tx_skbs[port->tx_in]; switch (desc->stat) { case PACKET_FULL: case PACKET_EMPTY: netif_wake_queue(dev); return; case PACKET_UNDERRUN: dev->stats.tx_errors++; dev->stats.tx_fifo_errors++; break; default: dev->stats.tx_packets++; dev->stats.tx_bytes += skb->len; } desc->stat = PACKET_EMPTY; /* Free descriptor */ pci_unmap_single(port->card->pdev, desc->address, skb->len, PCI_DMA_TODEVICE); dev_kfree_skb_irq(skb); port->tx_in = (port->tx_in + 1) % TX_BUFFERS; } } /* Receive complete interrupt service */ static inline void wanxl_rx_intr(card_t *card) { desc_t *desc; while (desc = &card->status->rx_descs[card->rx_in], desc->stat != PACKET_EMPTY) { if ((desc->stat & PACKET_PORT_MASK) > card->n_ports) pr_crit("%s: received packet for nonexistent port\n", pci_name(card->pdev)); else { struct sk_buff *skb = card->rx_skbs[card->rx_in]; port_t *port = &card->ports[desc->stat & PACKET_PORT_MASK]; struct net_device *dev = port->dev; if (!skb) dev->stats.rx_dropped++; else { pci_unmap_single(card->pdev, desc->address, BUFFER_LENGTH, PCI_DMA_FROMDEVICE); skb_put(skb, desc->length); #ifdef DEBUG_PKT printk(KERN_DEBUG "%s RX(%i):", dev->name, skb->len); debug_frame(skb); #endif dev->stats.rx_packets++; dev->stats.rx_bytes += skb->len; skb->protocol = hdlc_type_trans(skb, dev); netif_rx(skb); skb = NULL; } if (!skb) { skb = dev_alloc_skb(BUFFER_LENGTH); desc->address = skb ? pci_map_single(card->pdev, skb->data, BUFFER_LENGTH, PCI_DMA_FROMDEVICE) : 0; card->rx_skbs[card->rx_in] = skb; } } desc->stat = PACKET_EMPTY; /* Free descriptor */ card->rx_in = (card->rx_in + 1) % RX_QUEUE_LENGTH; } } static irqreturn_t wanxl_intr(int irq, void* dev_id) { card_t *card = dev_id; int i; u32 stat; int handled = 0; while((stat = readl(card->plx + PLX_DOORBELL_FROM_CARD)) != 0) { handled = 1; writel(stat, card->plx + PLX_DOORBELL_FROM_CARD); for (i = 0; i < card->n_ports; i++) { if (stat & (1 << (DOORBELL_FROM_CARD_TX_0 + i))) wanxl_tx_intr(&card->ports[i]); if (stat & (1 << (DOORBELL_FROM_CARD_CABLE_0 + i))) wanxl_cable_intr(&card->ports[i]); } if (stat & (1 << DOORBELL_FROM_CARD_RX)) wanxl_rx_intr(card); } return IRQ_RETVAL(handled); } static netdev_tx_t wanxl_xmit(struct sk_buff *skb, struct net_device *dev) { port_t *port = dev_to_port(dev); desc_t *desc; spin_lock(&port->lock); desc = &get_status(port)->tx_descs[port->tx_out]; if (desc->stat != PACKET_EMPTY) { /* should never happen - previous xmit should stop queue */ #ifdef DEBUG_PKT printk(KERN_DEBUG "%s: transmitter buffer full\n", dev->name); #endif netif_stop_queue(dev); spin_unlock(&port->lock); return NETDEV_TX_BUSY; /* request packet to be queued */ } #ifdef DEBUG_PKT printk(KERN_DEBUG "%s TX(%i):", dev->name, skb->len); debug_frame(skb); #endif port->tx_skbs[port->tx_out] = skb; desc->address = pci_map_single(port->card->pdev, skb->data, skb->len, PCI_DMA_TODEVICE); desc->length = skb->len; desc->stat = PACKET_FULL; writel(1 << (DOORBELL_TO_CARD_TX_0 + port->node), port->card->plx + PLX_DOORBELL_TO_CARD); port->tx_out = (port->tx_out + 1) % TX_BUFFERS; if (get_status(port)->tx_descs[port->tx_out].stat != PACKET_EMPTY) { netif_stop_queue(dev); #ifdef DEBUG_PKT printk(KERN_DEBUG "%s: transmitter buffer full\n", dev->name); #endif } spin_unlock(&port->lock); return NETDEV_TX_OK; } static int wanxl_attach(struct net_device *dev, unsigned short encoding, unsigned short parity) { port_t *port = dev_to_port(dev); if (encoding != ENCODING_NRZ && encoding != ENCODING_NRZI) return -EINVAL; if (parity != PARITY_NONE && parity != PARITY_CRC32_PR1_CCITT && parity != PARITY_CRC16_PR1_CCITT && parity != PARITY_CRC32_PR0_CCITT && parity != PARITY_CRC16_PR0_CCITT) return -EINVAL; get_status(port)->encoding = encoding; get_status(port)->parity = parity; return 0; } static int wanxl_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { const size_t size = sizeof(sync_serial_settings); sync_serial_settings line; port_t *port = dev_to_port(dev); if (cmd != SIOCWANDEV) return hdlc_ioctl(dev, ifr, cmd); switch (ifr->ifr_settings.type) { case IF_GET_IFACE: ifr->ifr_settings.type = IF_IFACE_SYNC_SERIAL; if (ifr->ifr_settings.size < size) { ifr->ifr_settings.size = size; /* data size wanted */ return -ENOBUFS; } line.clock_type = get_status(port)->clocking; line.clock_rate = 0; line.loopback = 0; if (copy_to_user(ifr->ifr_settings.ifs_ifsu.sync, &line, size)) return -EFAULT; return 0; case IF_IFACE_SYNC_SERIAL: if (!capable(CAP_NET_ADMIN)) return -EPERM; if (dev->flags & IFF_UP) return -EBUSY; if (copy_from_user(&line, ifr->ifr_settings.ifs_ifsu.sync, size)) return -EFAULT; if (line.clock_type != CLOCK_EXT && line.clock_type != CLOCK_TXFROMRX) return -EINVAL; /* No such clock setting */ if (line.loopback != 0) return -EINVAL; get_status(port)->clocking = line.clock_type; return 0; default: return hdlc_ioctl(dev, ifr, cmd); } } static int wanxl_open(struct net_device *dev) { port_t *port = dev_to_port(dev); u8 __iomem *dbr = port->card->plx + PLX_DOORBELL_TO_CARD; unsigned long timeout; int i; if (get_status(port)->open) { netdev_err(dev, "port already open\n"); return -EIO; } if ((i = hdlc_open(dev)) != 0) return i; port->tx_in = port->tx_out = 0; for (i = 0; i < TX_BUFFERS; i++) get_status(port)->tx_descs[i].stat = PACKET_EMPTY; /* signal the card */ writel(1 << (DOORBELL_TO_CARD_OPEN_0 + port->node), dbr); timeout = jiffies + HZ; do { if (get_status(port)->open) { netif_start_queue(dev); return 0; } } while (time_after(timeout, jiffies)); netdev_err(dev, "unable to open port\n"); /* ask the card to close the port, should it be still alive */ writel(1 << (DOORBELL_TO_CARD_CLOSE_0 + port->node), dbr); return -EFAULT; } static int wanxl_close(struct net_device *dev) { port_t *port = dev_to_port(dev); unsigned long timeout; int i; hdlc_close(dev); /* signal the card */ writel(1 << (DOORBELL_TO_CARD_CLOSE_0 + port->node), port->card->plx + PLX_DOORBELL_TO_CARD); timeout = jiffies + HZ; do { if (!get_status(port)->open) break; } while (time_after(timeout, jiffies)); if (get_status(port)->open) netdev_err(dev, "unable to close port\n"); netif_stop_queue(dev); for (i = 0; i < TX_BUFFERS; i++) { desc_t *desc = &get_status(port)->tx_descs[i]; if (desc->stat != PACKET_EMPTY) { desc->stat = PACKET_EMPTY; pci_unmap_single(port->card->pdev, desc->address, port->tx_skbs[i]->len, PCI_DMA_TODEVICE); dev_kfree_skb(port->tx_skbs[i]); } } return 0; } static struct net_device_stats *wanxl_get_stats(struct net_device *dev) { port_t *port = dev_to_port(dev); dev->stats.rx_over_errors = get_status(port)->rx_overruns; dev->stats.rx_frame_errors = get_status(port)->rx_frame_errors; dev->stats.rx_errors = dev->stats.rx_over_errors + dev->stats.rx_frame_errors; return &dev->stats; } static int wanxl_puts_command(card_t *card, u32 cmd) { unsigned long timeout = jiffies + 5 * HZ; writel(cmd, card->plx + PLX_MAILBOX_1); do { if (readl(card->plx + PLX_MAILBOX_1) == 0) return 0; schedule(); }while (time_after(timeout, jiffies)); return -1; } static void wanxl_reset(card_t *card) { u32 old_value = readl(card->plx + PLX_CONTROL) & ~PLX_CTL_RESET; writel(0x80, card->plx + PLX_MAILBOX_0); writel(old_value | PLX_CTL_RESET, card->plx + PLX_CONTROL); readl(card->plx + PLX_CONTROL); /* wait for posted write */ udelay(1); writel(old_value, card->plx + PLX_CONTROL); readl(card->plx + PLX_CONTROL); /* wait for posted write */ } static void wanxl_pci_remove_one(struct pci_dev *pdev) { card_t *card = pci_get_drvdata(pdev); int i; for (i = 0; i < card->n_ports; i++) { unregister_hdlc_device(card->ports[i].dev); free_netdev(card->ports[i].dev); } /* unregister and free all host resources */ if (card->irq) free_irq(card->irq, card); wanxl_reset(card); for (i = 0; i < RX_QUEUE_LENGTH; i++) if (card->rx_skbs[i]) { pci_unmap_single(card->pdev, card->status->rx_descs[i].address, BUFFER_LENGTH, PCI_DMA_FROMDEVICE); dev_kfree_skb(card->rx_skbs[i]); } if (card->plx) iounmap(card->plx); if (card->status) pci_free_consistent(pdev, sizeof(card_status_t), card->status, card->status_address); pci_release_regions(pdev); pci_disable_device(pdev); pci_set_drvdata(pdev, NULL); kfree(card); } #include "wanxlfw.inc" static const struct net_device_ops wanxl_ops = { .ndo_open = wanxl_open, .ndo_stop = wanxl_close, .ndo_change_mtu = hdlc_change_mtu, .ndo_start_xmit = hdlc_start_xmit, .ndo_do_ioctl = wanxl_ioctl, .ndo_get_stats = wanxl_get_stats, }; static int wanxl_pci_init_one(struct pci_dev *pdev, const struct pci_device_id *ent) { card_t *card; u32 ramsize, stat; unsigned long timeout; u32 plx_phy; /* PLX PCI base address */ u32 mem_phy; /* memory PCI base addr */ u8 __iomem *mem; /* memory virtual base addr */ int i, ports, alloc_size; #ifndef MODULE pr_info_once("%s\n", version); #endif i = pci_enable_device(pdev); if (i) return i; /* QUICC can only access first 256 MB of host RAM directly, but PLX9060 DMA does 32-bits for actual packet data transfers */ /* FIXME when PCI/DMA subsystems are fixed. We set both dma_mask and consistent_dma_mask to 28 bits and pray pci_alloc_consistent() will use this info. It should work on most platforms */ if (pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(28)) || pci_set_dma_mask(pdev, DMA_BIT_MASK(28))) { pr_err("No usable DMA configuration\n"); return -EIO; } i = pci_request_regions(pdev, "wanXL"); if (i) { pci_disable_device(pdev); return i; } switch (pdev->device) { case PCI_DEVICE_ID_SBE_WANXL100: ports = 1; break; case PCI_DEVICE_ID_SBE_WANXL200: ports = 2; break; default: ports = 4; } alloc_size = sizeof(card_t) + ports * sizeof(port_t); card = kzalloc(alloc_size, GFP_KERNEL); if (card == NULL) { pci_release_regions(pdev); pci_disable_device(pdev); return -ENOBUFS; } pci_set_drvdata(pdev, card); card->pdev = pdev; card->status = pci_alloc_consistent(pdev, sizeof(card_status_t), &card->status_address); if (card->status == NULL) { wanxl_pci_remove_one(pdev); return -ENOBUFS; } #ifdef DEBUG_PCI printk(KERN_DEBUG "wanXL %s: pci_alloc_consistent() returned memory" " at 0x%LX\n", pci_name(pdev), (unsigned long long)card->status_address); #endif /* FIXME when PCI/DMA subsystems are fixed. We set both dma_mask and consistent_dma_mask back to 32 bits to indicate the card can do 32-bit DMA addressing */ if (pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32)) || pci_set_dma_mask(pdev, DMA_BIT_MASK(32))) { pr_err("No usable DMA configuration\n"); wanxl_pci_remove_one(pdev); return -EIO; } /* set up PLX mapping */ plx_phy = pci_resource_start(pdev, 0); card->plx = ioremap_nocache(plx_phy, 0x70); if (!card->plx) { pr_err("ioremap() failed\n"); wanxl_pci_remove_one(pdev); return -EFAULT; } #if RESET_WHILE_LOADING wanxl_reset(card); #endif timeout = jiffies + 20 * HZ; while ((stat = readl(card->plx + PLX_MAILBOX_0)) != 0) { if (time_before(timeout, jiffies)) { pr_warn("%s: timeout waiting for PUTS to complete\n", pci_name(pdev)); wanxl_pci_remove_one(pdev); return -ENODEV; } switch(stat & 0xC0) { case 0x00: /* hmm - PUTS completed with non-zero code? */ case 0x80: /* PUTS still testing the hardware */ break; default: pr_warn("%s: PUTS test 0x%X failed\n", pci_name(pdev), stat & 0x30); wanxl_pci_remove_one(pdev); return -ENODEV; } schedule(); } /* get on-board memory size (PUTS detects no more than 4 MB) */ ramsize = readl(card->plx + PLX_MAILBOX_2) & MBX2_MEMSZ_MASK; /* set up on-board RAM mapping */ mem_phy = pci_resource_start(pdev, 2); /* sanity check the board's reported memory size */ if (ramsize < BUFFERS_ADDR + (TX_BUFFERS + RX_BUFFERS) * BUFFER_LENGTH * ports) { pr_warn("%s: no enough on-board RAM (%u bytes detected, %u bytes required)\n", pci_name(pdev), ramsize, BUFFERS_ADDR + (TX_BUFFERS + RX_BUFFERS) * BUFFER_LENGTH * ports); wanxl_pci_remove_one(pdev); return -ENODEV; } if (wanxl_puts_command(card, MBX1_CMD_BSWAP)) { pr_warn("%s: unable to Set Byte Swap Mode\n", pci_name(pdev)); wanxl_pci_remove_one(pdev); return -ENODEV; } for (i = 0; i < RX_QUEUE_LENGTH; i++) { struct sk_buff *skb = dev_alloc_skb(BUFFER_LENGTH); card->rx_skbs[i] = skb; if (skb) card->status->rx_descs[i].address = pci_map_single(card->pdev, skb->data, BUFFER_LENGTH, PCI_DMA_FROMDEVICE); } mem = ioremap_nocache(mem_phy, PDM_OFFSET + sizeof(firmware)); if (!mem) { pr_err("ioremap() failed\n"); wanxl_pci_remove_one(pdev); return -EFAULT; } for (i = 0; i < sizeof(firmware); i += 4) writel(ntohl(*(__be32*)(firmware + i)), mem + PDM_OFFSET + i); for (i = 0; i < ports; i++) writel(card->status_address + (void *)&card->status->port_status[i] - (void *)card->status, mem + PDM_OFFSET + 4 + i * 4); writel(card->status_address, mem + PDM_OFFSET + 20); writel(PDM_OFFSET, mem); iounmap(mem); writel(0, card->plx + PLX_MAILBOX_5); if (wanxl_puts_command(card, MBX1_CMD_ABORTJ)) { pr_warn("%s: unable to Abort and Jump\n", pci_name(pdev)); wanxl_pci_remove_one(pdev); return -ENODEV; } stat = 0; timeout = jiffies + 5 * HZ; do { if ((stat = readl(card->plx + PLX_MAILBOX_5)) != 0) break; schedule(); }while (time_after(timeout, jiffies)); if (!stat) { pr_warn("%s: timeout while initializing card firmware\n", pci_name(pdev)); wanxl_pci_remove_one(pdev); return -ENODEV; } #if DETECT_RAM ramsize = stat; #endif pr_info("%s: at 0x%X, %u KB of RAM at 0x%X, irq %u\n", pci_name(pdev), plx_phy, ramsize / 1024, mem_phy, pdev->irq); /* Allocate IRQ */ if (request_irq(pdev->irq, wanxl_intr, IRQF_SHARED, "wanXL", card)) { pr_warn("%s: could not allocate IRQ%i\n", pci_name(pdev), pdev->irq); wanxl_pci_remove_one(pdev); return -EBUSY; } card->irq = pdev->irq; for (i = 0; i < ports; i++) { hdlc_device *hdlc; port_t *port = &card->ports[i]; struct net_device *dev = alloc_hdlcdev(port); if (!dev) { pr_err("%s: unable to allocate memory\n", pci_name(pdev)); wanxl_pci_remove_one(pdev); return -ENOMEM; } port->dev = dev; hdlc = dev_to_hdlc(dev); spin_lock_init(&port->lock); dev->tx_queue_len = 50; dev->netdev_ops = &wanxl_ops; hdlc->attach = wanxl_attach; hdlc->xmit = wanxl_xmit; port->card = card; port->node = i; get_status(port)->clocking = CLOCK_EXT; if (register_hdlc_device(dev)) { pr_err("%s: unable to register hdlc device\n", pci_name(pdev)); free_netdev(dev); wanxl_pci_remove_one(pdev); return -ENOBUFS; } card->n_ports++; } pr_info("%s: port", pci_name(pdev)); for (i = 0; i < ports; i++) pr_cont("%s #%i: %s", i ? "," : "", i, card->ports[i].dev->name); pr_cont("\n"); for (i = 0; i < ports; i++) wanxl_cable_intr(&card->ports[i]); /* get carrier status etc.*/ return 0; } static DEFINE_PCI_DEVICE_TABLE(wanxl_pci_tbl) = { { PCI_VENDOR_ID_SBE, PCI_DEVICE_ID_SBE_WANXL100, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 }, { PCI_VENDOR_ID_SBE, PCI_DEVICE_ID_SBE_WANXL200, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 }, { PCI_VENDOR_ID_SBE, PCI_DEVICE_ID_SBE_WANXL400, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 }, { 0, } }; static struct pci_driver wanxl_pci_driver = { .name = "wanXL", .id_table = wanxl_pci_tbl, .probe = wanxl_pci_init_one, .remove = wanxl_pci_remove_one, }; static int __init wanxl_init_module(void) { #ifdef MODULE pr_info("%s\n", version); #endif return pci_register_driver(&wanxl_pci_driver); } static void __exit wanxl_cleanup_module(void) { pci_unregister_driver(&wanxl_pci_driver); } MODULE_AUTHOR("Krzysztof Halasa <khc@pm.waw.pl>"); MODULE_DESCRIPTION("SBE Inc. wanXL serial port driver"); MODULE_LICENSE("GPL v2"); MODULE_DEVICE_TABLE(pci, wanxl_pci_tbl); module_init(wanxl_init_module); module_exit(wanxl_cleanup_module);
./CrossVul/dataset_final_sorted/CWE-399/c/bad_2059_0
crossvul-cpp_data_good_2172_0
/* SCTP kernel implementation * Copyright (c) 1999-2000 Cisco, Inc. * Copyright (c) 1999-2001 Motorola, Inc. * Copyright (c) 2002 International Business Machines, Corp. * * This file is part of the SCTP kernel implementation * * These functions are the methods for accessing the SCTP inqueue. * * An SCTP inqueue is a queue into which you push SCTP packets * (which might be bundles or fragments of chunks) and out of which you * pop SCTP whole chunks. * * 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> */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <net/sctp/sctp.h> #include <net/sctp/sm.h> #include <linux/interrupt.h> #include <linux/slab.h> /* Initialize an SCTP inqueue. */ void sctp_inq_init(struct sctp_inq *queue) { INIT_LIST_HEAD(&queue->in_chunk_list); queue->in_progress = NULL; /* Create a task for delivering data. */ INIT_WORK(&queue->immediate, NULL); } /* Release the memory associated with an SCTP inqueue. */ void sctp_inq_free(struct sctp_inq *queue) { struct sctp_chunk *chunk, *tmp; /* Empty the queue. */ list_for_each_entry_safe(chunk, tmp, &queue->in_chunk_list, list) { list_del_init(&chunk->list); sctp_chunk_free(chunk); } /* If there is a packet which is currently being worked on, * free it as well. */ if (queue->in_progress) { sctp_chunk_free(queue->in_progress); queue->in_progress = NULL; } } /* Put a new packet in an SCTP inqueue. * We assume that packet->sctp_hdr is set and in host byte order. */ void sctp_inq_push(struct sctp_inq *q, struct sctp_chunk *chunk) { /* Directly call the packet handling routine. */ if (chunk->rcvr->dead) { sctp_chunk_free(chunk); return; } /* We are now calling this either from the soft interrupt * or from the backlog processing. * Eventually, we should clean up inqueue to not rely * on the BH related data structures. */ list_add_tail(&chunk->list, &q->in_chunk_list); if (chunk->asoc) chunk->asoc->stats.ipackets++; q->immediate.func(&q->immediate); } /* Peek at the next chunk on the inqeue. */ struct sctp_chunkhdr *sctp_inq_peek(struct sctp_inq *queue) { struct sctp_chunk *chunk; sctp_chunkhdr_t *ch = NULL; chunk = queue->in_progress; /* If there is no more chunks in this packet, say so */ if (chunk->singleton || chunk->end_of_packet || chunk->pdiscard) return NULL; ch = (sctp_chunkhdr_t *)chunk->chunk_end; return ch; } /* Extract a chunk from an SCTP inqueue. * * WARNING: If you need to put the chunk on another queue, you need to * make a shallow copy (clone) of it. */ struct sctp_chunk *sctp_inq_pop(struct sctp_inq *queue) { struct sctp_chunk *chunk; sctp_chunkhdr_t *ch = NULL; /* The assumption is that we are safe to process the chunks * at this time. */ if ((chunk = queue->in_progress)) { /* There is a packet that we have been working on. * Any post processing work to do before we move on? */ if (chunk->singleton || chunk->end_of_packet || chunk->pdiscard) { sctp_chunk_free(chunk); chunk = queue->in_progress = NULL; } else { /* Nothing to do. Next chunk in the packet, please. */ ch = (sctp_chunkhdr_t *) chunk->chunk_end; /* Force chunk->skb->data to chunk->chunk_end. */ skb_pull(chunk->skb, chunk->chunk_end - chunk->skb->data); /* We are guaranteed to pull a SCTP header. */ } } /* Do we need to take the next packet out of the queue to process? */ if (!chunk) { struct list_head *entry; /* Is the queue empty? */ if (list_empty(&queue->in_chunk_list)) return NULL; entry = queue->in_chunk_list.next; chunk = queue->in_progress = list_entry(entry, struct sctp_chunk, list); list_del_init(entry); /* This is the first chunk in the packet. */ chunk->singleton = 1; ch = (sctp_chunkhdr_t *) chunk->skb->data; chunk->data_accepted = 0; } chunk->chunk_hdr = ch; chunk->chunk_end = ((__u8 *)ch) + WORD_ROUND(ntohs(ch->length)); /* In the unlikely case of an IP reassembly, the skb could be * non-linear. If so, update chunk_end so that it doesn't go past * the skb->tail. */ if (unlikely(skb_is_nonlinear(chunk->skb))) { if (chunk->chunk_end > skb_tail_pointer(chunk->skb)) chunk->chunk_end = skb_tail_pointer(chunk->skb); } skb_pull(chunk->skb, sizeof(sctp_chunkhdr_t)); chunk->subh.v = NULL; /* Subheader is no longer valid. */ if (chunk->chunk_end + sizeof(sctp_chunkhdr_t) < skb_tail_pointer(chunk->skb)) { /* This is not a singleton */ chunk->singleton = 0; } else if (chunk->chunk_end > skb_tail_pointer(chunk->skb)) { /* Discard inside state machine. */ chunk->pdiscard = 1; chunk->chunk_end = skb_tail_pointer(chunk->skb); } else { /* We are at the end of the packet, so mark the chunk * in case we need to send a SACK. */ chunk->end_of_packet = 1; } pr_debug("+++sctp_inq_pop+++ chunk:%p[%s], length:%d, skb->len:%d\n", chunk, sctp_cname(SCTP_ST_CHUNK(chunk->chunk_hdr->type)), ntohs(chunk->chunk_hdr->length), chunk->skb->len); return chunk; } /* Set a top-half handler. * * Originally, we the top-half handler was scheduled as a BH. We now * call the handler directly in sctp_inq_push() at a time that * we know we are lock safe. * The intent is that this routine will pull stuff out of the * inqueue and process it. */ void sctp_inq_set_th_handler(struct sctp_inq *q, work_func_t callback) { INIT_WORK(&q->immediate, callback); }
./CrossVul/dataset_final_sorted/CWE-399/c/good_2172_0
crossvul-cpp_data_bad_5650_0
/* * linux/kernel/signal.c * * Copyright (C) 1991, 1992 Linus Torvalds * * 1997-11-02 Modified for POSIX.1b signals by Richard Henderson * * 2003-06-02 Jim Houston - Concurrent Computer Corp. * Changes to use preallocated sigqueue structures * to allow signals to be sent reliably. */ #include <linux/slab.h> #include <linux/export.h> #include <linux/init.h> #include <linux/sched.h> #include <linux/fs.h> #include <linux/tty.h> #include <linux/binfmts.h> #include <linux/coredump.h> #include <linux/security.h> #include <linux/syscalls.h> #include <linux/ptrace.h> #include <linux/signal.h> #include <linux/signalfd.h> #include <linux/ratelimit.h> #include <linux/tracehook.h> #include <linux/capability.h> #include <linux/freezer.h> #include <linux/pid_namespace.h> #include <linux/nsproxy.h> #include <linux/user_namespace.h> #include <linux/uprobes.h> #include <linux/compat.h> #define CREATE_TRACE_POINTS #include <trace/events/signal.h> #include <asm/param.h> #include <asm/uaccess.h> #include <asm/unistd.h> #include <asm/siginfo.h> #include <asm/cacheflush.h> #include "audit.h" /* audit_signal_info() */ /* * SLAB caches for signal bits. */ static struct kmem_cache *sigqueue_cachep; int print_fatal_signals __read_mostly; static void __user *sig_handler(struct task_struct *t, int sig) { return t->sighand->action[sig - 1].sa.sa_handler; } static int sig_handler_ignored(void __user *handler, int sig) { /* Is it explicitly or implicitly ignored? */ return handler == SIG_IGN || (handler == SIG_DFL && sig_kernel_ignore(sig)); } static int sig_task_ignored(struct task_struct *t, int sig, bool force) { void __user *handler; handler = sig_handler(t, sig); if (unlikely(t->signal->flags & SIGNAL_UNKILLABLE) && handler == SIG_DFL && !force) return 1; return sig_handler_ignored(handler, sig); } static int sig_ignored(struct task_struct *t, int sig, bool force) { /* * Blocked signals are never ignored, since the * signal handler may change by the time it is * unblocked. */ if (sigismember(&t->blocked, sig) || sigismember(&t->real_blocked, sig)) return 0; if (!sig_task_ignored(t, sig, force)) return 0; /* * Tracers may want to know about even ignored signals. */ return !t->ptrace; } /* * Re-calculate pending state from the set of locally pending * signals, globally pending signals, and blocked signals. */ static inline int has_pending_signals(sigset_t *signal, sigset_t *blocked) { unsigned long ready; long i; switch (_NSIG_WORDS) { default: for (i = _NSIG_WORDS, ready = 0; --i >= 0 ;) ready |= signal->sig[i] &~ blocked->sig[i]; break; case 4: ready = signal->sig[3] &~ blocked->sig[3]; ready |= signal->sig[2] &~ blocked->sig[2]; ready |= signal->sig[1] &~ blocked->sig[1]; ready |= signal->sig[0] &~ blocked->sig[0]; break; case 2: ready = signal->sig[1] &~ blocked->sig[1]; ready |= signal->sig[0] &~ blocked->sig[0]; break; case 1: ready = signal->sig[0] &~ blocked->sig[0]; } return ready != 0; } #define PENDING(p,b) has_pending_signals(&(p)->signal, (b)) static int recalc_sigpending_tsk(struct task_struct *t) { if ((t->jobctl & JOBCTL_PENDING_MASK) || PENDING(&t->pending, &t->blocked) || PENDING(&t->signal->shared_pending, &t->blocked)) { set_tsk_thread_flag(t, TIF_SIGPENDING); return 1; } /* * We must never clear the flag in another thread, or in current * when it's possible the current syscall is returning -ERESTART*. * So we don't clear it here, and only callers who know they should do. */ return 0; } /* * After recalculating TIF_SIGPENDING, we need to make sure the task wakes up. * This is superfluous when called on current, the wakeup is a harmless no-op. */ void recalc_sigpending_and_wake(struct task_struct *t) { if (recalc_sigpending_tsk(t)) signal_wake_up(t, 0); } void recalc_sigpending(void) { if (!recalc_sigpending_tsk(current) && !freezing(current)) clear_thread_flag(TIF_SIGPENDING); } /* Given the mask, find the first available signal that should be serviced. */ #define SYNCHRONOUS_MASK \ (sigmask(SIGSEGV) | sigmask(SIGBUS) | sigmask(SIGILL) | \ sigmask(SIGTRAP) | sigmask(SIGFPE) | sigmask(SIGSYS)) int next_signal(struct sigpending *pending, sigset_t *mask) { unsigned long i, *s, *m, x; int sig = 0; s = pending->signal.sig; m = mask->sig; /* * Handle the first word specially: it contains the * synchronous signals that need to be dequeued first. */ x = *s &~ *m; if (x) { if (x & SYNCHRONOUS_MASK) x &= SYNCHRONOUS_MASK; sig = ffz(~x) + 1; return sig; } switch (_NSIG_WORDS) { default: for (i = 1; i < _NSIG_WORDS; ++i) { x = *++s &~ *++m; if (!x) continue; sig = ffz(~x) + i*_NSIG_BPW + 1; break; } break; case 2: x = s[1] &~ m[1]; if (!x) break; sig = ffz(~x) + _NSIG_BPW + 1; break; case 1: /* Nothing to do */ break; } return sig; } static inline void print_dropped_signal(int sig) { static DEFINE_RATELIMIT_STATE(ratelimit_state, 5 * HZ, 10); if (!print_fatal_signals) return; if (!__ratelimit(&ratelimit_state)) return; printk(KERN_INFO "%s/%d: reached RLIMIT_SIGPENDING, dropped signal %d\n", current->comm, current->pid, sig); } /** * task_set_jobctl_pending - set jobctl pending bits * @task: target task * @mask: pending bits to set * * Clear @mask from @task->jobctl. @mask must be subset of * %JOBCTL_PENDING_MASK | %JOBCTL_STOP_CONSUME | %JOBCTL_STOP_SIGMASK | * %JOBCTL_TRAPPING. If stop signo is being set, the existing signo is * cleared. If @task is already being killed or exiting, this function * becomes noop. * * CONTEXT: * Must be called with @task->sighand->siglock held. * * RETURNS: * %true if @mask is set, %false if made noop because @task was dying. */ bool task_set_jobctl_pending(struct task_struct *task, unsigned int mask) { BUG_ON(mask & ~(JOBCTL_PENDING_MASK | JOBCTL_STOP_CONSUME | JOBCTL_STOP_SIGMASK | JOBCTL_TRAPPING)); BUG_ON((mask & JOBCTL_TRAPPING) && !(mask & JOBCTL_PENDING_MASK)); if (unlikely(fatal_signal_pending(task) || (task->flags & PF_EXITING))) return false; if (mask & JOBCTL_STOP_SIGMASK) task->jobctl &= ~JOBCTL_STOP_SIGMASK; task->jobctl |= mask; return true; } /** * task_clear_jobctl_trapping - clear jobctl trapping bit * @task: target task * * If JOBCTL_TRAPPING is set, a ptracer is waiting for us to enter TRACED. * Clear it and wake up the ptracer. Note that we don't need any further * locking. @task->siglock guarantees that @task->parent points to the * ptracer. * * CONTEXT: * Must be called with @task->sighand->siglock held. */ void task_clear_jobctl_trapping(struct task_struct *task) { if (unlikely(task->jobctl & JOBCTL_TRAPPING)) { task->jobctl &= ~JOBCTL_TRAPPING; wake_up_bit(&task->jobctl, JOBCTL_TRAPPING_BIT); } } /** * task_clear_jobctl_pending - clear jobctl pending bits * @task: target task * @mask: pending bits to clear * * Clear @mask from @task->jobctl. @mask must be subset of * %JOBCTL_PENDING_MASK. If %JOBCTL_STOP_PENDING is being cleared, other * STOP bits are cleared together. * * If clearing of @mask leaves no stop or trap pending, this function calls * task_clear_jobctl_trapping(). * * CONTEXT: * Must be called with @task->sighand->siglock held. */ void task_clear_jobctl_pending(struct task_struct *task, unsigned int mask) { BUG_ON(mask & ~JOBCTL_PENDING_MASK); if (mask & JOBCTL_STOP_PENDING) mask |= JOBCTL_STOP_CONSUME | JOBCTL_STOP_DEQUEUED; task->jobctl &= ~mask; if (!(task->jobctl & JOBCTL_PENDING_MASK)) task_clear_jobctl_trapping(task); } /** * task_participate_group_stop - participate in a group stop * @task: task participating in a group stop * * @task has %JOBCTL_STOP_PENDING set and is participating in a group stop. * Group stop states are cleared and the group stop count is consumed if * %JOBCTL_STOP_CONSUME was set. If the consumption completes the group * stop, the appropriate %SIGNAL_* flags are set. * * CONTEXT: * Must be called with @task->sighand->siglock held. * * RETURNS: * %true if group stop completion should be notified to the parent, %false * otherwise. */ static bool task_participate_group_stop(struct task_struct *task) { struct signal_struct *sig = task->signal; bool consume = task->jobctl & JOBCTL_STOP_CONSUME; WARN_ON_ONCE(!(task->jobctl & JOBCTL_STOP_PENDING)); task_clear_jobctl_pending(task, JOBCTL_STOP_PENDING); if (!consume) return false; if (!WARN_ON_ONCE(sig->group_stop_count == 0)) sig->group_stop_count--; /* * Tell the caller to notify completion iff we are entering into a * fresh group stop. Read comment in do_signal_stop() for details. */ if (!sig->group_stop_count && !(sig->flags & SIGNAL_STOP_STOPPED)) { sig->flags = SIGNAL_STOP_STOPPED; return true; } return false; } /* * allocate a new signal queue record * - this may be called without locks if and only if t == current, otherwise an * appropriate lock must be held to stop the target task from exiting */ static struct sigqueue * __sigqueue_alloc(int sig, struct task_struct *t, gfp_t flags, int override_rlimit) { struct sigqueue *q = NULL; struct user_struct *user; /* * Protect access to @t credentials. This can go away when all * callers hold rcu read lock. */ rcu_read_lock(); user = get_uid(__task_cred(t)->user); atomic_inc(&user->sigpending); rcu_read_unlock(); if (override_rlimit || atomic_read(&user->sigpending) <= task_rlimit(t, RLIMIT_SIGPENDING)) { q = kmem_cache_alloc(sigqueue_cachep, flags); } else { print_dropped_signal(sig); } if (unlikely(q == NULL)) { atomic_dec(&user->sigpending); free_uid(user); } else { INIT_LIST_HEAD(&q->list); q->flags = 0; q->user = user; } return q; } static void __sigqueue_free(struct sigqueue *q) { if (q->flags & SIGQUEUE_PREALLOC) return; atomic_dec(&q->user->sigpending); free_uid(q->user); kmem_cache_free(sigqueue_cachep, q); } void flush_sigqueue(struct sigpending *queue) { struct sigqueue *q; sigemptyset(&queue->signal); while (!list_empty(&queue->list)) { q = list_entry(queue->list.next, struct sigqueue , list); list_del_init(&q->list); __sigqueue_free(q); } } /* * Flush all pending signals for a task. */ void __flush_signals(struct task_struct *t) { clear_tsk_thread_flag(t, TIF_SIGPENDING); flush_sigqueue(&t->pending); flush_sigqueue(&t->signal->shared_pending); } void flush_signals(struct task_struct *t) { unsigned long flags; spin_lock_irqsave(&t->sighand->siglock, flags); __flush_signals(t); spin_unlock_irqrestore(&t->sighand->siglock, flags); } static void __flush_itimer_signals(struct sigpending *pending) { sigset_t signal, retain; struct sigqueue *q, *n; signal = pending->signal; sigemptyset(&retain); list_for_each_entry_safe(q, n, &pending->list, list) { int sig = q->info.si_signo; if (likely(q->info.si_code != SI_TIMER)) { sigaddset(&retain, sig); } else { sigdelset(&signal, sig); list_del_init(&q->list); __sigqueue_free(q); } } sigorsets(&pending->signal, &signal, &retain); } void flush_itimer_signals(void) { struct task_struct *tsk = current; unsigned long flags; spin_lock_irqsave(&tsk->sighand->siglock, flags); __flush_itimer_signals(&tsk->pending); __flush_itimer_signals(&tsk->signal->shared_pending); spin_unlock_irqrestore(&tsk->sighand->siglock, flags); } void ignore_signals(struct task_struct *t) { int i; for (i = 0; i < _NSIG; ++i) t->sighand->action[i].sa.sa_handler = SIG_IGN; flush_signals(t); } /* * Flush all handlers for a task. */ void flush_signal_handlers(struct task_struct *t, int force_default) { int i; struct k_sigaction *ka = &t->sighand->action[0]; for (i = _NSIG ; i != 0 ; i--) { if (force_default || ka->sa.sa_handler != SIG_IGN) ka->sa.sa_handler = SIG_DFL; ka->sa.sa_flags = 0; #ifdef __ARCH_HAS_SA_RESTORER ka->sa.sa_restorer = NULL; #endif sigemptyset(&ka->sa.sa_mask); ka++; } } int unhandled_signal(struct task_struct *tsk, int sig) { void __user *handler = tsk->sighand->action[sig-1].sa.sa_handler; if (is_global_init(tsk)) return 1; if (handler != SIG_IGN && handler != SIG_DFL) return 0; /* if ptraced, let the tracer determine */ return !tsk->ptrace; } /* * Notify the system that a driver wants to block all signals for this * process, and wants to be notified if any signals at all were to be * sent/acted upon. If the notifier routine returns non-zero, then the * signal will be acted upon after all. If the notifier routine returns 0, * then then signal will be blocked. Only one block per process is * allowed. priv is a pointer to private data that the notifier routine * can use to determine if the signal should be blocked or not. */ void block_all_signals(int (*notifier)(void *priv), void *priv, sigset_t *mask) { unsigned long flags; spin_lock_irqsave(&current->sighand->siglock, flags); current->notifier_mask = mask; current->notifier_data = priv; current->notifier = notifier; spin_unlock_irqrestore(&current->sighand->siglock, flags); } /* Notify the system that blocking has ended. */ void unblock_all_signals(void) { unsigned long flags; spin_lock_irqsave(&current->sighand->siglock, flags); current->notifier = NULL; current->notifier_data = NULL; recalc_sigpending(); spin_unlock_irqrestore(&current->sighand->siglock, flags); } static void collect_signal(int sig, struct sigpending *list, siginfo_t *info) { struct sigqueue *q, *first = NULL; /* * Collect the siginfo appropriate to this signal. Check if * there is another siginfo for the same signal. */ list_for_each_entry(q, &list->list, list) { if (q->info.si_signo == sig) { if (first) goto still_pending; first = q; } } sigdelset(&list->signal, sig); if (first) { still_pending: list_del_init(&first->list); copy_siginfo(info, &first->info); __sigqueue_free(first); } else { /* * Ok, it wasn't in the queue. This must be * a fast-pathed signal or we must have been * out of queue space. So zero out the info. */ info->si_signo = sig; info->si_errno = 0; info->si_code = SI_USER; info->si_pid = 0; info->si_uid = 0; } } static int __dequeue_signal(struct sigpending *pending, sigset_t *mask, siginfo_t *info) { int sig = next_signal(pending, mask); if (sig) { if (current->notifier) { if (sigismember(current->notifier_mask, sig)) { if (!(current->notifier)(current->notifier_data)) { clear_thread_flag(TIF_SIGPENDING); return 0; } } } collect_signal(sig, pending, info); } return sig; } /* * Dequeue a signal and return the element to the caller, which is * expected to free it. * * All callers have to hold the siglock. */ int dequeue_signal(struct task_struct *tsk, sigset_t *mask, siginfo_t *info) { int signr; /* We only dequeue private signals from ourselves, we don't let * signalfd steal them */ signr = __dequeue_signal(&tsk->pending, mask, info); if (!signr) { signr = __dequeue_signal(&tsk->signal->shared_pending, mask, info); /* * itimer signal ? * * itimers are process shared and we restart periodic * itimers in the signal delivery path to prevent DoS * attacks in the high resolution timer case. This is * compliant with the old way of self-restarting * itimers, as the SIGALRM is a legacy signal and only * queued once. Changing the restart behaviour to * restart the timer in the signal dequeue path is * reducing the timer noise on heavy loaded !highres * systems too. */ if (unlikely(signr == SIGALRM)) { struct hrtimer *tmr = &tsk->signal->real_timer; if (!hrtimer_is_queued(tmr) && tsk->signal->it_real_incr.tv64 != 0) { hrtimer_forward(tmr, tmr->base->get_time(), tsk->signal->it_real_incr); hrtimer_restart(tmr); } } } recalc_sigpending(); if (!signr) return 0; if (unlikely(sig_kernel_stop(signr))) { /* * Set a marker that we have dequeued a stop signal. Our * caller might release the siglock and then the pending * stop signal it is about to process is no longer in the * pending bitmasks, but must still be cleared by a SIGCONT * (and overruled by a SIGKILL). So those cases clear this * shared flag after we've set it. Note that this flag may * remain set after the signal we return is ignored or * handled. That doesn't matter because its only purpose * is to alert stop-signal processing code when another * processor has come along and cleared the flag. */ current->jobctl |= JOBCTL_STOP_DEQUEUED; } if ((info->si_code & __SI_MASK) == __SI_TIMER && info->si_sys_private) { /* * Release the siglock to ensure proper locking order * of timer locks outside of siglocks. Note, we leave * irqs disabled here, since the posix-timers code is * about to disable them again anyway. */ spin_unlock(&tsk->sighand->siglock); do_schedule_next_timer(info); spin_lock(&tsk->sighand->siglock); } return signr; } /* * Tell a process that it has a new active signal.. * * NOTE! we rely on the previous spin_lock to * lock interrupts for us! We can only be called with * "siglock" held, and the local interrupt must * have been disabled when that got acquired! * * No need to set need_resched since signal event passing * goes through ->blocked */ void signal_wake_up_state(struct task_struct *t, unsigned int state) { set_tsk_thread_flag(t, TIF_SIGPENDING); /* * TASK_WAKEKILL also means wake it up in the stopped/traced/killable * case. We don't check t->state here because there is a race with it * executing another processor and just now entering stopped state. * By using wake_up_state, we ensure the process will wake up and * handle its death signal. */ if (!wake_up_state(t, state | TASK_INTERRUPTIBLE)) kick_process(t); } /* * Remove signals in mask from the pending set and queue. * Returns 1 if any signals were found. * * All callers must be holding the siglock. * * This version takes a sigset mask and looks at all signals, * not just those in the first mask word. */ static int rm_from_queue_full(sigset_t *mask, struct sigpending *s) { struct sigqueue *q, *n; sigset_t m; sigandsets(&m, mask, &s->signal); if (sigisemptyset(&m)) return 0; sigandnsets(&s->signal, &s->signal, mask); list_for_each_entry_safe(q, n, &s->list, list) { if (sigismember(mask, q->info.si_signo)) { list_del_init(&q->list); __sigqueue_free(q); } } return 1; } /* * Remove signals in mask from the pending set and queue. * Returns 1 if any signals were found. * * All callers must be holding the siglock. */ static int rm_from_queue(unsigned long mask, struct sigpending *s) { struct sigqueue *q, *n; if (!sigtestsetmask(&s->signal, mask)) return 0; sigdelsetmask(&s->signal, mask); list_for_each_entry_safe(q, n, &s->list, list) { if (q->info.si_signo < SIGRTMIN && (mask & sigmask(q->info.si_signo))) { list_del_init(&q->list); __sigqueue_free(q); } } return 1; } static inline int is_si_special(const struct siginfo *info) { return info <= SEND_SIG_FORCED; } static inline bool si_fromuser(const struct siginfo *info) { return info == SEND_SIG_NOINFO || (!is_si_special(info) && SI_FROMUSER(info)); } /* * called with RCU read lock from check_kill_permission() */ static int kill_ok_by_cred(struct task_struct *t) { const struct cred *cred = current_cred(); const struct cred *tcred = __task_cred(t); if (uid_eq(cred->euid, tcred->suid) || uid_eq(cred->euid, tcred->uid) || uid_eq(cred->uid, tcred->suid) || uid_eq(cred->uid, tcred->uid)) return 1; if (ns_capable(tcred->user_ns, CAP_KILL)) return 1; return 0; } /* * Bad permissions for sending the signal * - the caller must hold the RCU read lock */ static int check_kill_permission(int sig, struct siginfo *info, struct task_struct *t) { struct pid *sid; int error; if (!valid_signal(sig)) return -EINVAL; if (!si_fromuser(info)) return 0; error = audit_signal_info(sig, t); /* Let audit system see the signal */ if (error) return error; if (!same_thread_group(current, t) && !kill_ok_by_cred(t)) { switch (sig) { case SIGCONT: sid = task_session(t); /* * We don't return the error if sid == NULL. The * task was unhashed, the caller must notice this. */ if (!sid || sid == task_session(current)) break; default: return -EPERM; } } return security_task_kill(t, info, sig, 0); } /** * ptrace_trap_notify - schedule trap to notify ptracer * @t: tracee wanting to notify tracer * * This function schedules sticky ptrace trap which is cleared on the next * TRAP_STOP to notify ptracer of an event. @t must have been seized by * ptracer. * * If @t is running, STOP trap will be taken. If trapped for STOP and * ptracer is listening for events, tracee is woken up so that it can * re-trap for the new event. If trapped otherwise, STOP trap will be * eventually taken without returning to userland after the existing traps * are finished by PTRACE_CONT. * * CONTEXT: * Must be called with @task->sighand->siglock held. */ static void ptrace_trap_notify(struct task_struct *t) { WARN_ON_ONCE(!(t->ptrace & PT_SEIZED)); assert_spin_locked(&t->sighand->siglock); task_set_jobctl_pending(t, JOBCTL_TRAP_NOTIFY); ptrace_signal_wake_up(t, t->jobctl & JOBCTL_LISTENING); } /* * Handle magic process-wide effects of stop/continue signals. Unlike * the signal actions, these happen immediately at signal-generation * time regardless of blocking, ignoring, or handling. This does the * actual continuing for SIGCONT, but not the actual stopping for stop * signals. The process stop is done as a signal action for SIG_DFL. * * Returns true if the signal should be actually delivered, otherwise * it should be dropped. */ static int prepare_signal(int sig, struct task_struct *p, bool force) { struct signal_struct *signal = p->signal; struct task_struct *t; if (unlikely(signal->flags & SIGNAL_GROUP_EXIT)) { /* * The process is in the middle of dying, nothing to do. */ } else if (sig_kernel_stop(sig)) { /* * This is a stop signal. Remove SIGCONT from all queues. */ rm_from_queue(sigmask(SIGCONT), &signal->shared_pending); t = p; do { rm_from_queue(sigmask(SIGCONT), &t->pending); } while_each_thread(p, t); } else if (sig == SIGCONT) { unsigned int why; /* * Remove all stop signals from all queues, wake all threads. */ rm_from_queue(SIG_KERNEL_STOP_MASK, &signal->shared_pending); t = p; do { task_clear_jobctl_pending(t, JOBCTL_STOP_PENDING); rm_from_queue(SIG_KERNEL_STOP_MASK, &t->pending); if (likely(!(t->ptrace & PT_SEIZED))) wake_up_state(t, __TASK_STOPPED); else ptrace_trap_notify(t); } while_each_thread(p, t); /* * Notify the parent with CLD_CONTINUED if we were stopped. * * If we were in the middle of a group stop, we pretend it * was already finished, and then continued. Since SIGCHLD * doesn't queue we report only CLD_STOPPED, as if the next * CLD_CONTINUED was dropped. */ why = 0; if (signal->flags & SIGNAL_STOP_STOPPED) why |= SIGNAL_CLD_CONTINUED; else if (signal->group_stop_count) why |= SIGNAL_CLD_STOPPED; if (why) { /* * The first thread which returns from do_signal_stop() * will take ->siglock, notice SIGNAL_CLD_MASK, and * notify its parent. See get_signal_to_deliver(). */ signal->flags = why | SIGNAL_STOP_CONTINUED; signal->group_stop_count = 0; signal->group_exit_code = 0; } } return !sig_ignored(p, sig, force); } /* * Test if P wants to take SIG. After we've checked all threads with this, * it's equivalent to finding no threads not blocking SIG. Any threads not * blocking SIG were ruled out because they are not running and already * have pending signals. Such threads will dequeue from the shared queue * as soon as they're available, so putting the signal on the shared queue * will be equivalent to sending it to one such thread. */ static inline int wants_signal(int sig, struct task_struct *p) { if (sigismember(&p->blocked, sig)) return 0; if (p->flags & PF_EXITING) return 0; if (sig == SIGKILL) return 1; if (task_is_stopped_or_traced(p)) return 0; return task_curr(p) || !signal_pending(p); } static void complete_signal(int sig, struct task_struct *p, int group) { struct signal_struct *signal = p->signal; struct task_struct *t; /* * Now find a thread we can wake up to take the signal off the queue. * * If the main thread wants the signal, it gets first crack. * Probably the least surprising to the average bear. */ if (wants_signal(sig, p)) t = p; else if (!group || thread_group_empty(p)) /* * There is just one thread and it does not need to be woken. * It will dequeue unblocked signals before it runs again. */ return; else { /* * Otherwise try to find a suitable thread. */ t = signal->curr_target; while (!wants_signal(sig, t)) { t = next_thread(t); if (t == signal->curr_target) /* * No thread needs to be woken. * Any eligible threads will see * the signal in the queue soon. */ return; } signal->curr_target = t; } /* * Found a killable thread. If the signal will be fatal, * then start taking the whole group down immediately. */ if (sig_fatal(p, sig) && !(signal->flags & (SIGNAL_UNKILLABLE | SIGNAL_GROUP_EXIT)) && !sigismember(&t->real_blocked, sig) && (sig == SIGKILL || !t->ptrace)) { /* * This signal will be fatal to the whole group. */ if (!sig_kernel_coredump(sig)) { /* * Start a group exit and wake everybody up. * This way we don't have other threads * running and doing things after a slower * thread has the fatal signal pending. */ signal->flags = SIGNAL_GROUP_EXIT; signal->group_exit_code = sig; signal->group_stop_count = 0; t = p; do { task_clear_jobctl_pending(t, JOBCTL_PENDING_MASK); sigaddset(&t->pending.signal, SIGKILL); signal_wake_up(t, 1); } while_each_thread(p, t); return; } } /* * The signal is already in the shared-pending queue. * Tell the chosen thread to wake up and dequeue it. */ signal_wake_up(t, sig == SIGKILL); return; } static inline int legacy_queue(struct sigpending *signals, int sig) { return (sig < SIGRTMIN) && sigismember(&signals->signal, sig); } #ifdef CONFIG_USER_NS static inline void userns_fixup_signal_uid(struct siginfo *info, struct task_struct *t) { if (current_user_ns() == task_cred_xxx(t, user_ns)) return; if (SI_FROMKERNEL(info)) return; rcu_read_lock(); info->si_uid = from_kuid_munged(task_cred_xxx(t, user_ns), make_kuid(current_user_ns(), info->si_uid)); rcu_read_unlock(); } #else static inline void userns_fixup_signal_uid(struct siginfo *info, struct task_struct *t) { return; } #endif static int __send_signal(int sig, struct siginfo *info, struct task_struct *t, int group, int from_ancestor_ns) { struct sigpending *pending; struct sigqueue *q; int override_rlimit; int ret = 0, result; assert_spin_locked(&t->sighand->siglock); result = TRACE_SIGNAL_IGNORED; if (!prepare_signal(sig, t, from_ancestor_ns || (info == SEND_SIG_FORCED))) goto ret; pending = group ? &t->signal->shared_pending : &t->pending; /* * Short-circuit ignored signals and support queuing * exactly one non-rt signal, so that we can get more * detailed information about the cause of the signal. */ result = TRACE_SIGNAL_ALREADY_PENDING; if (legacy_queue(pending, sig)) goto ret; result = TRACE_SIGNAL_DELIVERED; /* * fast-pathed signals for kernel-internal things like SIGSTOP * or SIGKILL. */ if (info == SEND_SIG_FORCED) goto out_set; /* * Real-time signals must be queued if sent by sigqueue, or * some other real-time mechanism. It is implementation * defined whether kill() does so. We attempt to do so, on * the principle of least surprise, but since kill is not * allowed to fail with EAGAIN when low on memory we just * make sure at least one signal gets delivered and don't * pass on the info struct. */ if (sig < SIGRTMIN) override_rlimit = (is_si_special(info) || info->si_code >= 0); else override_rlimit = 0; q = __sigqueue_alloc(sig, t, GFP_ATOMIC | __GFP_NOTRACK_FALSE_POSITIVE, override_rlimit); if (q) { list_add_tail(&q->list, &pending->list); switch ((unsigned long) info) { case (unsigned long) SEND_SIG_NOINFO: q->info.si_signo = sig; q->info.si_errno = 0; q->info.si_code = SI_USER; q->info.si_pid = task_tgid_nr_ns(current, task_active_pid_ns(t)); q->info.si_uid = from_kuid_munged(current_user_ns(), current_uid()); break; case (unsigned long) SEND_SIG_PRIV: q->info.si_signo = sig; q->info.si_errno = 0; q->info.si_code = SI_KERNEL; q->info.si_pid = 0; q->info.si_uid = 0; break; default: copy_siginfo(&q->info, info); if (from_ancestor_ns) q->info.si_pid = 0; break; } userns_fixup_signal_uid(&q->info, t); } else if (!is_si_special(info)) { if (sig >= SIGRTMIN && info->si_code != SI_USER) { /* * Queue overflow, abort. We may abort if the * signal was rt and sent by user using something * other than kill(). */ result = TRACE_SIGNAL_OVERFLOW_FAIL; ret = -EAGAIN; goto ret; } else { /* * This is a silent loss of information. We still * send the signal, but the *info bits are lost. */ result = TRACE_SIGNAL_LOSE_INFO; } } out_set: signalfd_notify(t, sig); sigaddset(&pending->signal, sig); complete_signal(sig, t, group); ret: trace_signal_generate(sig, info, t, group, result); return ret; } static int send_signal(int sig, struct siginfo *info, struct task_struct *t, int group) { int from_ancestor_ns = 0; #ifdef CONFIG_PID_NS from_ancestor_ns = si_fromuser(info) && !task_pid_nr_ns(current, task_active_pid_ns(t)); #endif return __send_signal(sig, info, t, group, from_ancestor_ns); } static void print_fatal_signal(int signr) { struct pt_regs *regs = signal_pt_regs(); printk(KERN_INFO "%s/%d: potentially unexpected fatal signal %d.\n", current->comm, task_pid_nr(current), signr); #if defined(__i386__) && !defined(__arch_um__) printk(KERN_INFO "code at %08lx: ", regs->ip); { int i; for (i = 0; i < 16; i++) { unsigned char insn; if (get_user(insn, (unsigned char *)(regs->ip + i))) break; printk(KERN_CONT "%02x ", insn); } } printk(KERN_CONT "\n"); #endif preempt_disable(); show_regs(regs); preempt_enable(); } static int __init setup_print_fatal_signals(char *str) { get_option (&str, &print_fatal_signals); return 1; } __setup("print-fatal-signals=", setup_print_fatal_signals); int __group_send_sig_info(int sig, struct siginfo *info, struct task_struct *p) { return send_signal(sig, info, p, 1); } static int specific_send_sig_info(int sig, struct siginfo *info, struct task_struct *t) { return send_signal(sig, info, t, 0); } int do_send_sig_info(int sig, struct siginfo *info, struct task_struct *p, bool group) { unsigned long flags; int ret = -ESRCH; if (lock_task_sighand(p, &flags)) { ret = send_signal(sig, info, p, group); unlock_task_sighand(p, &flags); } return ret; } /* * Force a signal that the process can't ignore: if necessary * we unblock the signal and change any SIG_IGN to SIG_DFL. * * Note: If we unblock the signal, we always reset it to SIG_DFL, * since we do not want to have a signal handler that was blocked * be invoked when user space had explicitly blocked it. * * We don't want to have recursive SIGSEGV's etc, for example, * that is why we also clear SIGNAL_UNKILLABLE. */ int force_sig_info(int sig, struct siginfo *info, struct task_struct *t) { unsigned long int flags; int ret, blocked, ignored; struct k_sigaction *action; spin_lock_irqsave(&t->sighand->siglock, flags); action = &t->sighand->action[sig-1]; ignored = action->sa.sa_handler == SIG_IGN; blocked = sigismember(&t->blocked, sig); if (blocked || ignored) { action->sa.sa_handler = SIG_DFL; if (blocked) { sigdelset(&t->blocked, sig); recalc_sigpending_and_wake(t); } } if (action->sa.sa_handler == SIG_DFL) t->signal->flags &= ~SIGNAL_UNKILLABLE; ret = specific_send_sig_info(sig, info, t); spin_unlock_irqrestore(&t->sighand->siglock, flags); return ret; } /* * Nuke all other threads in the group. */ int zap_other_threads(struct task_struct *p) { struct task_struct *t = p; int count = 0; p->signal->group_stop_count = 0; while_each_thread(p, t) { task_clear_jobctl_pending(t, JOBCTL_PENDING_MASK); count++; /* Don't bother with already dead threads */ if (t->exit_state) continue; sigaddset(&t->pending.signal, SIGKILL); signal_wake_up(t, 1); } return count; } struct sighand_struct *__lock_task_sighand(struct task_struct *tsk, unsigned long *flags) { struct sighand_struct *sighand; for (;;) { local_irq_save(*flags); rcu_read_lock(); sighand = rcu_dereference(tsk->sighand); if (unlikely(sighand == NULL)) { rcu_read_unlock(); local_irq_restore(*flags); break; } spin_lock(&sighand->siglock); if (likely(sighand == tsk->sighand)) { rcu_read_unlock(); break; } spin_unlock(&sighand->siglock); rcu_read_unlock(); local_irq_restore(*flags); } return sighand; } /* * send signal info to all the members of a group */ int group_send_sig_info(int sig, struct siginfo *info, struct task_struct *p) { int ret; rcu_read_lock(); ret = check_kill_permission(sig, info, p); rcu_read_unlock(); if (!ret && sig) ret = do_send_sig_info(sig, info, p, true); return ret; } /* * __kill_pgrp_info() sends a signal to a process group: this is what the tty * control characters do (^C, ^Z etc) * - the caller must hold at least a readlock on tasklist_lock */ int __kill_pgrp_info(int sig, struct siginfo *info, struct pid *pgrp) { struct task_struct *p = NULL; int retval, success; success = 0; retval = -ESRCH; do_each_pid_task(pgrp, PIDTYPE_PGID, p) { int err = group_send_sig_info(sig, info, p); success |= !err; retval = err; } while_each_pid_task(pgrp, PIDTYPE_PGID, p); return success ? 0 : retval; } int kill_pid_info(int sig, struct siginfo *info, struct pid *pid) { int error = -ESRCH; struct task_struct *p; rcu_read_lock(); retry: p = pid_task(pid, PIDTYPE_PID); if (p) { error = group_send_sig_info(sig, info, p); if (unlikely(error == -ESRCH)) /* * The task was unhashed in between, try again. * If it is dead, pid_task() will return NULL, * if we race with de_thread() it will find the * new leader. */ goto retry; } rcu_read_unlock(); return error; } int kill_proc_info(int sig, struct siginfo *info, pid_t pid) { int error; rcu_read_lock(); error = kill_pid_info(sig, info, find_vpid(pid)); rcu_read_unlock(); return error; } static int kill_as_cred_perm(const struct cred *cred, struct task_struct *target) { const struct cred *pcred = __task_cred(target); if (!uid_eq(cred->euid, pcred->suid) && !uid_eq(cred->euid, pcred->uid) && !uid_eq(cred->uid, pcred->suid) && !uid_eq(cred->uid, pcred->uid)) return 0; return 1; } /* like kill_pid_info(), but doesn't use uid/euid of "current" */ int kill_pid_info_as_cred(int sig, struct siginfo *info, struct pid *pid, const struct cred *cred, u32 secid) { int ret = -EINVAL; struct task_struct *p; unsigned long flags; if (!valid_signal(sig)) return ret; rcu_read_lock(); p = pid_task(pid, PIDTYPE_PID); if (!p) { ret = -ESRCH; goto out_unlock; } if (si_fromuser(info) && !kill_as_cred_perm(cred, p)) { ret = -EPERM; goto out_unlock; } ret = security_task_kill(p, info, sig, secid); if (ret) goto out_unlock; if (sig) { if (lock_task_sighand(p, &flags)) { ret = __send_signal(sig, info, p, 1, 0); unlock_task_sighand(p, &flags); } else ret = -ESRCH; } out_unlock: rcu_read_unlock(); return ret; } EXPORT_SYMBOL_GPL(kill_pid_info_as_cred); /* * kill_something_info() interprets pid in interesting ways just like kill(2). * * POSIX specifies that kill(-1,sig) is unspecified, but what we have * is probably wrong. Should make it like BSD or SYSV. */ static int kill_something_info(int sig, struct siginfo *info, pid_t pid) { int ret; if (pid > 0) { rcu_read_lock(); ret = kill_pid_info(sig, info, find_vpid(pid)); rcu_read_unlock(); return ret; } read_lock(&tasklist_lock); if (pid != -1) { ret = __kill_pgrp_info(sig, info, pid ? find_vpid(-pid) : task_pgrp(current)); } else { int retval = 0, count = 0; struct task_struct * p; for_each_process(p) { if (task_pid_vnr(p) > 1 && !same_thread_group(p, current)) { int err = group_send_sig_info(sig, info, p); ++count; if (err != -EPERM) retval = err; } } ret = count ? retval : -ESRCH; } read_unlock(&tasklist_lock); return ret; } /* * These are for backward compatibility with the rest of the kernel source. */ int send_sig_info(int sig, struct siginfo *info, struct task_struct *p) { /* * Make sure legacy kernel users don't send in bad values * (normal paths check this in check_kill_permission). */ if (!valid_signal(sig)) return -EINVAL; return do_send_sig_info(sig, info, p, false); } #define __si_special(priv) \ ((priv) ? SEND_SIG_PRIV : SEND_SIG_NOINFO) int send_sig(int sig, struct task_struct *p, int priv) { return send_sig_info(sig, __si_special(priv), p); } void force_sig(int sig, struct task_struct *p) { force_sig_info(sig, SEND_SIG_PRIV, p); } /* * When things go south during signal handling, we * will force a SIGSEGV. And if the signal that caused * the problem was already a SIGSEGV, we'll want to * make sure we don't even try to deliver the signal.. */ int force_sigsegv(int sig, struct task_struct *p) { if (sig == SIGSEGV) { unsigned long flags; spin_lock_irqsave(&p->sighand->siglock, flags); p->sighand->action[sig - 1].sa.sa_handler = SIG_DFL; spin_unlock_irqrestore(&p->sighand->siglock, flags); } force_sig(SIGSEGV, p); return 0; } int kill_pgrp(struct pid *pid, int sig, int priv) { int ret; read_lock(&tasklist_lock); ret = __kill_pgrp_info(sig, __si_special(priv), pid); read_unlock(&tasklist_lock); return ret; } EXPORT_SYMBOL(kill_pgrp); int kill_pid(struct pid *pid, int sig, int priv) { return kill_pid_info(sig, __si_special(priv), pid); } EXPORT_SYMBOL(kill_pid); /* * These functions support sending signals using preallocated sigqueue * structures. This is needed "because realtime applications cannot * afford to lose notifications of asynchronous events, like timer * expirations or I/O completions". In the case of POSIX Timers * we allocate the sigqueue structure from the timer_create. If this * allocation fails we are able to report the failure to the application * with an EAGAIN error. */ struct sigqueue *sigqueue_alloc(void) { struct sigqueue *q = __sigqueue_alloc(-1, current, GFP_KERNEL, 0); if (q) q->flags |= SIGQUEUE_PREALLOC; return q; } void sigqueue_free(struct sigqueue *q) { unsigned long flags; spinlock_t *lock = &current->sighand->siglock; BUG_ON(!(q->flags & SIGQUEUE_PREALLOC)); /* * We must hold ->siglock while testing q->list * to serialize with collect_signal() or with * __exit_signal()->flush_sigqueue(). */ spin_lock_irqsave(lock, flags); q->flags &= ~SIGQUEUE_PREALLOC; /* * If it is queued it will be freed when dequeued, * like the "regular" sigqueue. */ if (!list_empty(&q->list)) q = NULL; spin_unlock_irqrestore(lock, flags); if (q) __sigqueue_free(q); } int send_sigqueue(struct sigqueue *q, struct task_struct *t, int group) { int sig = q->info.si_signo; struct sigpending *pending; unsigned long flags; int ret, result; BUG_ON(!(q->flags & SIGQUEUE_PREALLOC)); ret = -1; if (!likely(lock_task_sighand(t, &flags))) goto ret; ret = 1; /* the signal is ignored */ result = TRACE_SIGNAL_IGNORED; if (!prepare_signal(sig, t, false)) goto out; ret = 0; if (unlikely(!list_empty(&q->list))) { /* * If an SI_TIMER entry is already queue just increment * the overrun count. */ BUG_ON(q->info.si_code != SI_TIMER); q->info.si_overrun++; result = TRACE_SIGNAL_ALREADY_PENDING; goto out; } q->info.si_overrun = 0; signalfd_notify(t, sig); pending = group ? &t->signal->shared_pending : &t->pending; list_add_tail(&q->list, &pending->list); sigaddset(&pending->signal, sig); complete_signal(sig, t, group); result = TRACE_SIGNAL_DELIVERED; out: trace_signal_generate(sig, &q->info, t, group, result); unlock_task_sighand(t, &flags); ret: return ret; } /* * Let a parent know about the death of a child. * For a stopped/continued status change, use do_notify_parent_cldstop instead. * * Returns true if our parent ignored us and so we've switched to * self-reaping. */ bool do_notify_parent(struct task_struct *tsk, int sig) { struct siginfo info; unsigned long flags; struct sighand_struct *psig; bool autoreap = false; cputime_t utime, stime; BUG_ON(sig == -1); /* do_notify_parent_cldstop should have been called instead. */ BUG_ON(task_is_stopped_or_traced(tsk)); BUG_ON(!tsk->ptrace && (tsk->group_leader != tsk || !thread_group_empty(tsk))); if (sig != SIGCHLD) { /* * This is only possible if parent == real_parent. * Check if it has changed security domain. */ if (tsk->parent_exec_id != tsk->parent->self_exec_id) sig = SIGCHLD; } info.si_signo = sig; info.si_errno = 0; /* * We are under tasklist_lock here so our parent is tied to * us and cannot change. * * task_active_pid_ns will always return the same pid namespace * until a task passes through release_task. * * write_lock() currently calls preempt_disable() which is the * same as rcu_read_lock(), but according to Oleg, this is not * correct to rely on this */ rcu_read_lock(); info.si_pid = task_pid_nr_ns(tsk, task_active_pid_ns(tsk->parent)); info.si_uid = from_kuid_munged(task_cred_xxx(tsk->parent, user_ns), task_uid(tsk)); rcu_read_unlock(); task_cputime(tsk, &utime, &stime); info.si_utime = cputime_to_clock_t(utime + tsk->signal->utime); info.si_stime = cputime_to_clock_t(stime + tsk->signal->stime); info.si_status = tsk->exit_code & 0x7f; if (tsk->exit_code & 0x80) info.si_code = CLD_DUMPED; else if (tsk->exit_code & 0x7f) info.si_code = CLD_KILLED; else { info.si_code = CLD_EXITED; info.si_status = tsk->exit_code >> 8; } psig = tsk->parent->sighand; spin_lock_irqsave(&psig->siglock, flags); if (!tsk->ptrace && sig == SIGCHLD && (psig->action[SIGCHLD-1].sa.sa_handler == SIG_IGN || (psig->action[SIGCHLD-1].sa.sa_flags & SA_NOCLDWAIT))) { /* * We are exiting and our parent doesn't care. POSIX.1 * defines special semantics for setting SIGCHLD to SIG_IGN * or setting the SA_NOCLDWAIT flag: we should be reaped * automatically and not left for our parent's wait4 call. * Rather than having the parent do it as a magic kind of * signal handler, we just set this to tell do_exit that we * can be cleaned up without becoming a zombie. Note that * we still call __wake_up_parent in this case, because a * blocked sys_wait4 might now return -ECHILD. * * Whether we send SIGCHLD or not for SA_NOCLDWAIT * is implementation-defined: we do (if you don't want * it, just use SIG_IGN instead). */ autoreap = true; if (psig->action[SIGCHLD-1].sa.sa_handler == SIG_IGN) sig = 0; } if (valid_signal(sig) && sig) __group_send_sig_info(sig, &info, tsk->parent); __wake_up_parent(tsk, tsk->parent); spin_unlock_irqrestore(&psig->siglock, flags); return autoreap; } /** * do_notify_parent_cldstop - notify parent of stopped/continued state change * @tsk: task reporting the state change * @for_ptracer: the notification is for ptracer * @why: CLD_{CONTINUED|STOPPED|TRAPPED} to report * * Notify @tsk's parent that the stopped/continued state has changed. If * @for_ptracer is %false, @tsk's group leader notifies to its real parent. * If %true, @tsk reports to @tsk->parent which should be the ptracer. * * CONTEXT: * Must be called with tasklist_lock at least read locked. */ static void do_notify_parent_cldstop(struct task_struct *tsk, bool for_ptracer, int why) { struct siginfo info; unsigned long flags; struct task_struct *parent; struct sighand_struct *sighand; cputime_t utime, stime; if (for_ptracer) { parent = tsk->parent; } else { tsk = tsk->group_leader; parent = tsk->real_parent; } info.si_signo = SIGCHLD; info.si_errno = 0; /* * see comment in do_notify_parent() about the following 4 lines */ rcu_read_lock(); info.si_pid = task_pid_nr_ns(tsk, task_active_pid_ns(parent)); info.si_uid = from_kuid_munged(task_cred_xxx(parent, user_ns), task_uid(tsk)); rcu_read_unlock(); task_cputime(tsk, &utime, &stime); info.si_utime = cputime_to_clock_t(utime); info.si_stime = cputime_to_clock_t(stime); info.si_code = why; switch (why) { case CLD_CONTINUED: info.si_status = SIGCONT; break; case CLD_STOPPED: info.si_status = tsk->signal->group_exit_code & 0x7f; break; case CLD_TRAPPED: info.si_status = tsk->exit_code & 0x7f; break; default: BUG(); } sighand = parent->sighand; spin_lock_irqsave(&sighand->siglock, flags); if (sighand->action[SIGCHLD-1].sa.sa_handler != SIG_IGN && !(sighand->action[SIGCHLD-1].sa.sa_flags & SA_NOCLDSTOP)) __group_send_sig_info(SIGCHLD, &info, parent); /* * Even if SIGCHLD is not generated, we must wake up wait4 calls. */ __wake_up_parent(tsk, parent); spin_unlock_irqrestore(&sighand->siglock, flags); } static inline int may_ptrace_stop(void) { if (!likely(current->ptrace)) return 0; /* * Are we in the middle of do_coredump? * If so and our tracer is also part of the coredump stopping * is a deadlock situation, and pointless because our tracer * is dead so don't allow us to stop. * If SIGKILL was already sent before the caller unlocked * ->siglock we must see ->core_state != NULL. Otherwise it * is safe to enter schedule(). * * This is almost outdated, a task with the pending SIGKILL can't * block in TASK_TRACED. But PTRACE_EVENT_EXIT can be reported * after SIGKILL was already dequeued. */ if (unlikely(current->mm->core_state) && unlikely(current->mm == current->parent->mm)) return 0; return 1; } /* * Return non-zero if there is a SIGKILL that should be waking us up. * Called with the siglock held. */ static int sigkill_pending(struct task_struct *tsk) { return sigismember(&tsk->pending.signal, SIGKILL) || sigismember(&tsk->signal->shared_pending.signal, SIGKILL); } /* * This must be called with current->sighand->siglock held. * * This should be the path for all ptrace stops. * We always set current->last_siginfo while stopped here. * That makes it a way to test a stopped process for * being ptrace-stopped vs being job-control-stopped. * * If we actually decide not to stop at all because the tracer * is gone, we keep current->exit_code unless clear_code. */ static void ptrace_stop(int exit_code, int why, int clear_code, siginfo_t *info) __releases(&current->sighand->siglock) __acquires(&current->sighand->siglock) { bool gstop_done = false; if (arch_ptrace_stop_needed(exit_code, info)) { /* * The arch code has something special to do before a * ptrace stop. This is allowed to block, e.g. for faults * on user stack pages. We can't keep the siglock while * calling arch_ptrace_stop, so we must release it now. * To preserve proper semantics, we must do this before * any signal bookkeeping like checking group_stop_count. * Meanwhile, a SIGKILL could come in before we retake the * siglock. That must prevent us from sleeping in TASK_TRACED. * So after regaining the lock, we must check for SIGKILL. */ spin_unlock_irq(&current->sighand->siglock); arch_ptrace_stop(exit_code, info); spin_lock_irq(&current->sighand->siglock); if (sigkill_pending(current)) return; } /* * We're committing to trapping. TRACED should be visible before * TRAPPING is cleared; otherwise, the tracer might fail do_wait(). * Also, transition to TRACED and updates to ->jobctl should be * atomic with respect to siglock and should be done after the arch * hook as siglock is released and regrabbed across it. */ set_current_state(TASK_TRACED); current->last_siginfo = info; current->exit_code = exit_code; /* * If @why is CLD_STOPPED, we're trapping to participate in a group * stop. Do the bookkeeping. Note that if SIGCONT was delievered * across siglock relocks since INTERRUPT was scheduled, PENDING * could be clear now. We act as if SIGCONT is received after * TASK_TRACED is entered - ignore it. */ if (why == CLD_STOPPED && (current->jobctl & JOBCTL_STOP_PENDING)) gstop_done = task_participate_group_stop(current); /* any trap clears pending STOP trap, STOP trap clears NOTIFY */ task_clear_jobctl_pending(current, JOBCTL_TRAP_STOP); if (info && info->si_code >> 8 == PTRACE_EVENT_STOP) task_clear_jobctl_pending(current, JOBCTL_TRAP_NOTIFY); /* entering a trap, clear TRAPPING */ task_clear_jobctl_trapping(current); spin_unlock_irq(&current->sighand->siglock); read_lock(&tasklist_lock); if (may_ptrace_stop()) { /* * Notify parents of the stop. * * While ptraced, there are two parents - the ptracer and * the real_parent of the group_leader. The ptracer should * know about every stop while the real parent is only * interested in the completion of group stop. The states * for the two don't interact with each other. Notify * separately unless they're gonna be duplicates. */ do_notify_parent_cldstop(current, true, why); if (gstop_done && ptrace_reparented(current)) do_notify_parent_cldstop(current, false, why); /* * Don't want to allow preemption here, because * sys_ptrace() needs this task to be inactive. * * XXX: implement read_unlock_no_resched(). */ preempt_disable(); read_unlock(&tasklist_lock); preempt_enable_no_resched(); freezable_schedule(); } else { /* * By the time we got the lock, our tracer went away. * Don't drop the lock yet, another tracer may come. * * If @gstop_done, the ptracer went away between group stop * completion and here. During detach, it would have set * JOBCTL_STOP_PENDING on us and we'll re-enter * TASK_STOPPED in do_signal_stop() on return, so notifying * the real parent of the group stop completion is enough. */ if (gstop_done) do_notify_parent_cldstop(current, false, why); /* tasklist protects us from ptrace_freeze_traced() */ __set_current_state(TASK_RUNNING); if (clear_code) current->exit_code = 0; read_unlock(&tasklist_lock); } /* * We are back. Now reacquire the siglock before touching * last_siginfo, so that we are sure to have synchronized with * any signal-sending on another CPU that wants to examine it. */ spin_lock_irq(&current->sighand->siglock); current->last_siginfo = NULL; /* LISTENING can be set only during STOP traps, clear it */ current->jobctl &= ~JOBCTL_LISTENING; /* * Queued signals ignored us while we were stopped for tracing. * So check for any that we should take before resuming user mode. * This sets TIF_SIGPENDING, but never clears it. */ recalc_sigpending_tsk(current); } static void ptrace_do_notify(int signr, int exit_code, int why) { siginfo_t info; memset(&info, 0, sizeof info); info.si_signo = signr; info.si_code = exit_code; info.si_pid = task_pid_vnr(current); info.si_uid = from_kuid_munged(current_user_ns(), current_uid()); /* Let the debugger run. */ ptrace_stop(exit_code, why, 1, &info); } void ptrace_notify(int exit_code) { BUG_ON((exit_code & (0x7f | ~0xffff)) != SIGTRAP); if (unlikely(current->task_works)) task_work_run(); spin_lock_irq(&current->sighand->siglock); ptrace_do_notify(SIGTRAP, exit_code, CLD_TRAPPED); spin_unlock_irq(&current->sighand->siglock); } /** * do_signal_stop - handle group stop for SIGSTOP and other stop signals * @signr: signr causing group stop if initiating * * If %JOBCTL_STOP_PENDING is not set yet, initiate group stop with @signr * and participate in it. If already set, participate in the existing * group stop. If participated in a group stop (and thus slept), %true is * returned with siglock released. * * If ptraced, this function doesn't handle stop itself. Instead, * %JOBCTL_TRAP_STOP is scheduled and %false is returned with siglock * untouched. The caller must ensure that INTERRUPT trap handling takes * places afterwards. * * CONTEXT: * Must be called with @current->sighand->siglock held, which is released * on %true return. * * RETURNS: * %false if group stop is already cancelled or ptrace trap is scheduled. * %true if participated in group stop. */ static bool do_signal_stop(int signr) __releases(&current->sighand->siglock) { struct signal_struct *sig = current->signal; if (!(current->jobctl & JOBCTL_STOP_PENDING)) { unsigned int gstop = JOBCTL_STOP_PENDING | JOBCTL_STOP_CONSUME; struct task_struct *t; /* signr will be recorded in task->jobctl for retries */ WARN_ON_ONCE(signr & ~JOBCTL_STOP_SIGMASK); if (!likely(current->jobctl & JOBCTL_STOP_DEQUEUED) || unlikely(signal_group_exit(sig))) return false; /* * There is no group stop already in progress. We must * initiate one now. * * While ptraced, a task may be resumed while group stop is * still in effect and then receive a stop signal and * initiate another group stop. This deviates from the * usual behavior as two consecutive stop signals can't * cause two group stops when !ptraced. That is why we * also check !task_is_stopped(t) below. * * The condition can be distinguished by testing whether * SIGNAL_STOP_STOPPED is already set. Don't generate * group_exit_code in such case. * * This is not necessary for SIGNAL_STOP_CONTINUED because * an intervening stop signal is required to cause two * continued events regardless of ptrace. */ if (!(sig->flags & SIGNAL_STOP_STOPPED)) sig->group_exit_code = signr; sig->group_stop_count = 0; if (task_set_jobctl_pending(current, signr | gstop)) sig->group_stop_count++; for (t = next_thread(current); t != current; t = next_thread(t)) { /* * Setting state to TASK_STOPPED for a group * stop is always done with the siglock held, * so this check has no races. */ if (!task_is_stopped(t) && task_set_jobctl_pending(t, signr | gstop)) { sig->group_stop_count++; if (likely(!(t->ptrace & PT_SEIZED))) signal_wake_up(t, 0); else ptrace_trap_notify(t); } } } if (likely(!current->ptrace)) { int notify = 0; /* * If there are no other threads in the group, or if there * is a group stop in progress and we are the last to stop, * report to the parent. */ if (task_participate_group_stop(current)) notify = CLD_STOPPED; __set_current_state(TASK_STOPPED); spin_unlock_irq(&current->sighand->siglock); /* * Notify the parent of the group stop completion. Because * we're not holding either the siglock or tasklist_lock * here, ptracer may attach inbetween; however, this is for * group stop and should always be delivered to the real * parent of the group leader. The new ptracer will get * its notification when this task transitions into * TASK_TRACED. */ if (notify) { read_lock(&tasklist_lock); do_notify_parent_cldstop(current, false, notify); read_unlock(&tasklist_lock); } /* Now we don't run again until woken by SIGCONT or SIGKILL */ freezable_schedule(); return true; } else { /* * While ptraced, group stop is handled by STOP trap. * Schedule it and let the caller deal with it. */ task_set_jobctl_pending(current, JOBCTL_TRAP_STOP); return false; } } /** * do_jobctl_trap - take care of ptrace jobctl traps * * When PT_SEIZED, it's used for both group stop and explicit * SEIZE/INTERRUPT traps. Both generate PTRACE_EVENT_STOP trap with * accompanying siginfo. If stopped, lower eight bits of exit_code contain * the stop signal; otherwise, %SIGTRAP. * * When !PT_SEIZED, it's used only for group stop trap with stop signal * number as exit_code and no siginfo. * * CONTEXT: * Must be called with @current->sighand->siglock held, which may be * released and re-acquired before returning with intervening sleep. */ static void do_jobctl_trap(void) { struct signal_struct *signal = current->signal; int signr = current->jobctl & JOBCTL_STOP_SIGMASK; if (current->ptrace & PT_SEIZED) { if (!signal->group_stop_count && !(signal->flags & SIGNAL_STOP_STOPPED)) signr = SIGTRAP; WARN_ON_ONCE(!signr); ptrace_do_notify(signr, signr | (PTRACE_EVENT_STOP << 8), CLD_STOPPED); } else { WARN_ON_ONCE(!signr); ptrace_stop(signr, CLD_STOPPED, 0, NULL); current->exit_code = 0; } } static int ptrace_signal(int signr, siginfo_t *info) { ptrace_signal_deliver(); /* * We do not check sig_kernel_stop(signr) but set this marker * unconditionally because we do not know whether debugger will * change signr. This flag has no meaning unless we are going * to stop after return from ptrace_stop(). In this case it will * be checked in do_signal_stop(), we should only stop if it was * not cleared by SIGCONT while we were sleeping. See also the * comment in dequeue_signal(). */ current->jobctl |= JOBCTL_STOP_DEQUEUED; ptrace_stop(signr, CLD_TRAPPED, 0, info); /* We're back. Did the debugger cancel the sig? */ signr = current->exit_code; if (signr == 0) return signr; current->exit_code = 0; /* * Update the siginfo structure if the signal has * changed. If the debugger wanted something * specific in the siginfo structure then it should * have updated *info via PTRACE_SETSIGINFO. */ if (signr != info->si_signo) { info->si_signo = signr; info->si_errno = 0; info->si_code = SI_USER; rcu_read_lock(); info->si_pid = task_pid_vnr(current->parent); info->si_uid = from_kuid_munged(current_user_ns(), task_uid(current->parent)); rcu_read_unlock(); } /* If the (new) signal is now blocked, requeue it. */ if (sigismember(&current->blocked, signr)) { specific_send_sig_info(signr, info, current); signr = 0; } return signr; } int get_signal_to_deliver(siginfo_t *info, struct k_sigaction *return_ka, struct pt_regs *regs, void *cookie) { struct sighand_struct *sighand = current->sighand; struct signal_struct *signal = current->signal; int signr; if (unlikely(current->task_works)) task_work_run(); if (unlikely(uprobe_deny_signal())) return 0; /* * Do this once, we can't return to user-mode if freezing() == T. * do_signal_stop() and ptrace_stop() do freezable_schedule() and * thus do not need another check after return. */ try_to_freeze(); relock: spin_lock_irq(&sighand->siglock); /* * Every stopped thread goes here after wakeup. Check to see if * we should notify the parent, prepare_signal(SIGCONT) encodes * the CLD_ si_code into SIGNAL_CLD_MASK bits. */ if (unlikely(signal->flags & SIGNAL_CLD_MASK)) { int why; if (signal->flags & SIGNAL_CLD_CONTINUED) why = CLD_CONTINUED; else why = CLD_STOPPED; signal->flags &= ~SIGNAL_CLD_MASK; spin_unlock_irq(&sighand->siglock); /* * Notify the parent that we're continuing. This event is * always per-process and doesn't make whole lot of sense * for ptracers, who shouldn't consume the state via * wait(2) either, but, for backward compatibility, notify * the ptracer of the group leader too unless it's gonna be * a duplicate. */ read_lock(&tasklist_lock); do_notify_parent_cldstop(current, false, why); if (ptrace_reparented(current->group_leader)) do_notify_parent_cldstop(current->group_leader, true, why); read_unlock(&tasklist_lock); goto relock; } for (;;) { struct k_sigaction *ka; if (unlikely(current->jobctl & JOBCTL_STOP_PENDING) && do_signal_stop(0)) goto relock; if (unlikely(current->jobctl & JOBCTL_TRAP_MASK)) { do_jobctl_trap(); spin_unlock_irq(&sighand->siglock); goto relock; } signr = dequeue_signal(current, &current->blocked, info); if (!signr) break; /* will return 0 */ if (unlikely(current->ptrace) && signr != SIGKILL) { signr = ptrace_signal(signr, info); if (!signr) continue; } ka = &sighand->action[signr-1]; /* Trace actually delivered signals. */ trace_signal_deliver(signr, info, ka); if (ka->sa.sa_handler == SIG_IGN) /* Do nothing. */ continue; if (ka->sa.sa_handler != SIG_DFL) { /* Run the handler. */ *return_ka = *ka; if (ka->sa.sa_flags & SA_ONESHOT) ka->sa.sa_handler = SIG_DFL; break; /* will return non-zero "signr" value */ } /* * Now we are doing the default action for this signal. */ if (sig_kernel_ignore(signr)) /* Default is nothing. */ continue; /* * Global init gets no signals it doesn't want. * Container-init gets no signals it doesn't want from same * container. * * Note that if global/container-init sees a sig_kernel_only() * signal here, the signal must have been generated internally * or must have come from an ancestor namespace. In either * case, the signal cannot be dropped. */ if (unlikely(signal->flags & SIGNAL_UNKILLABLE) && !sig_kernel_only(signr)) continue; if (sig_kernel_stop(signr)) { /* * The default action is to stop all threads in * the thread group. The job control signals * do nothing in an orphaned pgrp, but SIGSTOP * always works. Note that siglock needs to be * dropped during the call to is_orphaned_pgrp() * because of lock ordering with tasklist_lock. * This allows an intervening SIGCONT to be posted. * We need to check for that and bail out if necessary. */ if (signr != SIGSTOP) { spin_unlock_irq(&sighand->siglock); /* signals can be posted during this window */ if (is_current_pgrp_orphaned()) goto relock; spin_lock_irq(&sighand->siglock); } if (likely(do_signal_stop(info->si_signo))) { /* It released the siglock. */ goto relock; } /* * We didn't actually stop, due to a race * with SIGCONT or something like that. */ continue; } spin_unlock_irq(&sighand->siglock); /* * Anything else is fatal, maybe with a core dump. */ current->flags |= PF_SIGNALED; if (sig_kernel_coredump(signr)) { if (print_fatal_signals) print_fatal_signal(info->si_signo); /* * If it was able to dump core, this kills all * other threads in the group and synchronizes with * their demise. If we lost the race with another * thread getting here, it set group_exit_code * first and our do_group_exit call below will use * that value and ignore the one we pass it. */ do_coredump(info); } /* * Death signals, no core dump. */ do_group_exit(info->si_signo); /* NOTREACHED */ } spin_unlock_irq(&sighand->siglock); return signr; } /** * signal_delivered - * @sig: number of signal being delivered * @info: siginfo_t of signal being delivered * @ka: sigaction setting that chose the handler * @regs: user register state * @stepping: nonzero if debugger single-step or block-step in use * * This function should be called when a signal has succesfully been * delivered. It updates the blocked signals accordingly (@ka->sa.sa_mask * is always blocked, and the signal itself is blocked unless %SA_NODEFER * is set in @ka->sa.sa_flags. Tracing is notified. */ void signal_delivered(int sig, siginfo_t *info, struct k_sigaction *ka, struct pt_regs *regs, int stepping) { sigset_t blocked; /* A signal was successfully delivered, and the saved sigmask was stored on the signal frame, and will be restored by sigreturn. So we can simply clear the restore sigmask flag. */ clear_restore_sigmask(); sigorsets(&blocked, &current->blocked, &ka->sa.sa_mask); if (!(ka->sa.sa_flags & SA_NODEFER)) sigaddset(&blocked, sig); set_current_blocked(&blocked); tracehook_signal_handler(sig, info, ka, regs, stepping); } void signal_setup_done(int failed, struct ksignal *ksig, int stepping) { if (failed) force_sigsegv(ksig->sig, current); else signal_delivered(ksig->sig, &ksig->info, &ksig->ka, signal_pt_regs(), stepping); } /* * It could be that complete_signal() picked us to notify about the * group-wide signal. Other threads should be notified now to take * the shared signals in @which since we will not. */ static void retarget_shared_pending(struct task_struct *tsk, sigset_t *which) { sigset_t retarget; struct task_struct *t; sigandsets(&retarget, &tsk->signal->shared_pending.signal, which); if (sigisemptyset(&retarget)) return; t = tsk; while_each_thread(tsk, t) { if (t->flags & PF_EXITING) continue; if (!has_pending_signals(&retarget, &t->blocked)) continue; /* Remove the signals this thread can handle. */ sigandsets(&retarget, &retarget, &t->blocked); if (!signal_pending(t)) signal_wake_up(t, 0); if (sigisemptyset(&retarget)) break; } } void exit_signals(struct task_struct *tsk) { int group_stop = 0; sigset_t unblocked; /* * @tsk is about to have PF_EXITING set - lock out users which * expect stable threadgroup. */ threadgroup_change_begin(tsk); if (thread_group_empty(tsk) || signal_group_exit(tsk->signal)) { tsk->flags |= PF_EXITING; threadgroup_change_end(tsk); return; } spin_lock_irq(&tsk->sighand->siglock); /* * From now this task is not visible for group-wide signals, * see wants_signal(), do_signal_stop(). */ tsk->flags |= PF_EXITING; threadgroup_change_end(tsk); if (!signal_pending(tsk)) goto out; unblocked = tsk->blocked; signotset(&unblocked); retarget_shared_pending(tsk, &unblocked); if (unlikely(tsk->jobctl & JOBCTL_STOP_PENDING) && task_participate_group_stop(tsk)) group_stop = CLD_STOPPED; out: spin_unlock_irq(&tsk->sighand->siglock); /* * If group stop has completed, deliver the notification. This * should always go to the real parent of the group leader. */ if (unlikely(group_stop)) { read_lock(&tasklist_lock); do_notify_parent_cldstop(tsk, false, group_stop); read_unlock(&tasklist_lock); } } EXPORT_SYMBOL(recalc_sigpending); EXPORT_SYMBOL_GPL(dequeue_signal); EXPORT_SYMBOL(flush_signals); EXPORT_SYMBOL(force_sig); EXPORT_SYMBOL(send_sig); EXPORT_SYMBOL(send_sig_info); EXPORT_SYMBOL(sigprocmask); EXPORT_SYMBOL(block_all_signals); EXPORT_SYMBOL(unblock_all_signals); /* * System call entry points. */ /** * sys_restart_syscall - restart a system call */ SYSCALL_DEFINE0(restart_syscall) { struct restart_block *restart = &current_thread_info()->restart_block; return restart->fn(restart); } long do_no_restart_syscall(struct restart_block *param) { return -EINTR; } static void __set_task_blocked(struct task_struct *tsk, const sigset_t *newset) { if (signal_pending(tsk) && !thread_group_empty(tsk)) { sigset_t newblocked; /* A set of now blocked but previously unblocked signals. */ sigandnsets(&newblocked, newset, &current->blocked); retarget_shared_pending(tsk, &newblocked); } tsk->blocked = *newset; recalc_sigpending(); } /** * set_current_blocked - change current->blocked mask * @newset: new mask * * It is wrong to change ->blocked directly, this helper should be used * to ensure the process can't miss a shared signal we are going to block. */ void set_current_blocked(sigset_t *newset) { sigdelsetmask(newset, sigmask(SIGKILL) | sigmask(SIGSTOP)); __set_current_blocked(newset); } void __set_current_blocked(const sigset_t *newset) { struct task_struct *tsk = current; spin_lock_irq(&tsk->sighand->siglock); __set_task_blocked(tsk, newset); spin_unlock_irq(&tsk->sighand->siglock); } /* * This is also useful for kernel threads that want to temporarily * (or permanently) block certain signals. * * NOTE! Unlike the user-mode sys_sigprocmask(), the kernel * interface happily blocks "unblockable" signals like SIGKILL * and friends. */ int sigprocmask(int how, sigset_t *set, sigset_t *oldset) { struct task_struct *tsk = current; sigset_t newset; /* Lockless, only current can change ->blocked, never from irq */ if (oldset) *oldset = tsk->blocked; switch (how) { case SIG_BLOCK: sigorsets(&newset, &tsk->blocked, set); break; case SIG_UNBLOCK: sigandnsets(&newset, &tsk->blocked, set); break; case SIG_SETMASK: newset = *set; break; default: return -EINVAL; } __set_current_blocked(&newset); return 0; } /** * sys_rt_sigprocmask - change the list of currently blocked signals * @how: whether to add, remove, or set signals * @nset: stores pending signals * @oset: previous value of signal mask if non-null * @sigsetsize: size of sigset_t type */ SYSCALL_DEFINE4(rt_sigprocmask, int, how, sigset_t __user *, nset, sigset_t __user *, oset, size_t, sigsetsize) { sigset_t old_set, new_set; int error; /* XXX: Don't preclude handling different sized sigset_t's. */ if (sigsetsize != sizeof(sigset_t)) return -EINVAL; old_set = current->blocked; if (nset) { if (copy_from_user(&new_set, nset, sizeof(sigset_t))) return -EFAULT; sigdelsetmask(&new_set, sigmask(SIGKILL)|sigmask(SIGSTOP)); error = sigprocmask(how, &new_set, NULL); if (error) return error; } if (oset) { if (copy_to_user(oset, &old_set, sizeof(sigset_t))) return -EFAULT; } return 0; } #ifdef CONFIG_COMPAT COMPAT_SYSCALL_DEFINE4(rt_sigprocmask, int, how, compat_sigset_t __user *, nset, compat_sigset_t __user *, oset, compat_size_t, sigsetsize) { #ifdef __BIG_ENDIAN sigset_t old_set = current->blocked; /* XXX: Don't preclude handling different sized sigset_t's. */ if (sigsetsize != sizeof(sigset_t)) return -EINVAL; if (nset) { compat_sigset_t new32; sigset_t new_set; int error; if (copy_from_user(&new32, nset, sizeof(compat_sigset_t))) return -EFAULT; sigset_from_compat(&new_set, &new32); sigdelsetmask(&new_set, sigmask(SIGKILL)|sigmask(SIGSTOP)); error = sigprocmask(how, &new_set, NULL); if (error) return error; } if (oset) { compat_sigset_t old32; sigset_to_compat(&old32, &old_set); if (copy_to_user(oset, &old32, sizeof(compat_sigset_t))) return -EFAULT; } return 0; #else return sys_rt_sigprocmask(how, (sigset_t __user *)nset, (sigset_t __user *)oset, sigsetsize); #endif } #endif static int do_sigpending(void *set, unsigned long sigsetsize) { if (sigsetsize > sizeof(sigset_t)) return -EINVAL; spin_lock_irq(&current->sighand->siglock); sigorsets(set, &current->pending.signal, &current->signal->shared_pending.signal); spin_unlock_irq(&current->sighand->siglock); /* Outside the lock because only this thread touches it. */ sigandsets(set, &current->blocked, set); return 0; } /** * sys_rt_sigpending - examine a pending signal that has been raised * while blocked * @uset: stores pending signals * @sigsetsize: size of sigset_t type or larger */ SYSCALL_DEFINE2(rt_sigpending, sigset_t __user *, uset, size_t, sigsetsize) { sigset_t set; int err = do_sigpending(&set, sigsetsize); if (!err && copy_to_user(uset, &set, sigsetsize)) err = -EFAULT; return err; } #ifdef CONFIG_COMPAT COMPAT_SYSCALL_DEFINE2(rt_sigpending, compat_sigset_t __user *, uset, compat_size_t, sigsetsize) { #ifdef __BIG_ENDIAN sigset_t set; int err = do_sigpending(&set, sigsetsize); if (!err) { compat_sigset_t set32; sigset_to_compat(&set32, &set); /* we can get here only if sigsetsize <= sizeof(set) */ if (copy_to_user(uset, &set32, sigsetsize)) err = -EFAULT; } return err; #else return sys_rt_sigpending((sigset_t __user *)uset, sigsetsize); #endif } #endif #ifndef HAVE_ARCH_COPY_SIGINFO_TO_USER int copy_siginfo_to_user(siginfo_t __user *to, siginfo_t *from) { int err; if (!access_ok (VERIFY_WRITE, to, sizeof(siginfo_t))) return -EFAULT; if (from->si_code < 0) return __copy_to_user(to, from, sizeof(siginfo_t)) ? -EFAULT : 0; /* * If you change siginfo_t structure, please be sure * this code is fixed accordingly. * Please remember to update the signalfd_copyinfo() function * inside fs/signalfd.c too, in case siginfo_t changes. * It should never copy any pad contained in the structure * to avoid security leaks, but must copy the generic * 3 ints plus the relevant union member. */ err = __put_user(from->si_signo, &to->si_signo); err |= __put_user(from->si_errno, &to->si_errno); err |= __put_user((short)from->si_code, &to->si_code); switch (from->si_code & __SI_MASK) { case __SI_KILL: err |= __put_user(from->si_pid, &to->si_pid); err |= __put_user(from->si_uid, &to->si_uid); break; case __SI_TIMER: err |= __put_user(from->si_tid, &to->si_tid); err |= __put_user(from->si_overrun, &to->si_overrun); err |= __put_user(from->si_ptr, &to->si_ptr); break; case __SI_POLL: err |= __put_user(from->si_band, &to->si_band); err |= __put_user(from->si_fd, &to->si_fd); break; case __SI_FAULT: err |= __put_user(from->si_addr, &to->si_addr); #ifdef __ARCH_SI_TRAPNO err |= __put_user(from->si_trapno, &to->si_trapno); #endif #ifdef BUS_MCEERR_AO /* * Other callers might not initialize the si_lsb field, * so check explicitly for the right codes here. */ if (from->si_code == BUS_MCEERR_AR || from->si_code == BUS_MCEERR_AO) err |= __put_user(from->si_addr_lsb, &to->si_addr_lsb); #endif break; case __SI_CHLD: err |= __put_user(from->si_pid, &to->si_pid); err |= __put_user(from->si_uid, &to->si_uid); err |= __put_user(from->si_status, &to->si_status); err |= __put_user(from->si_utime, &to->si_utime); err |= __put_user(from->si_stime, &to->si_stime); break; case __SI_RT: /* This is not generated by the kernel as of now. */ case __SI_MESGQ: /* But this is */ err |= __put_user(from->si_pid, &to->si_pid); err |= __put_user(from->si_uid, &to->si_uid); err |= __put_user(from->si_ptr, &to->si_ptr); break; #ifdef __ARCH_SIGSYS case __SI_SYS: err |= __put_user(from->si_call_addr, &to->si_call_addr); err |= __put_user(from->si_syscall, &to->si_syscall); err |= __put_user(from->si_arch, &to->si_arch); break; #endif default: /* this is just in case for now ... */ err |= __put_user(from->si_pid, &to->si_pid); err |= __put_user(from->si_uid, &to->si_uid); break; } return err; } #endif /** * do_sigtimedwait - wait for queued signals specified in @which * @which: queued signals to wait for * @info: if non-null, the signal's siginfo is returned here * @ts: upper bound on process time suspension */ int do_sigtimedwait(const sigset_t *which, siginfo_t *info, const struct timespec *ts) { struct task_struct *tsk = current; long timeout = MAX_SCHEDULE_TIMEOUT; sigset_t mask = *which; int sig; if (ts) { if (!timespec_valid(ts)) return -EINVAL; timeout = timespec_to_jiffies(ts); /* * We can be close to the next tick, add another one * to ensure we will wait at least the time asked for. */ if (ts->tv_sec || ts->tv_nsec) timeout++; } /* * Invert the set of allowed signals to get those we want to block. */ sigdelsetmask(&mask, sigmask(SIGKILL) | sigmask(SIGSTOP)); signotset(&mask); spin_lock_irq(&tsk->sighand->siglock); sig = dequeue_signal(tsk, &mask, info); if (!sig && timeout) { /* * None ready, temporarily unblock those we're interested * while we are sleeping in so that we'll be awakened when * they arrive. Unblocking is always fine, we can avoid * set_current_blocked(). */ tsk->real_blocked = tsk->blocked; sigandsets(&tsk->blocked, &tsk->blocked, &mask); recalc_sigpending(); spin_unlock_irq(&tsk->sighand->siglock); timeout = schedule_timeout_interruptible(timeout); spin_lock_irq(&tsk->sighand->siglock); __set_task_blocked(tsk, &tsk->real_blocked); siginitset(&tsk->real_blocked, 0); sig = dequeue_signal(tsk, &mask, info); } spin_unlock_irq(&tsk->sighand->siglock); if (sig) return sig; return timeout ? -EINTR : -EAGAIN; } /** * sys_rt_sigtimedwait - synchronously wait for queued signals specified * in @uthese * @uthese: queued signals to wait for * @uinfo: if non-null, the signal's siginfo is returned here * @uts: upper bound on process time suspension * @sigsetsize: size of sigset_t type */ SYSCALL_DEFINE4(rt_sigtimedwait, const sigset_t __user *, uthese, siginfo_t __user *, uinfo, const struct timespec __user *, uts, size_t, sigsetsize) { sigset_t these; struct timespec ts; siginfo_t info; int ret; /* XXX: Don't preclude handling different sized sigset_t's. */ if (sigsetsize != sizeof(sigset_t)) return -EINVAL; if (copy_from_user(&these, uthese, sizeof(these))) return -EFAULT; if (uts) { if (copy_from_user(&ts, uts, sizeof(ts))) return -EFAULT; } ret = do_sigtimedwait(&these, &info, uts ? &ts : NULL); if (ret > 0 && uinfo) { if (copy_siginfo_to_user(uinfo, &info)) ret = -EFAULT; } return ret; } /** * sys_kill - send a signal to a process * @pid: the PID of the process * @sig: signal to be sent */ SYSCALL_DEFINE2(kill, pid_t, pid, int, sig) { struct siginfo info; info.si_signo = sig; info.si_errno = 0; info.si_code = SI_USER; info.si_pid = task_tgid_vnr(current); info.si_uid = from_kuid_munged(current_user_ns(), current_uid()); return kill_something_info(sig, &info, pid); } static int do_send_specific(pid_t tgid, pid_t pid, int sig, struct siginfo *info) { struct task_struct *p; int error = -ESRCH; rcu_read_lock(); p = find_task_by_vpid(pid); if (p && (tgid <= 0 || task_tgid_vnr(p) == tgid)) { error = check_kill_permission(sig, info, p); /* * The null signal is a permissions and process existence * probe. No signal is actually delivered. */ if (!error && sig) { error = do_send_sig_info(sig, info, p, false); /* * If lock_task_sighand() failed we pretend the task * dies after receiving the signal. The window is tiny, * and the signal is private anyway. */ if (unlikely(error == -ESRCH)) error = 0; } } rcu_read_unlock(); return error; } static int do_tkill(pid_t tgid, pid_t pid, int sig) { struct siginfo info; info.si_signo = sig; info.si_errno = 0; info.si_code = SI_TKILL; info.si_pid = task_tgid_vnr(current); info.si_uid = from_kuid_munged(current_user_ns(), current_uid()); return do_send_specific(tgid, pid, sig, &info); } /** * sys_tgkill - send signal to one specific thread * @tgid: the thread group ID of the thread * @pid: the PID of the thread * @sig: signal to be sent * * This syscall also checks the @tgid and returns -ESRCH even if the PID * exists but it's not belonging to the target process anymore. This * method solves the problem of threads exiting and PIDs getting reused. */ SYSCALL_DEFINE3(tgkill, pid_t, tgid, pid_t, pid, int, sig) { /* This is only valid for single tasks */ if (pid <= 0 || tgid <= 0) return -EINVAL; return do_tkill(tgid, pid, sig); } /** * sys_tkill - send signal to one specific task * @pid: the PID of the task * @sig: signal to be sent * * Send a signal to only one task, even if it's a CLONE_THREAD task. */ SYSCALL_DEFINE2(tkill, pid_t, pid, int, sig) { /* This is only valid for single tasks */ if (pid <= 0) return -EINVAL; return do_tkill(0, pid, sig); } static int do_rt_sigqueueinfo(pid_t pid, int sig, siginfo_t *info) { /* Not even root can pretend to send signals from the kernel. * Nor can they impersonate a kill()/tgkill(), which adds source info. */ if ((info->si_code >= 0 || info->si_code == SI_TKILL) && (task_pid_vnr(current) != pid)) { /* We used to allow any < 0 si_code */ WARN_ON_ONCE(info->si_code < 0); return -EPERM; } info->si_signo = sig; /* POSIX.1b doesn't mention process groups. */ return kill_proc_info(sig, info, pid); } /** * sys_rt_sigqueueinfo - send signal information to a signal * @pid: the PID of the thread * @sig: signal to be sent * @uinfo: signal info to be sent */ SYSCALL_DEFINE3(rt_sigqueueinfo, pid_t, pid, int, sig, siginfo_t __user *, uinfo) { siginfo_t info; if (copy_from_user(&info, uinfo, sizeof(siginfo_t))) return -EFAULT; return do_rt_sigqueueinfo(pid, sig, &info); } #ifdef CONFIG_COMPAT COMPAT_SYSCALL_DEFINE3(rt_sigqueueinfo, compat_pid_t, pid, int, sig, struct compat_siginfo __user *, uinfo) { siginfo_t info; int ret = copy_siginfo_from_user32(&info, uinfo); if (unlikely(ret)) return ret; return do_rt_sigqueueinfo(pid, sig, &info); } #endif static int do_rt_tgsigqueueinfo(pid_t tgid, pid_t pid, int sig, siginfo_t *info) { /* This is only valid for single tasks */ if (pid <= 0 || tgid <= 0) return -EINVAL; /* Not even root can pretend to send signals from the kernel. * Nor can they impersonate a kill()/tgkill(), which adds source info. */ if (((info->si_code >= 0 || info->si_code == SI_TKILL)) && (task_pid_vnr(current) != pid)) { /* We used to allow any < 0 si_code */ WARN_ON_ONCE(info->si_code < 0); return -EPERM; } info->si_signo = sig; return do_send_specific(tgid, pid, sig, info); } SYSCALL_DEFINE4(rt_tgsigqueueinfo, pid_t, tgid, pid_t, pid, int, sig, siginfo_t __user *, uinfo) { siginfo_t info; if (copy_from_user(&info, uinfo, sizeof(siginfo_t))) return -EFAULT; return do_rt_tgsigqueueinfo(tgid, pid, sig, &info); } #ifdef CONFIG_COMPAT COMPAT_SYSCALL_DEFINE4(rt_tgsigqueueinfo, compat_pid_t, tgid, compat_pid_t, pid, int, sig, struct compat_siginfo __user *, uinfo) { siginfo_t info; if (copy_siginfo_from_user32(&info, uinfo)) return -EFAULT; return do_rt_tgsigqueueinfo(tgid, pid, sig, &info); } #endif int do_sigaction(int sig, struct k_sigaction *act, struct k_sigaction *oact) { struct task_struct *t = current; struct k_sigaction *k; sigset_t mask; if (!valid_signal(sig) || sig < 1 || (act && sig_kernel_only(sig))) return -EINVAL; k = &t->sighand->action[sig-1]; spin_lock_irq(&current->sighand->siglock); if (oact) *oact = *k; if (act) { sigdelsetmask(&act->sa.sa_mask, sigmask(SIGKILL) | sigmask(SIGSTOP)); *k = *act; /* * POSIX 3.3.1.3: * "Setting a signal action to SIG_IGN for a signal that is * pending shall cause the pending signal to be discarded, * whether or not it is blocked." * * "Setting a signal action to SIG_DFL for a signal that is * pending and whose default action is to ignore the signal * (for example, SIGCHLD), shall cause the pending signal to * be discarded, whether or not it is blocked" */ if (sig_handler_ignored(sig_handler(t, sig), sig)) { sigemptyset(&mask); sigaddset(&mask, sig); rm_from_queue_full(&mask, &t->signal->shared_pending); do { rm_from_queue_full(&mask, &t->pending); t = next_thread(t); } while (t != current); } } spin_unlock_irq(&current->sighand->siglock); return 0; } static int do_sigaltstack (const stack_t __user *uss, stack_t __user *uoss, unsigned long sp) { stack_t oss; int error; oss.ss_sp = (void __user *) current->sas_ss_sp; oss.ss_size = current->sas_ss_size; oss.ss_flags = sas_ss_flags(sp); if (uss) { void __user *ss_sp; size_t ss_size; int ss_flags; error = -EFAULT; if (!access_ok(VERIFY_READ, uss, sizeof(*uss))) goto out; error = __get_user(ss_sp, &uss->ss_sp) | __get_user(ss_flags, &uss->ss_flags) | __get_user(ss_size, &uss->ss_size); if (error) goto out; error = -EPERM; if (on_sig_stack(sp)) goto out; error = -EINVAL; /* * Note - this code used to test ss_flags incorrectly: * old code may have been written using ss_flags==0 * to mean ss_flags==SS_ONSTACK (as this was the only * way that worked) - this fix preserves that older * mechanism. */ if (ss_flags != SS_DISABLE && ss_flags != SS_ONSTACK && ss_flags != 0) goto out; if (ss_flags == SS_DISABLE) { ss_size = 0; ss_sp = NULL; } else { error = -ENOMEM; if (ss_size < MINSIGSTKSZ) goto out; } current->sas_ss_sp = (unsigned long) ss_sp; current->sas_ss_size = ss_size; } error = 0; if (uoss) { error = -EFAULT; if (!access_ok(VERIFY_WRITE, uoss, sizeof(*uoss))) goto out; error = __put_user(oss.ss_sp, &uoss->ss_sp) | __put_user(oss.ss_size, &uoss->ss_size) | __put_user(oss.ss_flags, &uoss->ss_flags); } out: return error; } SYSCALL_DEFINE2(sigaltstack,const stack_t __user *,uss, stack_t __user *,uoss) { return do_sigaltstack(uss, uoss, current_user_stack_pointer()); } int restore_altstack(const stack_t __user *uss) { int err = do_sigaltstack(uss, NULL, current_user_stack_pointer()); /* squash all but EFAULT for now */ return err == -EFAULT ? err : 0; } int __save_altstack(stack_t __user *uss, unsigned long sp) { struct task_struct *t = current; return __put_user((void __user *)t->sas_ss_sp, &uss->ss_sp) | __put_user(sas_ss_flags(sp), &uss->ss_flags) | __put_user(t->sas_ss_size, &uss->ss_size); } #ifdef CONFIG_COMPAT COMPAT_SYSCALL_DEFINE2(sigaltstack, const compat_stack_t __user *, uss_ptr, compat_stack_t __user *, uoss_ptr) { stack_t uss, uoss; int ret; mm_segment_t seg; if (uss_ptr) { compat_stack_t uss32; memset(&uss, 0, sizeof(stack_t)); if (copy_from_user(&uss32, uss_ptr, sizeof(compat_stack_t))) return -EFAULT; uss.ss_sp = compat_ptr(uss32.ss_sp); uss.ss_flags = uss32.ss_flags; uss.ss_size = uss32.ss_size; } seg = get_fs(); set_fs(KERNEL_DS); ret = do_sigaltstack((stack_t __force __user *) (uss_ptr ? &uss : NULL), (stack_t __force __user *) &uoss, compat_user_stack_pointer()); set_fs(seg); if (ret >= 0 && uoss_ptr) { if (!access_ok(VERIFY_WRITE, uoss_ptr, sizeof(compat_stack_t)) || __put_user(ptr_to_compat(uoss.ss_sp), &uoss_ptr->ss_sp) || __put_user(uoss.ss_flags, &uoss_ptr->ss_flags) || __put_user(uoss.ss_size, &uoss_ptr->ss_size)) ret = -EFAULT; } return ret; } int compat_restore_altstack(const compat_stack_t __user *uss) { int err = compat_sys_sigaltstack(uss, NULL); /* squash all but -EFAULT for now */ return err == -EFAULT ? err : 0; } int __compat_save_altstack(compat_stack_t __user *uss, unsigned long sp) { struct task_struct *t = current; return __put_user(ptr_to_compat((void __user *)t->sas_ss_sp), &uss->ss_sp) | __put_user(sas_ss_flags(sp), &uss->ss_flags) | __put_user(t->sas_ss_size, &uss->ss_size); } #endif #ifdef __ARCH_WANT_SYS_SIGPENDING /** * sys_sigpending - examine pending signals * @set: where mask of pending signal is returned */ SYSCALL_DEFINE1(sigpending, old_sigset_t __user *, set) { return sys_rt_sigpending((sigset_t __user *)set, sizeof(old_sigset_t)); } #endif #ifdef __ARCH_WANT_SYS_SIGPROCMASK /** * sys_sigprocmask - examine and change blocked signals * @how: whether to add, remove, or set signals * @nset: signals to add or remove (if non-null) * @oset: previous value of signal mask if non-null * * Some platforms have their own version with special arguments; * others support only sys_rt_sigprocmask. */ SYSCALL_DEFINE3(sigprocmask, int, how, old_sigset_t __user *, nset, old_sigset_t __user *, oset) { old_sigset_t old_set, new_set; sigset_t new_blocked; old_set = current->blocked.sig[0]; if (nset) { if (copy_from_user(&new_set, nset, sizeof(*nset))) return -EFAULT; new_blocked = current->blocked; switch (how) { case SIG_BLOCK: sigaddsetmask(&new_blocked, new_set); break; case SIG_UNBLOCK: sigdelsetmask(&new_blocked, new_set); break; case SIG_SETMASK: new_blocked.sig[0] = new_set; break; default: return -EINVAL; } set_current_blocked(&new_blocked); } if (oset) { if (copy_to_user(oset, &old_set, sizeof(*oset))) return -EFAULT; } return 0; } #endif /* __ARCH_WANT_SYS_SIGPROCMASK */ #ifndef CONFIG_ODD_RT_SIGACTION /** * sys_rt_sigaction - alter an action taken by a process * @sig: signal to be sent * @act: new sigaction * @oact: used to save the previous sigaction * @sigsetsize: size of sigset_t type */ SYSCALL_DEFINE4(rt_sigaction, int, sig, const struct sigaction __user *, act, struct sigaction __user *, oact, size_t, sigsetsize) { struct k_sigaction new_sa, old_sa; int ret = -EINVAL; /* XXX: Don't preclude handling different sized sigset_t's. */ if (sigsetsize != sizeof(sigset_t)) goto out; if (act) { if (copy_from_user(&new_sa.sa, act, sizeof(new_sa.sa))) return -EFAULT; } ret = do_sigaction(sig, act ? &new_sa : NULL, oact ? &old_sa : NULL); if (!ret && oact) { if (copy_to_user(oact, &old_sa.sa, sizeof(old_sa.sa))) return -EFAULT; } out: return ret; } #ifdef CONFIG_COMPAT COMPAT_SYSCALL_DEFINE4(rt_sigaction, int, sig, const struct compat_sigaction __user *, act, struct compat_sigaction __user *, oact, compat_size_t, sigsetsize) { struct k_sigaction new_ka, old_ka; compat_sigset_t mask; #ifdef __ARCH_HAS_SA_RESTORER compat_uptr_t restorer; #endif int ret; /* XXX: Don't preclude handling different sized sigset_t's. */ if (sigsetsize != sizeof(compat_sigset_t)) return -EINVAL; if (act) { compat_uptr_t handler; ret = get_user(handler, &act->sa_handler); new_ka.sa.sa_handler = compat_ptr(handler); #ifdef __ARCH_HAS_SA_RESTORER ret |= get_user(restorer, &act->sa_restorer); new_ka.sa.sa_restorer = compat_ptr(restorer); #endif ret |= copy_from_user(&mask, &act->sa_mask, sizeof(mask)); ret |= __get_user(new_ka.sa.sa_flags, &act->sa_flags); if (ret) return -EFAULT; sigset_from_compat(&new_ka.sa.sa_mask, &mask); } ret = do_sigaction(sig, act ? &new_ka : NULL, oact ? &old_ka : NULL); if (!ret && oact) { sigset_to_compat(&mask, &old_ka.sa.sa_mask); ret = put_user(ptr_to_compat(old_ka.sa.sa_handler), &oact->sa_handler); ret |= copy_to_user(&oact->sa_mask, &mask, sizeof(mask)); ret |= __put_user(old_ka.sa.sa_flags, &oact->sa_flags); #ifdef __ARCH_HAS_SA_RESTORER ret |= put_user(ptr_to_compat(old_ka.sa.sa_restorer), &oact->sa_restorer); #endif } return ret; } #endif #endif /* !CONFIG_ODD_RT_SIGACTION */ #ifdef CONFIG_OLD_SIGACTION SYSCALL_DEFINE3(sigaction, int, sig, const struct old_sigaction __user *, act, struct old_sigaction __user *, oact) { struct k_sigaction new_ka, old_ka; int ret; if (act) { old_sigset_t mask; if (!access_ok(VERIFY_READ, act, sizeof(*act)) || __get_user(new_ka.sa.sa_handler, &act->sa_handler) || __get_user(new_ka.sa.sa_restorer, &act->sa_restorer) || __get_user(new_ka.sa.sa_flags, &act->sa_flags) || __get_user(mask, &act->sa_mask)) return -EFAULT; #ifdef __ARCH_HAS_KA_RESTORER new_ka.ka_restorer = NULL; #endif siginitset(&new_ka.sa.sa_mask, mask); } ret = do_sigaction(sig, act ? &new_ka : NULL, oact ? &old_ka : NULL); if (!ret && oact) { if (!access_ok(VERIFY_WRITE, oact, sizeof(*oact)) || __put_user(old_ka.sa.sa_handler, &oact->sa_handler) || __put_user(old_ka.sa.sa_restorer, &oact->sa_restorer) || __put_user(old_ka.sa.sa_flags, &oact->sa_flags) || __put_user(old_ka.sa.sa_mask.sig[0], &oact->sa_mask)) return -EFAULT; } return ret; } #endif #ifdef CONFIG_COMPAT_OLD_SIGACTION COMPAT_SYSCALL_DEFINE3(sigaction, int, sig, const struct compat_old_sigaction __user *, act, struct compat_old_sigaction __user *, oact) { struct k_sigaction new_ka, old_ka; int ret; compat_old_sigset_t mask; compat_uptr_t handler, restorer; if (act) { if (!access_ok(VERIFY_READ, act, sizeof(*act)) || __get_user(handler, &act->sa_handler) || __get_user(restorer, &act->sa_restorer) || __get_user(new_ka.sa.sa_flags, &act->sa_flags) || __get_user(mask, &act->sa_mask)) return -EFAULT; #ifdef __ARCH_HAS_KA_RESTORER new_ka.ka_restorer = NULL; #endif new_ka.sa.sa_handler = compat_ptr(handler); new_ka.sa.sa_restorer = compat_ptr(restorer); siginitset(&new_ka.sa.sa_mask, mask); } ret = do_sigaction(sig, act ? &new_ka : NULL, oact ? &old_ka : NULL); if (!ret && oact) { if (!access_ok(VERIFY_WRITE, oact, sizeof(*oact)) || __put_user(ptr_to_compat(old_ka.sa.sa_handler), &oact->sa_handler) || __put_user(ptr_to_compat(old_ka.sa.sa_restorer), &oact->sa_restorer) || __put_user(old_ka.sa.sa_flags, &oact->sa_flags) || __put_user(old_ka.sa.sa_mask.sig[0], &oact->sa_mask)) return -EFAULT; } return ret; } #endif #ifdef __ARCH_WANT_SYS_SGETMASK /* * For backwards compatibility. Functionality superseded by sigprocmask. */ SYSCALL_DEFINE0(sgetmask) { /* SMP safe */ return current->blocked.sig[0]; } SYSCALL_DEFINE1(ssetmask, int, newmask) { int old = current->blocked.sig[0]; sigset_t newset; siginitset(&newset, newmask); set_current_blocked(&newset); return old; } #endif /* __ARCH_WANT_SGETMASK */ #ifdef __ARCH_WANT_SYS_SIGNAL /* * For backwards compatibility. Functionality superseded by sigaction. */ SYSCALL_DEFINE2(signal, int, sig, __sighandler_t, handler) { struct k_sigaction new_sa, old_sa; int ret; new_sa.sa.sa_handler = handler; new_sa.sa.sa_flags = SA_ONESHOT | SA_NOMASK; sigemptyset(&new_sa.sa.sa_mask); ret = do_sigaction(sig, &new_sa, &old_sa); return ret ? ret : (unsigned long)old_sa.sa.sa_handler; } #endif /* __ARCH_WANT_SYS_SIGNAL */ #ifdef __ARCH_WANT_SYS_PAUSE SYSCALL_DEFINE0(pause) { while (!signal_pending(current)) { current->state = TASK_INTERRUPTIBLE; schedule(); } return -ERESTARTNOHAND; } #endif int sigsuspend(sigset_t *set) { current->saved_sigmask = current->blocked; set_current_blocked(set); current->state = TASK_INTERRUPTIBLE; schedule(); set_restore_sigmask(); return -ERESTARTNOHAND; } /** * sys_rt_sigsuspend - replace the signal mask for a value with the * @unewset value until a signal is received * @unewset: new signal mask value * @sigsetsize: size of sigset_t type */ SYSCALL_DEFINE2(rt_sigsuspend, sigset_t __user *, unewset, size_t, sigsetsize) { sigset_t newset; /* XXX: Don't preclude handling different sized sigset_t's. */ if (sigsetsize != sizeof(sigset_t)) return -EINVAL; if (copy_from_user(&newset, unewset, sizeof(newset))) return -EFAULT; return sigsuspend(&newset); } #ifdef CONFIG_COMPAT COMPAT_SYSCALL_DEFINE2(rt_sigsuspend, compat_sigset_t __user *, unewset, compat_size_t, sigsetsize) { #ifdef __BIG_ENDIAN sigset_t newset; compat_sigset_t newset32; /* XXX: Don't preclude handling different sized sigset_t's. */ if (sigsetsize != sizeof(sigset_t)) return -EINVAL; if (copy_from_user(&newset32, unewset, sizeof(compat_sigset_t))) return -EFAULT; sigset_from_compat(&newset, &newset32); return sigsuspend(&newset); #else /* on little-endian bitmaps don't care about granularity */ return sys_rt_sigsuspend((sigset_t __user *)unewset, sigsetsize); #endif } #endif #ifdef CONFIG_OLD_SIGSUSPEND SYSCALL_DEFINE1(sigsuspend, old_sigset_t, mask) { sigset_t blocked; siginitset(&blocked, mask); return sigsuspend(&blocked); } #endif #ifdef CONFIG_OLD_SIGSUSPEND3 SYSCALL_DEFINE3(sigsuspend, int, unused1, int, unused2, old_sigset_t, mask) { sigset_t blocked; siginitset(&blocked, mask); return sigsuspend(&blocked); } #endif __attribute__((weak)) const char *arch_vma_name(struct vm_area_struct *vma) { return NULL; } void __init signals_init(void) { sigqueue_cachep = KMEM_CACHE(sigqueue, SLAB_PANIC); } #ifdef CONFIG_KGDB_KDB #include <linux/kdb.h> /* * kdb_send_sig_info - Allows kdb to send signals without exposing * signal internals. This function checks if the required locks are * available before calling the main signal code, to avoid kdb * deadlocks. */ void kdb_send_sig_info(struct task_struct *t, struct siginfo *info) { static struct task_struct *kdb_prev_t; int sig, new_t; if (!spin_trylock(&t->sighand->siglock)) { kdb_printf("Can't do kill command now.\n" "The sigmask lock is held somewhere else in " "kernel, try again later\n"); return; } spin_unlock(&t->sighand->siglock); new_t = kdb_prev_t != t; kdb_prev_t = t; if (t->state != TASK_RUNNING && new_t) { kdb_printf("Process is not RUNNING, sending a signal from " "kdb risks deadlock\n" "on the run queue locks. " "The signal has _not_ been sent.\n" "Reissue the kill command if you want to risk " "the deadlock.\n"); return; } sig = info->si_signo; if (send_sig_info(sig, info, t)) kdb_printf("Fail to deliver Signal %d to process %d.\n", sig, t->pid); else kdb_printf("Signal %d is sent to process %d.\n", sig, t->pid); } #endif /* CONFIG_KGDB_KDB */
./CrossVul/dataset_final_sorted/CWE-399/c/bad_5650_0
crossvul-cpp_data_good_1416_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP DDDD FFFFF % % P P D D F % % PPPP D D FFF % % P D D F % % P DDDD F % % % % % % Read/Write Portable Document Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 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://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/artifact.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/compress.h" #include "MagickCore/constitute.h" #include "MagickCore/delegate.h" #include "MagickCore/delegate-private.h" #include "MagickCore/draw.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.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/nt-base-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/resize.h" #include "MagickCore/signature.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" #include "MagickCore/token.h" #include "MagickCore/transform.h" #include "MagickCore/utility.h" #include "MagickCore/module.h" /* Define declarations. */ #if defined(MAGICKCORE_TIFF_DELEGATE) #define CCITTParam "-1" #else #define CCITTParam "0" #endif /* Forward declarations. */ static MagickBooleanType WritePDFImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v o k e P D F D e l e g a t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InvokePDFDelegate() executes the PDF interpreter with the specified command. % % The format of the InvokePDFDelegate method is: % % MagickBooleanType InvokePDFDelegate(const MagickBooleanType verbose, % const char *command,ExceptionInfo *exception) % % A description of each parameter follows: % % o verbose: A value other than zero displays the command prior to % executing it. % % o command: the address of a character string containing the command to % execute. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_GS_DELEGATE) || defined(MAGICKCORE_WINDOWS_SUPPORT) static int MagickDLLCall PDFDelegateMessage(void *handle,const char *message, int length) { char **messages; ssize_t offset; offset=0; messages=(char **) handle; if (*messages == (char *) NULL) *messages=(char *) AcquireQuantumMemory(length+1,sizeof(char *)); else { offset=strlen(*messages); *messages=(char *) ResizeQuantumMemory(*messages,offset+length+1, sizeof(char *)); } if (*messages == (char *) NULL) return(0); (void) memcpy(*messages+offset,message,length); (*messages)[length+offset] ='\0'; return(length); } #endif static MagickBooleanType InvokePDFDelegate(const MagickBooleanType verbose, const char *command,char *message,ExceptionInfo *exception) { int status; #define ExecuteGhostscriptCommand(command,status) \ { \ status=ExternalDelegateCommand(MagickFalse,verbose,command,message, \ exception); \ if (status == 0) \ return(MagickTrue); \ if (status < 0) \ return(MagickFalse); \ (void) ThrowMagickException(exception,GetMagickModule(),DelegateError, \ "FailedToExecuteCommand","`%s' (%d)",command,status); \ return(MagickFalse); \ } #if defined(MAGICKCORE_GS_DELEGATE) || defined(MAGICKCORE_WINDOWS_SUPPORT) #define SetArgsStart(command,args_start) \ if (args_start == (const char *) NULL) \ { \ if (*command != '"') \ args_start=strchr(command,' '); \ else \ { \ args_start=strchr(command+1,'"'); \ if (args_start != (const char *) NULL) \ args_start++; \ } \ } char **argv, *errors; const char *args_start = (const char *) NULL; const GhostInfo *ghost_info; gs_main_instance *interpreter; gsapi_revision_t revision; int argc, code; register ssize_t i; #if defined(MAGICKCORE_WINDOWS_SUPPORT) ghost_info=NTGhostscriptDLLVectors(); #else GhostInfo ghost_info_struct; ghost_info=(&ghost_info_struct); (void) memset(&ghost_info_struct,0,sizeof(ghost_info_struct)); ghost_info_struct.delete_instance=(void (*)(gs_main_instance *)) gsapi_delete_instance; ghost_info_struct.exit=(int (*)(gs_main_instance *)) gsapi_exit; ghost_info_struct.new_instance=(int (*)(gs_main_instance **,void *)) gsapi_new_instance; ghost_info_struct.init_with_args=(int (*)(gs_main_instance *,int,char **)) gsapi_init_with_args; ghost_info_struct.run_string=(int (*)(gs_main_instance *,const char *,int, int *)) gsapi_run_string; ghost_info_struct.set_stdio=(int (*)(gs_main_instance *,int (*)(void *,char *, int),int (*)(void *,const char *,int),int (*)(void *, const char *, int))) gsapi_set_stdio; ghost_info_struct.revision=(int (*)(gsapi_revision_t *,int)) gsapi_revision; #endif if (ghost_info == (GhostInfo *) NULL) ExecuteGhostscriptCommand(command,status); if ((ghost_info->revision)(&revision,sizeof(revision)) != 0) revision.revision=0; if (verbose != MagickFalse) { (void) fprintf(stdout,"[ghostscript library %.2f]",(double) revision.revision/100.0); SetArgsStart(command,args_start); (void) fputs(args_start,stdout); } errors=(char *) NULL; status=(ghost_info->new_instance)(&interpreter,(void *) &errors); if (status < 0) ExecuteGhostscriptCommand(command,status); code=0; argv=StringToArgv(command,&argc); if (argv == (char **) NULL) { (ghost_info->delete_instance)(interpreter); return(MagickFalse); } (void) (ghost_info->set_stdio)(interpreter,(int (MagickDLLCall *)(void *, char *,int)) NULL,PDFDelegateMessage,PDFDelegateMessage); status=(ghost_info->init_with_args)(interpreter,argc-1,argv+1); if (status == 0) status=(ghost_info->run_string)(interpreter,"systemdict /start get exec\n", 0,&code); (ghost_info->exit)(interpreter); (ghost_info->delete_instance)(interpreter); for (i=0; i < (ssize_t) argc; i++) argv[i]=DestroyString(argv[i]); argv=(char **) RelinquishMagickMemory(argv); if (status != 0) { SetArgsStart(command,args_start); if (status == -101) /* quit */ (void) FormatLocaleString(message,MagickPathExtent, "[ghostscript library %.2f]%s: %s",(double) revision.revision/100.0, args_start,errors); else { (void) ThrowMagickException(exception,GetMagickModule(),DelegateError, "PDFDelegateFailed","`[ghostscript library %.2f]%s': %s",(double) revision.revision/100.0,args_start,errors); if (errors != (char *) NULL) errors=DestroyString(errors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Ghostscript returns status %d, exit code %d",status,code); return(MagickFalse); } } if (errors != (char *) NULL) errors=DestroyString(errors); return(MagickTrue); #else ExecuteGhostscriptCommand(command,status); #endif } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P D F % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPDF() returns MagickTrue if the image format type, identified by the % magick string, is PDF. % % The format of the IsPDF method is: % % MagickBooleanType IsPDF(const unsigned char *magick,const size_t offset) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o offset: Specifies the offset of the magick string. % */ static MagickBooleanType IsPDF(const unsigned char *magick,const size_t offset) { if (offset < 5) return(MagickFalse); if (LocaleNCompare((const char *) magick,"%PDF-",5) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P D F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPDFImage() reads a Portable Document Format 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 ReadPDFImage method is: % % Image *ReadPDFImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType IsPDFRendered(const char *path) { MagickBooleanType status; struct stat attributes; if ((path == (const char *) NULL) || (*path == '\0')) return(MagickFalse); status=GetPathAttributes(path,&attributes); if ((status != MagickFalse) && S_ISREG(attributes.st_mode) && (attributes.st_size > 0)) return(MagickTrue); return(MagickFalse); } static Image *ReadPDFImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define BeginXMPPacket "<?xpacket begin=" #define CMYKProcessColor "CMYKProcessColor" #define CropBox "CropBox" #define DefaultCMYK "DefaultCMYK" #define DeviceCMYK "DeviceCMYK" #define EndXMPPacket "<?xpacket end=" #define MediaBox "MediaBox" #define RenderPostscriptText "Rendering Postscript... " #define PDFRotate "Rotate" #define SpotColor "Separation" #define TrimBox "TrimBox" #define PDFVersion "PDF-" char command[MagickPathExtent], *density, filename[MagickPathExtent], geometry[MagickPathExtent], input_filename[MagickPathExtent], message[MagickPathExtent], *options, postscript_filename[MagickPathExtent]; const char *option; const DelegateInfo *delegate_info; double angle; GeometryInfo geometry_info; Image *image, *next, *pdf_image; ImageInfo *read_info; int c, file; MagickBooleanType cmyk, cropbox, fitPage, status, stop_on_error, trimbox; MagickStatusType flags; PointInfo delta; RectangleInfo bounding_box, page; register char *p; register ssize_t i; SegmentInfo bounds, hires_bounds; size_t scene, spotcolor; ssize_t count; 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); /* Open image file. */ image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } status=AcquireUniqueSymbolicLink(image_info->filename,input_filename); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Set the page density. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; } (void) memset(&page,0,sizeof(page)); (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); page.width=(size_t) ceil((double) (page.width*image->resolution.x/delta.x)- 0.5); page.height=(size_t) ceil((double) (page.height*image->resolution.y/delta.y)- 0.5); /* Determine page geometry from the PDF media box. */ cmyk=image_info->colorspace == CMYKColorspace ? MagickTrue : MagickFalse; cropbox=IsStringTrue(GetImageOption(image_info,"pdf:use-cropbox")); stop_on_error=IsStringTrue(GetImageOption(image_info,"pdf:stop-on-error")); trimbox=IsStringTrue(GetImageOption(image_info,"pdf:use-trimbox")); count=0; spotcolor=0; (void) memset(&bounding_box,0,sizeof(bounding_box)); (void) memset(&bounds,0,sizeof(bounds)); (void) memset(&hires_bounds,0,sizeof(hires_bounds)); (void) memset(command,0,sizeof(command)); angle=0.0; p=command; for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { /* Note PDF elements. */ if (c == '\n') c=' '; *p++=(char) c; if ((c != (int) '/') && (c != (int) '%') && ((size_t) (p-command) < (MagickPathExtent-1))) continue; *(--p)='\0'; p=command; if (LocaleNCompare(PDFRotate,command,strlen(PDFRotate)) == 0) count=(ssize_t) sscanf(command,"Rotate %lf",&angle); /* Is this a CMYK document? */ if (LocaleNCompare(DefaultCMYK,command,strlen(DefaultCMYK)) == 0) cmyk=MagickTrue; if (LocaleNCompare(DeviceCMYK,command,strlen(DeviceCMYK)) == 0) cmyk=MagickTrue; if (LocaleNCompare(CMYKProcessColor,command,strlen(CMYKProcessColor)) == 0) cmyk=MagickTrue; if (LocaleNCompare(SpotColor,command,strlen(SpotColor)) == 0) { char name[MagickPathExtent], property[MagickPathExtent], *value; /* Note spot names. */ (void) FormatLocaleString(property,MagickPathExtent, "pdf:SpotColor-%.20g",(double) spotcolor++); i=0; for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { if ((isspace(c) != 0) || (c == '/') || ((i+1) == MagickPathExtent)) break; name[i++]=(char) c; } name[i]='\0'; value=ConstantString(name); (void) SubstituteString(&value,"#20"," "); if (*value != '\0') (void) SetImageProperty(image,property,value,exception); value=DestroyString(value); continue; } if (LocaleNCompare(PDFVersion,command,strlen(PDFVersion)) == 0) (void) SetImageProperty(image,"pdf:Version",command,exception); if (image_info->page != (char *) NULL) continue; count=0; if (cropbox != MagickFalse) { if (LocaleNCompare(CropBox,command,strlen(CropBox)) == 0) { /* Note region defined by crop box. */ count=(ssize_t) sscanf(command,"CropBox [%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); if (count != 4) count=(ssize_t) sscanf(command,"CropBox[%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); } } else if (trimbox != MagickFalse) { if (LocaleNCompare(TrimBox,command,strlen(TrimBox)) == 0) { /* Note region defined by trim box. */ count=(ssize_t) sscanf(command,"TrimBox [%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); if (count != 4) count=(ssize_t) sscanf(command,"TrimBox[%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); } } else if (LocaleNCompare(MediaBox,command,strlen(MediaBox)) == 0) { /* Note region defined by media box. */ count=(ssize_t) sscanf(command,"MediaBox [%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); if (count != 4) count=(ssize_t) sscanf(command,"MediaBox[%lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); } if (count != 4) continue; if ((fabs(bounds.x2-bounds.x1) <= fabs(hires_bounds.x2-hires_bounds.x1)) || (fabs(bounds.y2-bounds.y1) <= fabs(hires_bounds.y2-hires_bounds.y1))) continue; hires_bounds=bounds; } if ((fabs(hires_bounds.x2-hires_bounds.x1) >= MagickEpsilon) && (fabs(hires_bounds.y2-hires_bounds.y1) >= MagickEpsilon)) { /* Set PDF render geometry. */ (void) FormatLocaleString(geometry,MagickPathExtent,"%gx%g%+.15g%+.15g", hires_bounds.x2-bounds.x1,hires_bounds.y2-hires_bounds.y1, hires_bounds.x1,hires_bounds.y1); (void) SetImageProperty(image,"pdf:HiResBoundingBox",geometry,exception); page.width=(size_t) ceil((double) ((hires_bounds.x2-hires_bounds.x1)* image->resolution.x/delta.x)-0.5); page.height=(size_t) ceil((double) ((hires_bounds.y2-hires_bounds.y1)* image->resolution.y/delta.y)-0.5); } fitPage=MagickFalse; option=GetImageOption(image_info,"pdf:fit-page"); if (option != (char *) NULL) { char *page_geometry; page_geometry=GetPageGeometry(option); flags=ParseMetaGeometry(page_geometry,&page.x,&page.y,&page.width, &page.height); page_geometry=DestroyString(page_geometry); if (flags == NoValue) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidGeometry","`%s'",option); image=DestroyImage(image); return((Image *) NULL); } page.width=(size_t) ceil((double) (page.width*image->resolution.x/delta.x) -0.5); page.height=(size_t) ceil((double) (page.height*image->resolution.y/ delta.y) -0.5); fitPage=MagickTrue; } if ((fabs(angle) == 90.0) || (fabs(angle) == 270.0)) { size_t swap; swap=page.width; page.width=page.height; page.height=swap; } if (IssRGBCompatibleColorspace(image_info->colorspace) != MagickFalse) cmyk=MagickFalse; /* Create Ghostscript control file. */ file=AcquireUniqueFileResource(postscript_filename); if (file == -1) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", image_info->filename); image=DestroyImage(image); return((Image *) NULL); } count=write(file," ",1); file=close(file)-1; /* Render Postscript with the Ghostscript delegate. */ if (image_info->monochrome != MagickFalse) delegate_info=GetDelegateInfo("ps:mono",(char *) NULL,exception); else if (cmyk != MagickFalse) delegate_info=GetDelegateInfo("ps:cmyk",(char *) NULL,exception); else delegate_info=GetDelegateInfo("ps:alpha",(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) { (void) RelinquishUniqueFileResource(postscript_filename); image=DestroyImage(image); return((Image *) NULL); } density=AcquireString(""); options=AcquireString(""); (void) FormatLocaleString(density,MagickPathExtent,"%gx%g", image->resolution.x,image->resolution.y); if ((image_info->page != (char *) NULL) || (fitPage != MagickFalse)) (void) FormatLocaleString(options,MagickPathExtent,"-g%.20gx%.20g ",(double) page.width,(double) page.height); if (fitPage != MagickFalse) (void) ConcatenateMagickString(options,"-dPSFitPage ",MagickPathExtent); if (cmyk != MagickFalse) (void) ConcatenateMagickString(options,"-dUseCIEColor ",MagickPathExtent); if (cropbox != MagickFalse) (void) ConcatenateMagickString(options,"-dUseCropBox ",MagickPathExtent); if (stop_on_error != MagickFalse) (void) ConcatenateMagickString(options,"-dPDFSTOPONERROR ", MagickPathExtent); if (trimbox != MagickFalse) (void) ConcatenateMagickString(options,"-dUseTrimBox ",MagickPathExtent); option=GetImageOption(image_info,"authenticate"); if (option != (char *) NULL) { char passphrase[MagickPathExtent]; (void) FormatLocaleString(passphrase,MagickPathExtent, "\"-sPDFPassword=%s\" ",option); (void) ConcatenateMagickString(options,passphrase,MagickPathExtent); } read_info=CloneImageInfo(image_info); *read_info->magick='\0'; if (read_info->number_scenes != 0) { char pages[MagickPathExtent]; (void) FormatLocaleString(pages,MagickPathExtent,"-dFirstPage=%.20g " "-dLastPage=%.20g",(double) read_info->scene+1,(double) (read_info->scene+read_info->number_scenes)); (void) ConcatenateMagickString(options,pages,MagickPathExtent); read_info->number_scenes=0; if (read_info->scenes != (char *) NULL) *read_info->scenes='\0'; } (void) CopyMagickString(filename,read_info->filename,MagickPathExtent); (void) AcquireUniqueFilename(filename); (void) RelinquishUniqueFileResource(filename); (void) ConcatenateMagickString(filename,"%d",MagickPathExtent); (void) FormatLocaleString(command,MagickPathExtent, GetDelegateCommands(delegate_info), read_info->antialias != MagickFalse ? 4 : 1, read_info->antialias != MagickFalse ? 4 : 1,density,options,filename, postscript_filename,input_filename); options=DestroyString(options); density=DestroyString(density); *message='\0'; status=InvokePDFDelegate(read_info->verbose,command,message,exception); (void) RelinquishUniqueFileResource(postscript_filename); (void) RelinquishUniqueFileResource(input_filename); pdf_image=(Image *) NULL; if (status == MagickFalse) for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename,exception); if (IsPDFRendered(read_info->filename) == MagickFalse) break; (void) RelinquishUniqueFileResource(read_info->filename); } else for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename,exception); if (IsPDFRendered(read_info->filename) == MagickFalse) break; read_info->blob=NULL; read_info->length=0; next=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); if (next == (Image *) NULL) break; AppendImageToList(&pdf_image,next); } read_info=DestroyImageInfo(read_info); if (pdf_image == (Image *) NULL) { if (*message != '\0') (void) ThrowMagickException(exception,GetMagickModule(),DelegateError, "PDFDelegateFailed","`%s'",message); image=DestroyImage(image); return((Image *) NULL); } if (LocaleCompare(pdf_image->magick,"BMP") == 0) { Image *cmyk_image; cmyk_image=ConsolidateCMYKImages(pdf_image,exception); if (cmyk_image != (Image *) NULL) { pdf_image=DestroyImageList(pdf_image); pdf_image=cmyk_image; } } (void) SeekBlob(image,0,SEEK_SET); for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { /* Note document structuring comments. */ *p++=(char) c; if ((strchr("\n\r%",c) == (char *) NULL) && ((size_t) (p-command) < (MagickPathExtent-1))) continue; *p='\0'; p=command; if (LocaleNCompare(BeginXMPPacket,command,strlen(BeginXMPPacket)) == 0) { StringInfo *profile; /* Read XMP profile. */ p=command; profile=StringToStringInfo(command); for (i=(ssize_t) GetStringInfoLength(profile)-1; c != EOF; i++) { SetStringInfoLength(profile,(size_t) (i+1)); c=ReadBlobByte(image); GetStringInfoDatum(profile)[i]=(unsigned char) c; *p++=(char) c; if ((strchr("\n\r%",c) == (char *) NULL) && ((size_t) (p-command) < (MagickPathExtent-1))) continue; *p='\0'; p=command; if (LocaleNCompare(EndXMPPacket,command,strlen(EndXMPPacket)) == 0) break; } SetStringInfoLength(profile,(size_t) i); (void) SetImageProfile(image,"xmp",profile,exception); profile=DestroyStringInfo(profile); continue; } } (void) CloseBlob(image); if (image_info->number_scenes != 0) { Image *clone_image; /* Add place holder images to meet the subimage specification requirement. */ for (i=0; i < (ssize_t) image_info->scene; i++) { clone_image=CloneImage(pdf_image,1,1,MagickTrue,exception); if (clone_image != (Image *) NULL) PrependImageToList(&pdf_image,clone_image); } } do { (void) CopyMagickString(pdf_image->filename,filename,MagickPathExtent); (void) CopyMagickString(pdf_image->magick,image->magick,MagickPathExtent); pdf_image->page=page; (void) CloneImageProfiles(pdf_image,image); (void) CloneImageProperties(pdf_image,image); next=SyncNextImageInList(pdf_image); if (next != (Image *) NULL) pdf_image=next; } while (next != (Image *) NULL); image=DestroyImage(image); scene=0; for (next=GetFirstImageInList(pdf_image); next != (Image *) NULL; ) { next->scene=scene++; next=GetNextImageInList(next); } return(GetFirstImageInList(pdf_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P D F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPDFImage() adds properties for the PDF 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 RegisterPDFImage method is: % % size_t RegisterPDFImage(void) % */ ModuleExport size_t RegisterPDFImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PDF","AI","Adobe Illustrator CS2"); entry->decoder=(DecodeImageHandler *) ReadPDFImage; entry->encoder=(EncodeImageHandler *) WritePDFImage; entry->flags^=CoderAdjoinFlag; entry->flags^=CoderBlobSupportFlag; entry->mime_type=ConstantString("application/pdf"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PDF","EPDF", "Encapsulated Portable Document Format"); entry->decoder=(DecodeImageHandler *) ReadPDFImage; entry->encoder=(EncodeImageHandler *) WritePDFImage; entry->flags^=CoderAdjoinFlag; entry->flags^=CoderBlobSupportFlag; entry->mime_type=ConstantString("application/pdf"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PDF","PDF","Portable Document Format"); entry->decoder=(DecodeImageHandler *) ReadPDFImage; entry->encoder=(EncodeImageHandler *) WritePDFImage; entry->magick=(IsImageFormatHandler *) IsPDF; entry->flags^=CoderBlobSupportFlag; entry->mime_type=ConstantString("application/pdf"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PDF","PDFA","Portable Document Archive Format"); entry->decoder=(DecodeImageHandler *) ReadPDFImage; entry->encoder=(EncodeImageHandler *) WritePDFImage; entry->magick=(IsImageFormatHandler *) IsPDF; entry->flags^=CoderBlobSupportFlag; entry->mime_type=ConstantString("application/pdf"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P D F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPDFImage() removes format registrations made by the % PDF module from the list of supported formats. % % The format of the UnregisterPDFImage method is: % % UnregisterPDFImage(void) % */ ModuleExport void UnregisterPDFImage(void) { (void) UnregisterMagickInfo("AI"); (void) UnregisterMagickInfo("EPDF"); (void) UnregisterMagickInfo("PDF"); (void) UnregisterMagickInfo("PDFA"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P D F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePDFImage() writes an image in the Portable Document image % format. % % The format of the WritePDFImage method is: % % MagickBooleanType WritePDFImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static char *EscapeParenthesis(const char *source) { char *destination; register char *q; register const char *p; size_t length; assert(source != (const char *) NULL); length=0; for (p=source; *p != '\0'; p++) { if ((*p == '\\') || (*p == '(') || (*p == ')')) { if (~length < 1) ThrowFatalException(ResourceLimitFatalError,"UnableToEscapeString"); length++; } length++; } destination=(char *) NULL; if (~length >= (MagickPathExtent-1)) destination=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*destination)); if (destination == (char *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToEscapeString"); *destination='\0'; q=destination; for (p=source; *p != '\0'; p++) { if ((*p == '\\') || (*p == '(') || (*p == ')')) *q++='\\'; *q++=(*p); } *q='\0'; return(destination); } static size_t UTF8ToUTF16(const unsigned char *utf8,wchar_t *utf16) { register const unsigned char *p; if (utf16 != (wchar_t *) NULL) { register wchar_t *q; wchar_t c; /* Convert UTF-8 to UTF-16. */ q=utf16; for (p=utf8; *p != '\0'; p++) { if ((*p & 0x80) == 0) *q=(*p); else if ((*p & 0xE0) == 0xC0) { c=(*p); *q=(c & 0x1F) << 6; p++; if ((*p & 0xC0) != 0x80) return(0); *q|=(*p & 0x3F); } else if ((*p & 0xF0) == 0xE0) { c=(*p); *q=c << 12; p++; if ((*p & 0xC0) != 0x80) return(0); c=(*p); *q|=(c & 0x3F) << 6; p++; if ((*p & 0xC0) != 0x80) return(0); *q|=(*p & 0x3F); } else return(0); q++; } *q++=(wchar_t) '\0'; return((size_t) (q-utf16)); } /* Compute UTF-16 string length. */ for (p=utf8; *p != '\0'; p++) { if ((*p & 0x80) == 0) ; else if ((*p & 0xE0) == 0xC0) { p++; if ((*p & 0xC0) != 0x80) return(0); } else if ((*p & 0xF0) == 0xE0) { p++; if ((*p & 0xC0) != 0x80) return(0); p++; if ((*p & 0xC0) != 0x80) return(0); } else return(0); } return((size_t) (p-utf8)); } static wchar_t *ConvertUTF8ToUTF16(const unsigned char *source,size_t *length) { wchar_t *utf16; *length=UTF8ToUTF16(source,(wchar_t *) NULL); if (*length == 0) { register ssize_t i; /* Not UTF-8, just copy. */ *length=strlen((const char *) source); utf16=(wchar_t *) AcquireQuantumMemory(*length+1,sizeof(*utf16)); if (utf16 == (wchar_t *) NULL) return((wchar_t *) NULL); for (i=0; i <= (ssize_t) *length; i++) utf16[i]=source[i]; return(utf16); } utf16=(wchar_t *) AcquireQuantumMemory(*length+1,sizeof(*utf16)); if (utf16 == (wchar_t *) NULL) return((wchar_t *) NULL); *length=UTF8ToUTF16(source,utf16); return(utf16); } static MagickBooleanType Huffman2DEncodeImage(const ImageInfo *image_info, Image *image,Image *inject_image,ExceptionInfo *exception) { Image *group4_image; ImageInfo *write_info; MagickBooleanType status; size_t length; unsigned char *group4; status=MagickTrue; write_info=CloneImageInfo(image_info); (void) CopyMagickString(write_info->filename,"GROUP4:",MagickPathExtent); (void) CopyMagickString(write_info->magick,"GROUP4",MagickPathExtent); group4_image=CloneImage(inject_image,0,0,MagickTrue,exception); if (group4_image == (Image *) NULL) return(MagickFalse); group4=(unsigned char *) ImageToBlob(write_info,group4_image,&length, exception); group4_image=DestroyImage(group4_image); if (group4 == (unsigned char *) NULL) return(MagickFalse); write_info=DestroyImageInfo(write_info); if (WriteBlob(image,length,group4) != (ssize_t) length) status=MagickFalse; group4=(unsigned char *) RelinquishMagickMemory(group4); return(status); } static MagickBooleanType WritePDFImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { #define CFormat "/Filter [ /%s ]\n" #define ObjectsPerImage 14 #define ThrowPDFException(exception,message) \ { \ if (xref != (MagickOffsetType *) NULL) \ xref=(MagickOffsetType *) RelinquishMagickMemory(xref); \ ThrowWriterException((exception),(message)); \ } DisableMSCWarning(4310) static const char XMPProfile[]= { "<?xpacket begin=\"%s\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n" "<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"Adobe XMP Core 4.0-c316 44.253921, Sun Oct 01 2006 17:08:23\">\n" " <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:xap=\"http://ns.adobe.com/xap/1.0/\">\n" " <xap:ModifyDate>%s</xap:ModifyDate>\n" " <xap:CreateDate>%s</xap:CreateDate>\n" " <xap:MetadataDate>%s</xap:MetadataDate>\n" " <xap:CreatorTool>%s</xap:CreatorTool>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n" " <dc:format>application/pdf</dc:format>\n" " <dc:title>\n" " <rdf:Alt>\n" " <rdf:li xml:lang=\"x-default\">%s</rdf:li>\n" " </rdf:Alt>\n" " </dc:title>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:xapMM=\"http://ns.adobe.com/xap/1.0/mm/\">\n" " <xapMM:DocumentID>uuid:6ec119d7-7982-4f56-808d-dfe64f5b35cf</xapMM:DocumentID>\n" " <xapMM:InstanceID>uuid:a79b99b4-6235-447f-9f6c-ec18ef7555cb</xapMM:InstanceID>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\">\n" " <pdf:Producer>%s</pdf:Producer>\n" " </rdf:Description>\n" " <rdf:Description rdf:about=\"\"\n" " xmlns:pdfaid=\"http://www.aiim.org/pdfa/ns/id/\">\n" " <pdfaid:part>3</pdfaid:part>\n" " <pdfaid:conformance>B</pdfaid:conformance>\n" " </rdf:Description>\n" " </rdf:RDF>\n" "</x:xmpmeta>\n" "<?xpacket end=\"w\"?>\n" }, XMPProfileMagick[4]= { (char) 0xef, (char) 0xbb, (char) 0xbf, (char) 0x00 }; RestoreMSCWarning char basename[MagickPathExtent], buffer[MagickPathExtent], *escape, date[MagickPathExtent], **labels, page_geometry[MagickPathExtent], *url; CompressionType compression; const char *device, *option, *value; const StringInfo *profile; double pointsize; GeometryInfo geometry_info; Image *next, *tile_image; MagickBooleanType status; MagickOffsetType offset, scene, *xref; MagickSizeType number_pixels; MagickStatusType flags; PointInfo delta, resolution, scale; RectangleInfo geometry, media_info, page_info; register const Quantum *p; register unsigned char *q; register ssize_t i, x; size_t channels, imageListLength, info_id, length, object, pages_id, root_id, text_size, version; ssize_t count, page_count, y; struct tm local_time; time_t seconds; unsigned char *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); /* Allocate X ref memory. */ xref=(MagickOffsetType *) AcquireQuantumMemory(2048UL,sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) memset(xref,0,2048UL*sizeof(*xref)); /* Write Info object. */ object=0; version=3; if (image_info->compression == JPEG2000Compression) version=(size_t) MagickMax(version,5); for (next=image; next != (Image *) NULL; next=GetNextImageInList(next)) if (next->alpha_trait != UndefinedPixelTrait) version=(size_t) MagickMax(version,4); if (LocaleCompare(image_info->magick,"PDFA") == 0) version=(size_t) MagickMax(version,6); profile=GetImageProfile(image,"icc"); if (profile != (StringInfo *) NULL) version=(size_t) MagickMax(version,7); (void) FormatLocaleString(buffer,MagickPathExtent,"%%PDF-1.%.20g \n",(double) version); (void) WriteBlobString(image,buffer); if (LocaleCompare(image_info->magick,"PDFA") == 0) { (void) WriteBlobByte(image,'%'); (void) WriteBlobByte(image,0xe2); (void) WriteBlobByte(image,0xe3); (void) WriteBlobByte(image,0xcf); (void) WriteBlobByte(image,0xd3); (void) WriteBlobByte(image,'\n'); } /* Write Catalog object. */ xref[object++]=TellBlob(image); root_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (LocaleCompare(image_info->magick,"PDFA") != 0) (void) FormatLocaleString(buffer,MagickPathExtent,"/Pages %.20g 0 R\n", (double) object+1); else { (void) FormatLocaleString(buffer,MagickPathExtent,"/Metadata %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Pages %.20g 0 R\n", (double) object+2); } (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/Type /Catalog"); option=GetImageOption(image_info,"pdf:page-direction"); if ((option != (const char *) NULL) && (LocaleCompare(option,"right-to-left") == 0)) (void) WriteBlobString(image,"/ViewerPreferences<</PageDirection/R2L>>\n"); (void) WriteBlobString(image,"\n"); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); GetPathComponent(image->filename,BasePath,basename); if (LocaleCompare(image_info->magick,"PDFA") == 0) { char create_date[MagickPathExtent], modify_date[MagickPathExtent], timestamp[MagickPathExtent], *url, xmp_profile[MagickPathExtent]; /* Write XMP object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Subtype /XML\n"); *modify_date='\0'; value=GetImageProperty(image,"date:modify",exception); if (value != (const char *) NULL) (void) CopyMagickString(modify_date,value,MagickPathExtent); *create_date='\0'; value=GetImageProperty(image,"date:create",exception); if (value != (const char *) NULL) (void) CopyMagickString(create_date,value,MagickPathExtent); (void) FormatMagickTime(time((time_t *) NULL),MagickPathExtent,timestamp); url=(char *) MagickAuthoritativeURL; escape=EscapeParenthesis(basename); i=FormatLocaleString(xmp_profile,MagickPathExtent,XMPProfile, XMPProfileMagick,modify_date,create_date,timestamp,url,escape,url); escape=DestroyString(escape); (void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g\n", (double) i); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/Type /Metadata\n"); (void) WriteBlobString(image,">>\nstream\n"); (void) WriteBlobString(image,xmp_profile); (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); } /* Write Pages object. */ xref[object++]=TellBlob(image); pages_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Type /Pages\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Kids [ %.20g 0 R ", (double) object+1); (void) WriteBlobString(image,buffer); count=(ssize_t) (pages_id+ObjectsPerImage+1); page_count=1; if (image_info->adjoin != MagickFalse) { Image *kid_image; /* Predict page object id's. */ kid_image=image; for ( ; GetNextImageInList(kid_image) != (Image *) NULL; count+=ObjectsPerImage) { page_count++; profile=GetImageProfile(kid_image,"icc"); if (profile != (StringInfo *) NULL) count+=2; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 R ",(double) count); (void) WriteBlobString(image,buffer); kid_image=GetNextImageInList(kid_image); } xref=(MagickOffsetType *) ResizeQuantumMemory(xref,(size_t) count+2048UL, sizeof(*xref)); if (xref == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } (void) WriteBlobString(image,"]\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Count %.20g\n",(double) page_count); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); scene=0; imageListLength=GetImageListLength(image); do { MagickBooleanType has_icc_profile; profile=GetImageProfile(image,"icc"); has_icc_profile=(profile != (StringInfo *) NULL) ? MagickTrue : MagickFalse; compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; switch (compression) { case FaxCompression: case Group4Compression: { if ((SetImageMonochrome(image,exception) == MagickFalse) || (image->alpha_trait != UndefinedPixelTrait)) compression=RLECompression; break; } #if !defined(MAGICKCORE_JPEG_DELEGATE) case JPEGCompression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JPEG)", image->filename); break; } #endif #if !defined(MAGICKCORE_LIBOPENJP2_DELEGATE) case JPEG2000Compression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (JP2)", image->filename); break; } #endif #if !defined(MAGICKCORE_ZLIB_DELEGATE) case ZipCompression: { compression=RLECompression; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn","`%s' (ZLIB)", image->filename); break; } #endif case LZWCompression: { if (LocaleCompare(image_info->magick,"PDFA") == 0) compression=RLECompression; /* LZW compression is forbidden */ break; } case NoCompression: { if (LocaleCompare(image_info->magick,"PDFA") == 0) compression=RLECompression; /* ASCII 85 compression is forbidden */ break; } default: break; } if (compression == JPEG2000Compression) (void) TransformImageColorspace(image,sRGBColorspace,exception); /* Scale relative to dots-per-inch. */ delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->resolution.x; resolution.y=image->resolution.y; if ((resolution.x == 0.0) || (resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image->units == PixelsPerCentimeterResolution) { resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0); resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0); } SetGeometry(image,&geometry); (void) FormatLocaleString(page_geometry,MagickPathExtent,"%.20gx%.20g", (double) image->columns,(double) image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MagickPathExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatLocaleString(page_geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); else if ((image->gravity != UndefinedGravity) && (LocaleCompare(image_info->magick,"PDF") == 0)) (void) CopyMagickString(page_geometry,PSPageGeometry, MagickPathExtent); (void) ConcatenateMagickString(page_geometry,">",MagickPathExtent); (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); scale.x=(double) (geometry.width*delta.x)/resolution.x; geometry.width=(size_t) floor(scale.x+0.5); scale.y=(double) (geometry.height*delta.y)/resolution.y; geometry.height=(size_t) floor(scale.y+0.5); (void) ParseAbsoluteGeometry(page_geometry,&media_info); (void) ParseGravityGeometry(image,page_geometry,&page_info,exception); if (image->gravity != UndefinedGravity) { geometry.x=(-page_info.x); geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows); } pointsize=12.0; if (image_info->pointsize != 0.0) pointsize=image_info->pointsize; text_size=0; value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) text_size=(size_t) (MultilineCensus(value)*pointsize+12); (void) text_size; /* Write Page object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Type /Page\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Parent %.20g 0 R\n", (double) pages_id); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/Resources <<\n"); labels=(char **) NULL; value=GetImageProperty(image,"label",exception); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { (void) FormatLocaleString(buffer,MagickPathExtent, "/Font << /F%.20g %.20g 0 R >>\n",(double) image->scene,(double) object+4); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MagickPathExtent, "/XObject << /Im%.20g %.20g 0 R >>\n",(double) image->scene,(double) object+5); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/ProcSet %.20g 0 R >>\n", (double) object+3); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "/MediaBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x, 72.0*media_info.height/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "/CropBox [0 0 %g %g]\n",72.0*media_info.width/resolution.x, 72.0*media_info.height/resolution.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Contents %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Thumb %.20g 0 R\n", (double) object+(has_icc_profile != MagickFalse ? 10 : 8)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Contents object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); (void) WriteBlobString(image,"q\n"); if (labels != (char **) NULL) for (i=0; labels[i] != (char *) NULL; i++) { (void) WriteBlobString(image,"BT\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/F%.20g %g Tf\n", (double) image->scene,pointsize); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g Td\n", (double) geometry.x,(double) (geometry.y+geometry.height+i*pointsize+ 12)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"(%s) Tj\n", labels[i]); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"ET\n"); labels[i]=DestroyString(labels[i]); } (void) FormatLocaleString(buffer,MagickPathExtent, "%g 0 0 %g %.20g %.20g cm\n",scale.x,scale.y,(double) geometry.x, (double) geometry.y); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Im%.20g Do\n",(double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"Q\n"); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write Procset object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) CopyMagickString(buffer,"[ /PDF /Text /ImageC",MagickPathExtent); else if ((compression == FaxCompression) || (compression == Group4Compression)) (void) CopyMagickString(buffer,"[ /PDF /Text /ImageB",MagickPathExtent); else (void) CopyMagickString(buffer,"[ /PDF /Text /ImageI",MagickPathExtent); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image," ]\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Font object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (labels != (char **) NULL) { (void) WriteBlobString(image,"/Type /Font\n"); (void) WriteBlobString(image,"/Subtype /Type1\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Name /F%.20g\n", (double) image->scene); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/BaseFont /Helvetica\n"); (void) WriteBlobString(image,"/Encoding /MacRomanEncoding\n"); labels=(char **) RelinquishMagickMemory(labels); } (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); /* Write XObject object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); (void) WriteBlobString(image,"/Type /XObject\n"); (void) WriteBlobString(image,"/Subtype /Image\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Name /Im%.20g\n", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "ASCII85Decode"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"DCTDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MagickPathExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"JPXDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MagickPathExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "FlateDecode"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/DecodeParms [ << " "/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam, (double) image->columns,(double) image->rows); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Width %.20g\n",(double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Height %.20g\n",(double) image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/ColorSpace %.20g 0 R\n", (double) object+2); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/BitsPerComponent %d\n", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); if (image->alpha_trait != UndefinedPixelTrait) { (void) FormatLocaleString(buffer,MagickPathExtent,"/SMask %.20g 0 R\n", (double) object+(has_icc_profile != MagickFalse ? 9 : 7)); (void) WriteBlobString(image,buffer); } (void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*number_pixels) != (MagickSizeType) ((size_t) (4*number_pixels))) ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,"0") == 0) { (void) HuffmanEncodeImage(image_info,image,image,exception); break; } (void) Huffman2DEncodeImage(image_info,image,image,exception); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,image,"jpeg",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,"jp2",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(image,p))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p)))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,image,"jpeg",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,image,"jp2",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; length*=image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runoffset encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); if (image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelBlack(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed DirectColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(GetPixelRed(image,p))); Ascii85Encode(image,ScaleQuantumToChar(GetPixelGreen(image,p))); Ascii85Encode(image,ScaleQuantumToChar(GetPixelBlue(image,p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlack(image,p))); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } else { /* Dump number of colors and colormap. */ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,(unsigned char) GetPixelIndex(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } Ascii85Flush(image); break; } } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write Colorspace object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); device="DeviceRGB"; channels=0; if (image->colorspace == CMYKColorspace) { device="DeviceCMYK"; channels=4; } else if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse))) { device="DeviceGray"; channels=1; } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) { device="DeviceRGB"; channels=3; } profile=GetImageProfile(image,"icc"); if ((profile == (StringInfo *) NULL) || (channels == 0)) { if (channels != 0) (void) FormatLocaleString(buffer,MagickPathExtent,"/%s\n",device); else (void) FormatLocaleString(buffer,MagickPathExtent, "[ /Indexed /%s %.20g %.20g 0 R ]\n",device,(double) image->colors- 1,(double) object+3); (void) WriteBlobString(image,buffer); } else { const unsigned char *p; /* Write ICC profile. */ (void) FormatLocaleString(buffer,MagickPathExtent, "[/ICCBased %.20g 0 R]\n",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"<<\n/N %.20g\n" "/Filter /ASCII85Decode\n/Length %.20g 0 R\n/Alternate /%s\n>>\n" "stream\n",(double) channels,(double) object+1,device); (void) WriteBlobString(image,buffer); offset=TellBlob(image); Ascii85Initialize(image); p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) Ascii85Encode(image,(unsigned char) *p++); Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"endstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n", (double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"endobj\n"); /* Write Thumb object. */ SetGeometry(image,&geometry); (void) ParseMetaGeometry("106x106+0+0>",&geometry.x,&geometry.y, &geometry.width,&geometry.height); tile_image=ThumbnailImage(image,geometry.width,geometry.height,exception); if (tile_image == (Image *) NULL) return(MagickFalse); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "ASCII85Decode"); break; } case JPEGCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"DCTDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MagickPathExtent); break; } case JPEG2000Compression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"JPXDecode"); if (image->colorspace != CMYKColorspace) break; (void) WriteBlobString(image,buffer); (void) CopyMagickString(buffer,"/Decode [1 0 1 0 1 0 1 0]\n", MagickPathExtent); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat,"LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "FlateDecode"); break; } case FaxCompression: case Group4Compression: { (void) CopyMagickString(buffer,"/Filter [ /CCITTFaxDecode ]\n", MagickPathExtent); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/DecodeParms [ << " "/K %s /BlackIs1 false /Columns %.20g /Rows %.20g >> ]\n",CCITTParam, (double) tile_image->columns,(double) tile_image->rows); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Width %.20g\n",(double) tile_image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Height %.20g\n",(double) tile_image->rows); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/ColorSpace %.20g 0 R\n", (double) object-(has_icc_profile != MagickFalse ? 3 : 1)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/BitsPerComponent %d\n", (compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); number_pixels=(MagickSizeType) tile_image->columns*tile_image->rows; if ((compression == FaxCompression) || (compression == Group4Compression) || ((image_info->type != TrueColorType) && (SetImageGray(tile_image,exception) != MagickFalse))) { switch (compression) { case FaxCompression: case Group4Compression: { if (LocaleCompare(CCITTParam,"0") == 0) { (void) HuffmanEncodeImage(image_info,image,tile_image, exception); break; } (void) Huffman2DEncodeImage(image_info,image,tile_image,exception); break; } case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,"jpeg", exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,"jp2",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma( tile_image,p))); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(tile_image,p)))); p+=GetPixelChannels(tile_image); } } Ascii85Flush(image); break; } } } else if ((tile_image->storage_class == DirectClass) || (tile_image->colors > 256) || (compression == JPEGCompression) || (compression == JPEG2000Compression)) switch (compression) { case JPEGCompression: { status=InjectImageBlob(image_info,image,tile_image,"jpeg", exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case JPEG2000Compression: { status=InjectImageBlob(image_info,image,tile_image,"jp2",exception); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; length*=tile_image->colorspace == CMYKColorspace ? 4UL : 3UL; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelRed(tile_image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(tile_image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(tile_image,p)); if (tile_image->colorspace == CMYKColorspace) *q++=ScaleQuantumToChar(GetPixelBlack(tile_image,p)); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed DirectColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar( GetPixelRed(tile_image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelGreen(tile_image,p))); Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlue(tile_image,p))); if (image->colorspace == CMYKColorspace) Ascii85Encode(image,ScaleQuantumToChar( GetPixelBlack(tile_image,p))); p+=GetPixelChannels(tile_image); } } Ascii85Flush(image); break; } } else { /* Dump number of colors and colormap. */ switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { tile_image=DestroyImage(tile_image); ThrowPDFException(ResourceLimitError, "MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { *q++=(unsigned char) GetPixelIndex(tile_image,p); p+=GetPixelChannels(tile_image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) tile_image->rows; y++) { p=GetVirtualPixels(tile_image,0,y,tile_image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) tile_image->columns; x++) { Ascii85Encode(image,(unsigned char) GetPixelIndex(tile_image,p)); p+=GetPixelChannels(image); } } Ascii85Flush(image); break; } } } tile_image=DestroyImage(tile_image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if ((image->storage_class == DirectClass) || (image->colors > 256) || (compression == FaxCompression) || (compression == Group4Compression)) (void) WriteBlobString(image,">>\n"); else { /* Write Colormap object. */ if (compression == NoCompression) (void) WriteBlobString(image,"/Filter [ /ASCII85Decode ]\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); if (compression == NoCompression) Ascii85Initialize(image); for (i=0; i < (ssize_t) image->colors; i++) { if (compression == NoCompression) { Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].red))); Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].green))); Ascii85Encode(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].blue))); continue; } (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].red))); (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].green))); (void) WriteBlobByte(image,ScaleQuantumToChar( ClampToQuantum(image->colormap[i].blue))); } if (compression == NoCompression) Ascii85Flush(image); offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); } (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); /* Write softmask object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (image->alpha_trait == UndefinedPixelTrait) (void) WriteBlobString(image,">>\n"); else { (void) WriteBlobString(image,"/Type /XObject\n"); (void) WriteBlobString(image,"/Subtype /Image\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Name /Ma%.20g\n", (double) image->scene); (void) WriteBlobString(image,buffer); switch (compression) { case NoCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "ASCII85Decode"); break; } case LZWCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "LZWDecode"); break; } case ZipCompression: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "FlateDecode"); break; } default: { (void) FormatLocaleString(buffer,MagickPathExtent,CFormat, "RunLengthDecode"); break; } } (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Width %.20g\n", (double) image->columns); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Height %.20g\n", (double) image->rows); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"/ColorSpace /DeviceGray\n"); (void) FormatLocaleString(buffer,MagickPathExtent, "/BitsPerComponent %d\n",(compression == FaxCompression) || (compression == Group4Compression) ? 1 : 8); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Length %.20g 0 R\n", (double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"stream\n"); offset=TellBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; switch (compression) { case RLECompression: default: { MemoryInfo *pixel_info; /* Allocate pixel array. */ length=(size_t) number_pixels; pixel_info=AcquireVirtualMemory(length,4*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) { image=DestroyImage(image); ThrowPDFException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Dump Runlength encoded pixels. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } #if defined(MAGICKCORE_ZLIB_DELEGATE) if (compression == ZipCompression) status=ZLIBEncodeImage(image,length,pixels,exception); else #endif if (compression == LZWCompression) status=LZWEncodeImage(image,length,pixels,exception); else status=PackbitsEncodeImage(image,length,pixels,exception); pixel_info=RelinquishVirtualMemory(pixel_info); if (status == MagickFalse) { xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickFalse); } break; } case NoCompression: { /* Dump uncompressed PseudoColor packets. */ Ascii85Initialize(image); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { Ascii85Encode(image,ScaleQuantumToChar(GetPixelAlpha(image,p))); p+=GetPixelChannels(image); } } Ascii85Flush(image); break; } } offset=TellBlob(image)-offset; (void) WriteBlobString(image,"\nendstream\n"); } (void) WriteBlobString(image,"endobj\n"); /* Write Length object. */ xref[object++]=TellBlob(image); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"endobj\n"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); /* Write Metadata object. */ xref[object++]=TellBlob(image); info_id=object; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g 0 obj\n",(double) object); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"<<\n"); if (LocaleCompare(image_info->magick,"PDFA") == 0) (void) FormatLocaleString(buffer,MagickPathExtent,"/Title (%s)\n", EscapeParenthesis(basename)); else { wchar_t *utf16; utf16=ConvertUTF8ToUTF16((unsigned char *) basename,&length); if (utf16 != (wchar_t *) NULL) { (void) FormatLocaleString(buffer,MagickPathExtent,"/Title (\xfe\xff"); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) length; i++) (void) WriteBlobMSBShort(image,(unsigned short) utf16[i]); (void) FormatLocaleString(buffer,MagickPathExtent,")\n"); utf16=(wchar_t *) RelinquishMagickMemory(utf16); } } (void) WriteBlobString(image,buffer); seconds=time((time_t *) NULL); #if defined(MAGICKCORE_HAVE_LOCALTIME_R) (void) localtime_r(&seconds,&local_time); #else (void) memcpy(&local_time,localtime(&seconds),sizeof(local_time)); #endif (void) FormatLocaleString(date,MagickPathExtent,"D:%04d%02d%02d%02d%02d%02d", local_time.tm_year+1900,local_time.tm_mon+1,local_time.tm_mday, local_time.tm_hour,local_time.tm_min,local_time.tm_sec); (void) FormatLocaleString(buffer,MagickPathExtent,"/CreationDate (%s)\n", date); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/ModDate (%s)\n",date); (void) WriteBlobString(image,buffer); url=(char *) MagickAuthoritativeURL; escape=EscapeParenthesis(url); (void) FormatLocaleString(buffer,MagickPathExtent,"/Producer (%s)\n",escape); escape=DestroyString(escape); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"endobj\n"); /* Write Xref object. */ offset=TellBlob(image)-xref[0]+ (LocaleCompare(image_info->magick,"PDFA") == 0 ? 6 : 0)+10; (void) WriteBlobString(image,"xref\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"0 %.20g\n",(double) object+1); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"0000000000 65535 f \n"); for (i=0; i < (ssize_t) object; i++) { (void) FormatLocaleString(buffer,MagickPathExtent,"%010lu 00000 n \n", (unsigned long) xref[i]); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"trailer\n"); (void) WriteBlobString(image,"<<\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"/Size %.20g\n",(double) object+1); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Info %.20g 0 R\n",(double) info_id); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent,"/Root %.20g 0 R\n",(double) root_id); (void) WriteBlobString(image,buffer); (void) SignatureImage(image,exception); (void) FormatLocaleString(buffer,MagickPathExtent,"/ID [<%s> <%s>]\n", GetImageProperty(image,"signature",exception), GetImageProperty(image,"signature",exception)); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,">>\n"); (void) WriteBlobString(image,"startxref\n"); (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) offset); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"%%EOF\n"); xref=(MagickOffsetType *) RelinquishMagickMemory(xref); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-399/c/good_1416_0
crossvul-cpp_data_good_3471_0
/* * linux/fs/lockd/clntproc.c * * RPC procedures for the client side NLM implementation * * Copyright (C) 1996, Olaf Kirch <okir@monad.swb.de> */ #include <linux/module.h> #include <linux/slab.h> #include <linux/types.h> #include <linux/errno.h> #include <linux/fs.h> #include <linux/nfs_fs.h> #include <linux/utsname.h> #include <linux/freezer.h> #include <linux/sunrpc/clnt.h> #include <linux/sunrpc/svc.h> #include <linux/lockd/lockd.h> #define NLMDBG_FACILITY NLMDBG_CLIENT #define NLMCLNT_GRACE_WAIT (5*HZ) #define NLMCLNT_POLL_TIMEOUT (30*HZ) #define NLMCLNT_MAX_RETRIES 3 static int nlmclnt_test(struct nlm_rqst *, struct file_lock *); static int nlmclnt_lock(struct nlm_rqst *, struct file_lock *); static int nlmclnt_unlock(struct nlm_rqst *, struct file_lock *); static int nlm_stat_to_errno(__be32 stat); static void nlmclnt_locks_init_private(struct file_lock *fl, struct nlm_host *host); static int nlmclnt_cancel(struct nlm_host *, int , struct file_lock *); static const struct rpc_call_ops nlmclnt_unlock_ops; static const struct rpc_call_ops nlmclnt_cancel_ops; /* * Cookie counter for NLM requests */ static atomic_t nlm_cookie = ATOMIC_INIT(0x1234); void nlmclnt_next_cookie(struct nlm_cookie *c) { u32 cookie = atomic_inc_return(&nlm_cookie); memcpy(c->data, &cookie, 4); c->len=4; } static struct nlm_lockowner *nlm_get_lockowner(struct nlm_lockowner *lockowner) { atomic_inc(&lockowner->count); return lockowner; } static void nlm_put_lockowner(struct nlm_lockowner *lockowner) { if (!atomic_dec_and_lock(&lockowner->count, &lockowner->host->h_lock)) return; list_del(&lockowner->list); spin_unlock(&lockowner->host->h_lock); nlmclnt_release_host(lockowner->host); kfree(lockowner); } static inline int nlm_pidbusy(struct nlm_host *host, uint32_t pid) { struct nlm_lockowner *lockowner; list_for_each_entry(lockowner, &host->h_lockowners, list) { if (lockowner->pid == pid) return -EBUSY; } return 0; } static inline uint32_t __nlm_alloc_pid(struct nlm_host *host) { uint32_t res; do { res = host->h_pidcount++; } while (nlm_pidbusy(host, res) < 0); return res; } static struct nlm_lockowner *__nlm_find_lockowner(struct nlm_host *host, fl_owner_t owner) { struct nlm_lockowner *lockowner; list_for_each_entry(lockowner, &host->h_lockowners, list) { if (lockowner->owner != owner) continue; return nlm_get_lockowner(lockowner); } return NULL; } static struct nlm_lockowner *nlm_find_lockowner(struct nlm_host *host, fl_owner_t owner) { struct nlm_lockowner *res, *new = NULL; spin_lock(&host->h_lock); res = __nlm_find_lockowner(host, owner); if (res == NULL) { spin_unlock(&host->h_lock); new = kmalloc(sizeof(*new), GFP_KERNEL); spin_lock(&host->h_lock); res = __nlm_find_lockowner(host, owner); if (res == NULL && new != NULL) { res = new; atomic_set(&new->count, 1); new->owner = owner; new->pid = __nlm_alloc_pid(host); new->host = nlm_get_host(host); list_add(&new->list, &host->h_lockowners); new = NULL; } } spin_unlock(&host->h_lock); kfree(new); return res; } /* * Initialize arguments for TEST/LOCK/UNLOCK/CANCEL calls */ static void nlmclnt_setlockargs(struct nlm_rqst *req, struct file_lock *fl) { struct nlm_args *argp = &req->a_args; struct nlm_lock *lock = &argp->lock; nlmclnt_next_cookie(&argp->cookie); memcpy(&lock->fh, NFS_FH(fl->fl_file->f_path.dentry->d_inode), sizeof(struct nfs_fh)); lock->caller = utsname()->nodename; lock->oh.data = req->a_owner; lock->oh.len = snprintf(req->a_owner, sizeof(req->a_owner), "%u@%s", (unsigned int)fl->fl_u.nfs_fl.owner->pid, utsname()->nodename); lock->svid = fl->fl_u.nfs_fl.owner->pid; lock->fl.fl_start = fl->fl_start; lock->fl.fl_end = fl->fl_end; lock->fl.fl_type = fl->fl_type; } static void nlmclnt_release_lockargs(struct nlm_rqst *req) { BUG_ON(req->a_args.lock.fl.fl_ops != NULL); } /** * nlmclnt_proc - Perform a single client-side lock request * @host: address of a valid nlm_host context representing the NLM server * @cmd: fcntl-style file lock operation to perform * @fl: address of arguments for the lock operation * */ int nlmclnt_proc(struct nlm_host *host, int cmd, struct file_lock *fl) { struct nlm_rqst *call; int status; nlm_get_host(host); call = nlm_alloc_call(host); if (call == NULL) return -ENOMEM; nlmclnt_locks_init_private(fl, host); /* Set up the argument struct */ nlmclnt_setlockargs(call, fl); if (IS_SETLK(cmd) || IS_SETLKW(cmd)) { if (fl->fl_type != F_UNLCK) { call->a_args.block = IS_SETLKW(cmd) ? 1 : 0; status = nlmclnt_lock(call, fl); } else status = nlmclnt_unlock(call, fl); } else if (IS_GETLK(cmd)) status = nlmclnt_test(call, fl); else status = -EINVAL; fl->fl_ops->fl_release_private(fl); fl->fl_ops = NULL; dprintk("lockd: clnt proc returns %d\n", status); return status; } EXPORT_SYMBOL_GPL(nlmclnt_proc); /* * Allocate an NLM RPC call struct * * Note: the caller must hold a reference to host. In case of failure, * this reference will be released. */ struct nlm_rqst *nlm_alloc_call(struct nlm_host *host) { struct nlm_rqst *call; for(;;) { call = kzalloc(sizeof(*call), GFP_KERNEL); if (call != NULL) { atomic_set(&call->a_count, 1); locks_init_lock(&call->a_args.lock.fl); locks_init_lock(&call->a_res.lock.fl); call->a_host = host; return call; } if (signalled()) break; printk("nlm_alloc_call: failed, waiting for memory\n"); schedule_timeout_interruptible(5*HZ); } nlmclnt_release_host(host); return NULL; } void nlmclnt_release_call(struct nlm_rqst *call) { if (!atomic_dec_and_test(&call->a_count)) return; nlmclnt_release_host(call->a_host); nlmclnt_release_lockargs(call); kfree(call); } static void nlmclnt_rpc_release(void *data) { nlmclnt_release_call(data); } static int nlm_wait_on_grace(wait_queue_head_t *queue) { DEFINE_WAIT(wait); int status = -EINTR; prepare_to_wait(queue, &wait, TASK_INTERRUPTIBLE); if (!signalled ()) { schedule_timeout(NLMCLNT_GRACE_WAIT); try_to_freeze(); if (!signalled ()) status = 0; } finish_wait(queue, &wait); return status; } /* * Generic NLM call */ static int nlmclnt_call(struct rpc_cred *cred, struct nlm_rqst *req, u32 proc) { struct nlm_host *host = req->a_host; struct rpc_clnt *clnt; struct nlm_args *argp = &req->a_args; struct nlm_res *resp = &req->a_res; struct rpc_message msg = { .rpc_argp = argp, .rpc_resp = resp, .rpc_cred = cred, }; int status; dprintk("lockd: call procedure %d on %s\n", (int)proc, host->h_name); do { if (host->h_reclaiming && !argp->reclaim) goto in_grace_period; /* If we have no RPC client yet, create one. */ if ((clnt = nlm_bind_host(host)) == NULL) return -ENOLCK; msg.rpc_proc = &clnt->cl_procinfo[proc]; /* Perform the RPC call. If an error occurs, try again */ if ((status = rpc_call_sync(clnt, &msg, 0)) < 0) { dprintk("lockd: rpc_call returned error %d\n", -status); switch (status) { case -EPROTONOSUPPORT: status = -EINVAL; break; case -ECONNREFUSED: case -ETIMEDOUT: case -ENOTCONN: nlm_rebind_host(host); status = -EAGAIN; break; case -ERESTARTSYS: return signalled () ? -EINTR : status; default: break; } break; } else if (resp->status == nlm_lck_denied_grace_period) { dprintk("lockd: server in grace period\n"); if (argp->reclaim) { printk(KERN_WARNING "lockd: spurious grace period reject?!\n"); return -ENOLCK; } } else { if (!argp->reclaim) { /* We appear to be out of the grace period */ wake_up_all(&host->h_gracewait); } dprintk("lockd: server returns status %d\n", resp->status); return 0; /* Okay, call complete */ } in_grace_period: /* * The server has rebooted and appears to be in the grace * period during which locks are only allowed to be * reclaimed. * We can only back off and try again later. */ status = nlm_wait_on_grace(&host->h_gracewait); } while (status == 0); return status; } /* * Generic NLM call, async version. */ static struct rpc_task *__nlm_async_call(struct nlm_rqst *req, u32 proc, struct rpc_message *msg, const struct rpc_call_ops *tk_ops) { struct nlm_host *host = req->a_host; struct rpc_clnt *clnt; struct rpc_task_setup task_setup_data = { .rpc_message = msg, .callback_ops = tk_ops, .callback_data = req, .flags = RPC_TASK_ASYNC, }; dprintk("lockd: call procedure %d on %s (async)\n", (int)proc, host->h_name); /* If we have no RPC client yet, create one. */ clnt = nlm_bind_host(host); if (clnt == NULL) goto out_err; msg->rpc_proc = &clnt->cl_procinfo[proc]; task_setup_data.rpc_client = clnt; /* bootstrap and kick off the async RPC call */ return rpc_run_task(&task_setup_data); out_err: tk_ops->rpc_release(req); return ERR_PTR(-ENOLCK); } static int nlm_do_async_call(struct nlm_rqst *req, u32 proc, struct rpc_message *msg, const struct rpc_call_ops *tk_ops) { struct rpc_task *task; task = __nlm_async_call(req, proc, msg, tk_ops); if (IS_ERR(task)) return PTR_ERR(task); rpc_put_task(task); return 0; } /* * NLM asynchronous call. */ int nlm_async_call(struct nlm_rqst *req, u32 proc, const struct rpc_call_ops *tk_ops) { struct rpc_message msg = { .rpc_argp = &req->a_args, .rpc_resp = &req->a_res, }; return nlm_do_async_call(req, proc, &msg, tk_ops); } int nlm_async_reply(struct nlm_rqst *req, u32 proc, const struct rpc_call_ops *tk_ops) { struct rpc_message msg = { .rpc_argp = &req->a_res, }; return nlm_do_async_call(req, proc, &msg, tk_ops); } /* * NLM client asynchronous call. * * Note that although the calls are asynchronous, and are therefore * guaranteed to complete, we still always attempt to wait for * completion in order to be able to correctly track the lock * state. */ static int nlmclnt_async_call(struct rpc_cred *cred, struct nlm_rqst *req, u32 proc, const struct rpc_call_ops *tk_ops) { struct rpc_message msg = { .rpc_argp = &req->a_args, .rpc_resp = &req->a_res, .rpc_cred = cred, }; struct rpc_task *task; int err; task = __nlm_async_call(req, proc, &msg, tk_ops); if (IS_ERR(task)) return PTR_ERR(task); err = rpc_wait_for_completion_task(task); rpc_put_task(task); return err; } /* * TEST for the presence of a conflicting lock */ static int nlmclnt_test(struct nlm_rqst *req, struct file_lock *fl) { int status; status = nlmclnt_call(nfs_file_cred(fl->fl_file), req, NLMPROC_TEST); if (status < 0) goto out; switch (req->a_res.status) { case nlm_granted: fl->fl_type = F_UNLCK; break; case nlm_lck_denied: /* * Report the conflicting lock back to the application. */ fl->fl_start = req->a_res.lock.fl.fl_start; fl->fl_end = req->a_res.lock.fl.fl_end; fl->fl_type = req->a_res.lock.fl.fl_type; fl->fl_pid = 0; break; default: status = nlm_stat_to_errno(req->a_res.status); } out: nlmclnt_release_call(req); return status; } static void nlmclnt_locks_copy_lock(struct file_lock *new, struct file_lock *fl) { spin_lock(&fl->fl_u.nfs_fl.owner->host->h_lock); new->fl_u.nfs_fl.state = fl->fl_u.nfs_fl.state; new->fl_u.nfs_fl.owner = nlm_get_lockowner(fl->fl_u.nfs_fl.owner); list_add_tail(&new->fl_u.nfs_fl.list, &fl->fl_u.nfs_fl.owner->host->h_granted); spin_unlock(&fl->fl_u.nfs_fl.owner->host->h_lock); } static void nlmclnt_locks_release_private(struct file_lock *fl) { spin_lock(&fl->fl_u.nfs_fl.owner->host->h_lock); list_del(&fl->fl_u.nfs_fl.list); spin_unlock(&fl->fl_u.nfs_fl.owner->host->h_lock); nlm_put_lockowner(fl->fl_u.nfs_fl.owner); } static const struct file_lock_operations nlmclnt_lock_ops = { .fl_copy_lock = nlmclnt_locks_copy_lock, .fl_release_private = nlmclnt_locks_release_private, }; static void nlmclnt_locks_init_private(struct file_lock *fl, struct nlm_host *host) { BUG_ON(fl->fl_ops != NULL); fl->fl_u.nfs_fl.state = 0; fl->fl_u.nfs_fl.owner = nlm_find_lockowner(host, fl->fl_owner); INIT_LIST_HEAD(&fl->fl_u.nfs_fl.list); fl->fl_ops = &nlmclnt_lock_ops; } static int do_vfs_lock(struct file_lock *fl) { int res = 0; switch (fl->fl_flags & (FL_POSIX|FL_FLOCK)) { case FL_POSIX: res = posix_lock_file_wait(fl->fl_file, fl); break; case FL_FLOCK: res = flock_lock_file_wait(fl->fl_file, fl); break; default: BUG(); } return res; } /* * LOCK: Try to create a lock * * Programmer Harassment Alert * * When given a blocking lock request in a sync RPC call, the HPUX lockd * will faithfully return LCK_BLOCKED but never cares to notify us when * the lock could be granted. This way, our local process could hang * around forever waiting for the callback. * * Solution A: Implement busy-waiting * Solution B: Use the async version of the call (NLM_LOCK_{MSG,RES}) * * For now I am implementing solution A, because I hate the idea of * re-implementing lockd for a third time in two months. The async * calls shouldn't be too hard to do, however. * * This is one of the lovely things about standards in the NFS area: * they're so soft and squishy you can't really blame HP for doing this. */ static int nlmclnt_lock(struct nlm_rqst *req, struct file_lock *fl) { struct rpc_cred *cred = nfs_file_cred(fl->fl_file); struct nlm_host *host = req->a_host; struct nlm_res *resp = &req->a_res; struct nlm_wait *block = NULL; unsigned char fl_flags = fl->fl_flags; unsigned char fl_type; int status = -ENOLCK; if (nsm_monitor(host) < 0) goto out; req->a_args.state = nsm_local_state; fl->fl_flags |= FL_ACCESS; status = do_vfs_lock(fl); fl->fl_flags = fl_flags; if (status < 0) goto out; block = nlmclnt_prepare_block(host, fl); again: /* * Initialise resp->status to a valid non-zero value, * since 0 == nlm_lck_granted */ resp->status = nlm_lck_blocked; for(;;) { /* Reboot protection */ fl->fl_u.nfs_fl.state = host->h_state; status = nlmclnt_call(cred, req, NLMPROC_LOCK); if (status < 0) break; /* Did a reclaimer thread notify us of a server reboot? */ if (resp->status == nlm_lck_denied_grace_period) continue; if (resp->status != nlm_lck_blocked) break; /* Wait on an NLM blocking lock */ status = nlmclnt_block(block, req, NLMCLNT_POLL_TIMEOUT); if (status < 0) break; if (resp->status != nlm_lck_blocked) break; } /* if we were interrupted while blocking, then cancel the lock request * and exit */ if (resp->status == nlm_lck_blocked) { if (!req->a_args.block) goto out_unlock; if (nlmclnt_cancel(host, req->a_args.block, fl) == 0) goto out_unblock; } if (resp->status == nlm_granted) { down_read(&host->h_rwsem); /* Check whether or not the server has rebooted */ if (fl->fl_u.nfs_fl.state != host->h_state) { up_read(&host->h_rwsem); goto again; } /* Ensure the resulting lock will get added to granted list */ fl->fl_flags |= FL_SLEEP; if (do_vfs_lock(fl) < 0) printk(KERN_WARNING "%s: VFS is out of sync with lock manager!\n", __func__); up_read(&host->h_rwsem); fl->fl_flags = fl_flags; status = 0; } if (status < 0) goto out_unlock; /* * EAGAIN doesn't make sense for sleeping locks, and in some * cases NLM_LCK_DENIED is returned for a permanent error. So * turn it into an ENOLCK. */ if (resp->status == nlm_lck_denied && (fl_flags & FL_SLEEP)) status = -ENOLCK; else status = nlm_stat_to_errno(resp->status); out_unblock: nlmclnt_finish_block(block); out: nlmclnt_release_call(req); return status; out_unlock: /* Fatal error: ensure that we remove the lock altogether */ dprintk("lockd: lock attempt ended in fatal error.\n" " Attempting to unlock.\n"); nlmclnt_finish_block(block); fl_type = fl->fl_type; fl->fl_type = F_UNLCK; down_read(&host->h_rwsem); do_vfs_lock(fl); up_read(&host->h_rwsem); fl->fl_type = fl_type; fl->fl_flags = fl_flags; nlmclnt_async_call(cred, req, NLMPROC_UNLOCK, &nlmclnt_unlock_ops); return status; } /* * RECLAIM: Try to reclaim a lock */ int nlmclnt_reclaim(struct nlm_host *host, struct file_lock *fl) { struct nlm_rqst reqst, *req; int status; req = &reqst; memset(req, 0, sizeof(*req)); locks_init_lock(&req->a_args.lock.fl); locks_init_lock(&req->a_res.lock.fl); req->a_host = host; req->a_flags = 0; /* Set up the argument struct */ nlmclnt_setlockargs(req, fl); req->a_args.reclaim = 1; status = nlmclnt_call(nfs_file_cred(fl->fl_file), req, NLMPROC_LOCK); if (status >= 0 && req->a_res.status == nlm_granted) return 0; printk(KERN_WARNING "lockd: failed to reclaim lock for pid %d " "(errno %d, status %d)\n", fl->fl_pid, status, ntohl(req->a_res.status)); /* * FIXME: This is a serious failure. We can * * a. Ignore the problem * b. Send the owning process some signal (Linux doesn't have * SIGLOST, though...) * c. Retry the operation * * Until someone comes up with a simple implementation * for b or c, I'll choose option a. */ return -ENOLCK; } /* * UNLOCK: remove an existing lock */ static int nlmclnt_unlock(struct nlm_rqst *req, struct file_lock *fl) { struct nlm_host *host = req->a_host; struct nlm_res *resp = &req->a_res; int status; unsigned char fl_flags = fl->fl_flags; /* * Note: the server is supposed to either grant us the unlock * request, or to deny it with NLM_LCK_DENIED_GRACE_PERIOD. In either * case, we want to unlock. */ fl->fl_flags |= FL_EXISTS; down_read(&host->h_rwsem); status = do_vfs_lock(fl); up_read(&host->h_rwsem); fl->fl_flags = fl_flags; if (status == -ENOENT) { status = 0; goto out; } atomic_inc(&req->a_count); status = nlmclnt_async_call(nfs_file_cred(fl->fl_file), req, NLMPROC_UNLOCK, &nlmclnt_unlock_ops); if (status < 0) goto out; if (resp->status == nlm_granted) goto out; if (resp->status != nlm_lck_denied_nolocks) printk("lockd: unexpected unlock status: %d\n", resp->status); /* What to do now? I'm out of my depth... */ status = -ENOLCK; out: nlmclnt_release_call(req); return status; } static void nlmclnt_unlock_callback(struct rpc_task *task, void *data) { struct nlm_rqst *req = data; u32 status = ntohl(req->a_res.status); if (RPC_ASSASSINATED(task)) goto die; if (task->tk_status < 0) { dprintk("lockd: unlock failed (err = %d)\n", -task->tk_status); switch (task->tk_status) { case -EACCES: case -EIO: goto die; default: goto retry_rebind; } } if (status == NLM_LCK_DENIED_GRACE_PERIOD) { rpc_delay(task, NLMCLNT_GRACE_WAIT); goto retry_unlock; } if (status != NLM_LCK_GRANTED) printk(KERN_WARNING "lockd: unexpected unlock status: %d\n", status); die: return; retry_rebind: nlm_rebind_host(req->a_host); retry_unlock: rpc_restart_call(task); } static const struct rpc_call_ops nlmclnt_unlock_ops = { .rpc_call_done = nlmclnt_unlock_callback, .rpc_release = nlmclnt_rpc_release, }; /* * Cancel a blocked lock request. * We always use an async RPC call for this in order not to hang a * process that has been Ctrl-C'ed. */ static int nlmclnt_cancel(struct nlm_host *host, int block, struct file_lock *fl) { struct nlm_rqst *req; int status; dprintk("lockd: blocking lock attempt was interrupted by a signal.\n" " Attempting to cancel lock.\n"); req = nlm_alloc_call(nlm_get_host(host)); if (!req) return -ENOMEM; req->a_flags = RPC_TASK_ASYNC; nlmclnt_setlockargs(req, fl); req->a_args.block = block; atomic_inc(&req->a_count); status = nlmclnt_async_call(nfs_file_cred(fl->fl_file), req, NLMPROC_CANCEL, &nlmclnt_cancel_ops); if (status == 0 && req->a_res.status == nlm_lck_denied) status = -ENOLCK; nlmclnt_release_call(req); return status; } static void nlmclnt_cancel_callback(struct rpc_task *task, void *data) { struct nlm_rqst *req = data; u32 status = ntohl(req->a_res.status); if (RPC_ASSASSINATED(task)) goto die; if (task->tk_status < 0) { dprintk("lockd: CANCEL call error %d, retrying.\n", task->tk_status); goto retry_cancel; } dprintk("lockd: cancel status %u (task %u)\n", status, task->tk_pid); switch (status) { case NLM_LCK_GRANTED: case NLM_LCK_DENIED_GRACE_PERIOD: case NLM_LCK_DENIED: /* Everything's good */ break; case NLM_LCK_DENIED_NOLOCKS: dprintk("lockd: CANCEL failed (server has no locks)\n"); goto retry_cancel; default: printk(KERN_NOTICE "lockd: weird return %d for CANCEL call\n", status); } die: return; retry_cancel: /* Don't ever retry more than 3 times */ if (req->a_retries++ >= NLMCLNT_MAX_RETRIES) goto die; nlm_rebind_host(req->a_host); rpc_restart_call(task); rpc_delay(task, 30 * HZ); } static const struct rpc_call_ops nlmclnt_cancel_ops = { .rpc_call_done = nlmclnt_cancel_callback, .rpc_release = nlmclnt_rpc_release, }; /* * Convert an NLM status code to a generic kernel errno */ static int nlm_stat_to_errno(__be32 status) { switch(ntohl(status)) { case NLM_LCK_GRANTED: return 0; case NLM_LCK_DENIED: return -EAGAIN; case NLM_LCK_DENIED_NOLOCKS: case NLM_LCK_DENIED_GRACE_PERIOD: return -ENOLCK; case NLM_LCK_BLOCKED: printk(KERN_NOTICE "lockd: unexpected status NLM_BLOCKED\n"); return -ENOLCK; #ifdef CONFIG_LOCKD_V4 case NLM_DEADLCK: return -EDEADLK; case NLM_ROFS: return -EROFS; case NLM_STALE_FH: return -ESTALE; case NLM_FBIG: return -EOVERFLOW; case NLM_FAILED: return -ENOLCK; #endif } printk(KERN_NOTICE "lockd: unexpected server status %d\n", status); return -ENOLCK; }
./CrossVul/dataset_final_sorted/CWE-399/c/good_3471_0
crossvul-cpp_data_bad_3573_0
/* * An async IO implementation for Linux * Written by Benjamin LaHaise <bcrl@kvack.org> * * Implements an efficient asynchronous io interface. * * Copyright 2000, 2001, 2002 Red Hat, Inc. All Rights Reserved. * * See ../COPYING for licensing terms. */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/errno.h> #include <linux/time.h> #include <linux/aio_abi.h> #include <linux/module.h> #include <linux/syscalls.h> #include <linux/backing-dev.h> #include <linux/uio.h> #define DEBUG 0 #include <linux/sched.h> #include <linux/fs.h> #include <linux/file.h> #include <linux/mm.h> #include <linux/mman.h> #include <linux/mmu_context.h> #include <linux/slab.h> #include <linux/timer.h> #include <linux/aio.h> #include <linux/highmem.h> #include <linux/workqueue.h> #include <linux/security.h> #include <linux/eventfd.h> #include <linux/blkdev.h> #include <linux/compat.h> #include <asm/kmap_types.h> #include <asm/uaccess.h> #if DEBUG > 1 #define dprintk printk #else #define dprintk(x...) do { ; } while (0) #endif /*------ sysctl variables----*/ static DEFINE_SPINLOCK(aio_nr_lock); unsigned long aio_nr; /* current system wide number of aio requests */ unsigned long aio_max_nr = 0x10000; /* system wide maximum number of aio requests */ /*----end sysctl variables---*/ static struct kmem_cache *kiocb_cachep; static struct kmem_cache *kioctx_cachep; static struct workqueue_struct *aio_wq; /* Used for rare fput completion. */ static void aio_fput_routine(struct work_struct *); static DECLARE_WORK(fput_work, aio_fput_routine); static DEFINE_SPINLOCK(fput_lock); static LIST_HEAD(fput_head); static void aio_kick_handler(struct work_struct *); static void aio_queue_work(struct kioctx *); /* aio_setup * Creates the slab caches used by the aio routines, panic on * failure as this is done early during the boot sequence. */ static int __init aio_setup(void) { kiocb_cachep = KMEM_CACHE(kiocb, SLAB_HWCACHE_ALIGN|SLAB_PANIC); kioctx_cachep = KMEM_CACHE(kioctx,SLAB_HWCACHE_ALIGN|SLAB_PANIC); aio_wq = alloc_workqueue("aio", 0, 1); /* used to limit concurrency */ BUG_ON(!aio_wq); pr_debug("aio_setup: sizeof(struct page) = %d\n", (int)sizeof(struct page)); return 0; } __initcall(aio_setup); static void aio_free_ring(struct kioctx *ctx) { struct aio_ring_info *info = &ctx->ring_info; long i; for (i=0; i<info->nr_pages; i++) put_page(info->ring_pages[i]); if (info->mmap_size) { down_write(&ctx->mm->mmap_sem); do_munmap(ctx->mm, info->mmap_base, info->mmap_size); up_write(&ctx->mm->mmap_sem); } if (info->ring_pages && info->ring_pages != info->internal_pages) kfree(info->ring_pages); info->ring_pages = NULL; info->nr = 0; } static int aio_setup_ring(struct kioctx *ctx) { struct aio_ring *ring; struct aio_ring_info *info = &ctx->ring_info; unsigned nr_events = ctx->max_reqs; unsigned long size; int nr_pages; /* Compensate for the ring buffer's head/tail overlap entry */ nr_events += 2; /* 1 is required, 2 for good luck */ size = sizeof(struct aio_ring); size += sizeof(struct io_event) * nr_events; nr_pages = (size + PAGE_SIZE-1) >> PAGE_SHIFT; if (nr_pages < 0) return -EINVAL; nr_events = (PAGE_SIZE * nr_pages - sizeof(struct aio_ring)) / sizeof(struct io_event); info->nr = 0; info->ring_pages = info->internal_pages; if (nr_pages > AIO_RING_PAGES) { info->ring_pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL); if (!info->ring_pages) return -ENOMEM; } info->mmap_size = nr_pages * PAGE_SIZE; dprintk("attempting mmap of %lu bytes\n", info->mmap_size); down_write(&ctx->mm->mmap_sem); info->mmap_base = do_mmap(NULL, 0, info->mmap_size, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_PRIVATE, 0); if (IS_ERR((void *)info->mmap_base)) { up_write(&ctx->mm->mmap_sem); info->mmap_size = 0; aio_free_ring(ctx); return -EAGAIN; } dprintk("mmap address: 0x%08lx\n", info->mmap_base); info->nr_pages = get_user_pages(current, ctx->mm, info->mmap_base, nr_pages, 1, 0, info->ring_pages, NULL); up_write(&ctx->mm->mmap_sem); if (unlikely(info->nr_pages != nr_pages)) { aio_free_ring(ctx); return -EAGAIN; } ctx->user_id = info->mmap_base; info->nr = nr_events; /* trusted copy */ ring = kmap_atomic(info->ring_pages[0], KM_USER0); ring->nr = nr_events; /* user copy */ ring->id = ctx->user_id; ring->head = ring->tail = 0; ring->magic = AIO_RING_MAGIC; ring->compat_features = AIO_RING_COMPAT_FEATURES; ring->incompat_features = AIO_RING_INCOMPAT_FEATURES; ring->header_length = sizeof(struct aio_ring); kunmap_atomic(ring, KM_USER0); return 0; } /* aio_ring_event: returns a pointer to the event at the given index from * kmap_atomic(, km). Release the pointer with put_aio_ring_event(); */ #define AIO_EVENTS_PER_PAGE (PAGE_SIZE / sizeof(struct io_event)) #define AIO_EVENTS_FIRST_PAGE ((PAGE_SIZE - sizeof(struct aio_ring)) / sizeof(struct io_event)) #define AIO_EVENTS_OFFSET (AIO_EVENTS_PER_PAGE - AIO_EVENTS_FIRST_PAGE) #define aio_ring_event(info, nr, km) ({ \ unsigned pos = (nr) + AIO_EVENTS_OFFSET; \ struct io_event *__event; \ __event = kmap_atomic( \ (info)->ring_pages[pos / AIO_EVENTS_PER_PAGE], km); \ __event += pos % AIO_EVENTS_PER_PAGE; \ __event; \ }) #define put_aio_ring_event(event, km) do { \ struct io_event *__event = (event); \ (void)__event; \ kunmap_atomic((void *)((unsigned long)__event & PAGE_MASK), km); \ } while(0) static void ctx_rcu_free(struct rcu_head *head) { struct kioctx *ctx = container_of(head, struct kioctx, rcu_head); unsigned nr_events = ctx->max_reqs; kmem_cache_free(kioctx_cachep, ctx); if (nr_events) { spin_lock(&aio_nr_lock); BUG_ON(aio_nr - nr_events > aio_nr); aio_nr -= nr_events; spin_unlock(&aio_nr_lock); } } /* __put_ioctx * Called when the last user of an aio context has gone away, * and the struct needs to be freed. */ static void __put_ioctx(struct kioctx *ctx) { BUG_ON(ctx->reqs_active); cancel_delayed_work(&ctx->wq); cancel_work_sync(&ctx->wq.work); aio_free_ring(ctx); mmdrop(ctx->mm); ctx->mm = NULL; pr_debug("__put_ioctx: freeing %p\n", ctx); call_rcu(&ctx->rcu_head, ctx_rcu_free); } static inline void get_ioctx(struct kioctx *kioctx) { BUG_ON(atomic_read(&kioctx->users) <= 0); atomic_inc(&kioctx->users); } static inline int try_get_ioctx(struct kioctx *kioctx) { return atomic_inc_not_zero(&kioctx->users); } static inline void put_ioctx(struct kioctx *kioctx) { BUG_ON(atomic_read(&kioctx->users) <= 0); if (unlikely(atomic_dec_and_test(&kioctx->users))) __put_ioctx(kioctx); } /* ioctx_alloc * Allocates and initializes an ioctx. Returns an ERR_PTR if it failed. */ static struct kioctx *ioctx_alloc(unsigned nr_events) { struct mm_struct *mm; struct kioctx *ctx; int did_sync = 0; /* Prevent overflows */ if ((nr_events > (0x10000000U / sizeof(struct io_event))) || (nr_events > (0x10000000U / sizeof(struct kiocb)))) { pr_debug("ENOMEM: nr_events too high\n"); return ERR_PTR(-EINVAL); } if ((unsigned long)nr_events > aio_max_nr) return ERR_PTR(-EAGAIN); ctx = kmem_cache_zalloc(kioctx_cachep, GFP_KERNEL); if (!ctx) return ERR_PTR(-ENOMEM); ctx->max_reqs = nr_events; mm = ctx->mm = current->mm; atomic_inc(&mm->mm_count); atomic_set(&ctx->users, 1); spin_lock_init(&ctx->ctx_lock); spin_lock_init(&ctx->ring_info.ring_lock); init_waitqueue_head(&ctx->wait); INIT_LIST_HEAD(&ctx->active_reqs); INIT_LIST_HEAD(&ctx->run_list); INIT_DELAYED_WORK(&ctx->wq, aio_kick_handler); if (aio_setup_ring(ctx) < 0) goto out_freectx; /* limit the number of system wide aios */ do { spin_lock_bh(&aio_nr_lock); if (aio_nr + nr_events > aio_max_nr || aio_nr + nr_events < aio_nr) ctx->max_reqs = 0; else aio_nr += ctx->max_reqs; spin_unlock_bh(&aio_nr_lock); if (ctx->max_reqs || did_sync) break; /* wait for rcu callbacks to have completed before giving up */ synchronize_rcu(); did_sync = 1; ctx->max_reqs = nr_events; } while (1); if (ctx->max_reqs == 0) goto out_cleanup; /* now link into global list. */ spin_lock(&mm->ioctx_lock); hlist_add_head_rcu(&ctx->list, &mm->ioctx_list); spin_unlock(&mm->ioctx_lock); dprintk("aio: allocated ioctx %p[%ld]: mm=%p mask=0x%x\n", ctx, ctx->user_id, current->mm, ctx->ring_info.nr); return ctx; out_cleanup: __put_ioctx(ctx); return ERR_PTR(-EAGAIN); out_freectx: mmdrop(mm); kmem_cache_free(kioctx_cachep, ctx); ctx = ERR_PTR(-ENOMEM); dprintk("aio: error allocating ioctx %p\n", ctx); return ctx; } /* aio_cancel_all * Cancels all outstanding aio requests on an aio context. Used * when the processes owning a context have all exited to encourage * the rapid destruction of the kioctx. */ static void aio_cancel_all(struct kioctx *ctx) { int (*cancel)(struct kiocb *, struct io_event *); struct io_event res; spin_lock_irq(&ctx->ctx_lock); ctx->dead = 1; while (!list_empty(&ctx->active_reqs)) { struct list_head *pos = ctx->active_reqs.next; struct kiocb *iocb = list_kiocb(pos); list_del_init(&iocb->ki_list); cancel = iocb->ki_cancel; kiocbSetCancelled(iocb); if (cancel) { iocb->ki_users++; spin_unlock_irq(&ctx->ctx_lock); cancel(iocb, &res); spin_lock_irq(&ctx->ctx_lock); } } spin_unlock_irq(&ctx->ctx_lock); } static void wait_for_all_aios(struct kioctx *ctx) { struct task_struct *tsk = current; DECLARE_WAITQUEUE(wait, tsk); spin_lock_irq(&ctx->ctx_lock); if (!ctx->reqs_active) goto out; add_wait_queue(&ctx->wait, &wait); set_task_state(tsk, TASK_UNINTERRUPTIBLE); while (ctx->reqs_active) { spin_unlock_irq(&ctx->ctx_lock); io_schedule(); set_task_state(tsk, TASK_UNINTERRUPTIBLE); spin_lock_irq(&ctx->ctx_lock); } __set_task_state(tsk, TASK_RUNNING); remove_wait_queue(&ctx->wait, &wait); out: spin_unlock_irq(&ctx->ctx_lock); } /* wait_on_sync_kiocb: * Waits on the given sync kiocb to complete. */ ssize_t wait_on_sync_kiocb(struct kiocb *iocb) { while (iocb->ki_users) { set_current_state(TASK_UNINTERRUPTIBLE); if (!iocb->ki_users) break; io_schedule(); } __set_current_state(TASK_RUNNING); return iocb->ki_user_data; } EXPORT_SYMBOL(wait_on_sync_kiocb); /* exit_aio: called when the last user of mm goes away. At this point, * there is no way for any new requests to be submited or any of the * io_* syscalls to be called on the context. However, there may be * outstanding requests which hold references to the context; as they * go away, they will call put_ioctx and release any pinned memory * associated with the request (held via struct page * references). */ void exit_aio(struct mm_struct *mm) { struct kioctx *ctx; while (!hlist_empty(&mm->ioctx_list)) { ctx = hlist_entry(mm->ioctx_list.first, struct kioctx, list); hlist_del_rcu(&ctx->list); aio_cancel_all(ctx); wait_for_all_aios(ctx); /* * Ensure we don't leave the ctx on the aio_wq */ cancel_work_sync(&ctx->wq.work); if (1 != atomic_read(&ctx->users)) printk(KERN_DEBUG "exit_aio:ioctx still alive: %d %d %d\n", atomic_read(&ctx->users), ctx->dead, ctx->reqs_active); put_ioctx(ctx); } } /* aio_get_req * Allocate a slot for an aio request. Increments the users count * of the kioctx so that the kioctx stays around until all requests are * complete. Returns NULL if no requests are free. * * Returns with kiocb->users set to 2. The io submit code path holds * an extra reference while submitting the i/o. * This prevents races between the aio code path referencing the * req (after submitting it) and aio_complete() freeing the req. */ static struct kiocb *__aio_get_req(struct kioctx *ctx) { struct kiocb *req = NULL; req = kmem_cache_alloc(kiocb_cachep, GFP_KERNEL); if (unlikely(!req)) return NULL; req->ki_flags = 0; req->ki_users = 2; req->ki_key = 0; req->ki_ctx = ctx; req->ki_cancel = NULL; req->ki_retry = NULL; req->ki_dtor = NULL; req->private = NULL; req->ki_iovec = NULL; INIT_LIST_HEAD(&req->ki_run_list); req->ki_eventfd = NULL; return req; } /* * struct kiocb's are allocated in batches to reduce the number of * times the ctx lock is acquired and released. */ #define KIOCB_BATCH_SIZE 32L struct kiocb_batch { struct list_head head; long count; /* number of requests left to allocate */ }; static void kiocb_batch_init(struct kiocb_batch *batch, long total) { INIT_LIST_HEAD(&batch->head); batch->count = total; } static void kiocb_batch_free(struct kiocb_batch *batch) { struct kiocb *req, *n; list_for_each_entry_safe(req, n, &batch->head, ki_batch) { list_del(&req->ki_batch); kmem_cache_free(kiocb_cachep, req); } } /* * Allocate a batch of kiocbs. This avoids taking and dropping the * context lock a lot during setup. */ static int kiocb_batch_refill(struct kioctx *ctx, struct kiocb_batch *batch) { unsigned short allocated, to_alloc; long avail; bool called_fput = false; struct kiocb *req, *n; struct aio_ring *ring; to_alloc = min(batch->count, KIOCB_BATCH_SIZE); for (allocated = 0; allocated < to_alloc; allocated++) { req = __aio_get_req(ctx); if (!req) /* allocation failed, go with what we've got */ break; list_add(&req->ki_batch, &batch->head); } if (allocated == 0) goto out; retry: spin_lock_irq(&ctx->ctx_lock); ring = kmap_atomic(ctx->ring_info.ring_pages[0]); avail = aio_ring_avail(&ctx->ring_info, ring) - ctx->reqs_active; BUG_ON(avail < 0); if (avail == 0 && !called_fput) { /* * Handle a potential starvation case. It is possible that * we hold the last reference on a struct file, causing us * to delay the final fput to non-irq context. In this case, * ctx->reqs_active is artificially high. Calling the fput * routine here may free up a slot in the event completion * ring, allowing this allocation to succeed. */ kunmap_atomic(ring); spin_unlock_irq(&ctx->ctx_lock); aio_fput_routine(NULL); called_fput = true; goto retry; } if (avail < allocated) { /* Trim back the number of requests. */ list_for_each_entry_safe(req, n, &batch->head, ki_batch) { list_del(&req->ki_batch); kmem_cache_free(kiocb_cachep, req); if (--allocated <= avail) break; } } batch->count -= allocated; list_for_each_entry(req, &batch->head, ki_batch) { list_add(&req->ki_list, &ctx->active_reqs); ctx->reqs_active++; } kunmap_atomic(ring); spin_unlock_irq(&ctx->ctx_lock); out: return allocated; } static inline struct kiocb *aio_get_req(struct kioctx *ctx, struct kiocb_batch *batch) { struct kiocb *req; if (list_empty(&batch->head)) if (kiocb_batch_refill(ctx, batch) == 0) return NULL; req = list_first_entry(&batch->head, struct kiocb, ki_batch); list_del(&req->ki_batch); return req; } static inline void really_put_req(struct kioctx *ctx, struct kiocb *req) { assert_spin_locked(&ctx->ctx_lock); if (req->ki_eventfd != NULL) eventfd_ctx_put(req->ki_eventfd); if (req->ki_dtor) req->ki_dtor(req); if (req->ki_iovec != &req->ki_inline_vec) kfree(req->ki_iovec); kmem_cache_free(kiocb_cachep, req); ctx->reqs_active--; if (unlikely(!ctx->reqs_active && ctx->dead)) wake_up_all(&ctx->wait); } static void aio_fput_routine(struct work_struct *data) { spin_lock_irq(&fput_lock); while (likely(!list_empty(&fput_head))) { struct kiocb *req = list_kiocb(fput_head.next); struct kioctx *ctx = req->ki_ctx; list_del(&req->ki_list); spin_unlock_irq(&fput_lock); /* Complete the fput(s) */ if (req->ki_filp != NULL) fput(req->ki_filp); /* Link the iocb into the context's free list */ spin_lock_irq(&ctx->ctx_lock); really_put_req(ctx, req); spin_unlock_irq(&ctx->ctx_lock); put_ioctx(ctx); spin_lock_irq(&fput_lock); } spin_unlock_irq(&fput_lock); } /* __aio_put_req * Returns true if this put was the last user of the request. */ static int __aio_put_req(struct kioctx *ctx, struct kiocb *req) { dprintk(KERN_DEBUG "aio_put(%p): f_count=%ld\n", req, atomic_long_read(&req->ki_filp->f_count)); assert_spin_locked(&ctx->ctx_lock); req->ki_users--; BUG_ON(req->ki_users < 0); if (likely(req->ki_users)) return 0; list_del(&req->ki_list); /* remove from active_reqs */ req->ki_cancel = NULL; req->ki_retry = NULL; /* * Try to optimize the aio and eventfd file* puts, by avoiding to * schedule work in case it is not final fput() time. In normal cases, * we would not be holding the last reference to the file*, so * this function will be executed w/out any aio kthread wakeup. */ if (unlikely(!fput_atomic(req->ki_filp))) { get_ioctx(ctx); spin_lock(&fput_lock); list_add(&req->ki_list, &fput_head); spin_unlock(&fput_lock); schedule_work(&fput_work); } else { req->ki_filp = NULL; really_put_req(ctx, req); } return 1; } /* aio_put_req * Returns true if this put was the last user of the kiocb, * false if the request is still in use. */ int aio_put_req(struct kiocb *req) { struct kioctx *ctx = req->ki_ctx; int ret; spin_lock_irq(&ctx->ctx_lock); ret = __aio_put_req(ctx, req); spin_unlock_irq(&ctx->ctx_lock); return ret; } EXPORT_SYMBOL(aio_put_req); static struct kioctx *lookup_ioctx(unsigned long ctx_id) { struct mm_struct *mm = current->mm; struct kioctx *ctx, *ret = NULL; struct hlist_node *n; rcu_read_lock(); hlist_for_each_entry_rcu(ctx, n, &mm->ioctx_list, list) { /* * RCU protects us against accessing freed memory but * we have to be careful not to get a reference when the * reference count already dropped to 0 (ctx->dead test * is unreliable because of races). */ if (ctx->user_id == ctx_id && !ctx->dead && try_get_ioctx(ctx)){ ret = ctx; break; } } rcu_read_unlock(); return ret; } /* * Queue up a kiocb to be retried. Assumes that the kiocb * has already been marked as kicked, and places it on * the retry run list for the corresponding ioctx, if it * isn't already queued. Returns 1 if it actually queued * the kiocb (to tell the caller to activate the work * queue to process it), or 0, if it found that it was * already queued. */ static inline int __queue_kicked_iocb(struct kiocb *iocb) { struct kioctx *ctx = iocb->ki_ctx; assert_spin_locked(&ctx->ctx_lock); if (list_empty(&iocb->ki_run_list)) { list_add_tail(&iocb->ki_run_list, &ctx->run_list); return 1; } return 0; } /* aio_run_iocb * This is the core aio execution routine. It is * invoked both for initial i/o submission and * subsequent retries via the aio_kick_handler. * Expects to be invoked with iocb->ki_ctx->lock * already held. The lock is released and reacquired * as needed during processing. * * Calls the iocb retry method (already setup for the * iocb on initial submission) for operation specific * handling, but takes care of most of common retry * execution details for a given iocb. The retry method * needs to be non-blocking as far as possible, to avoid * holding up other iocbs waiting to be serviced by the * retry kernel thread. * * The trickier parts in this code have to do with * ensuring that only one retry instance is in progress * for a given iocb at any time. Providing that guarantee * simplifies the coding of individual aio operations as * it avoids various potential races. */ static ssize_t aio_run_iocb(struct kiocb *iocb) { struct kioctx *ctx = iocb->ki_ctx; ssize_t (*retry)(struct kiocb *); ssize_t ret; if (!(retry = iocb->ki_retry)) { printk("aio_run_iocb: iocb->ki_retry = NULL\n"); return 0; } /* * We don't want the next retry iteration for this * operation to start until this one has returned and * updated the iocb state. However, wait_queue functions * can trigger a kick_iocb from interrupt context in the * meantime, indicating that data is available for the next * iteration. We want to remember that and enable the * next retry iteration _after_ we are through with * this one. * * So, in order to be able to register a "kick", but * prevent it from being queued now, we clear the kick * flag, but make the kick code *think* that the iocb is * still on the run list until we are actually done. * When we are done with this iteration, we check if * the iocb was kicked in the meantime and if so, queue * it up afresh. */ kiocbClearKicked(iocb); /* * This is so that aio_complete knows it doesn't need to * pull the iocb off the run list (We can't just call * INIT_LIST_HEAD because we don't want a kick_iocb to * queue this on the run list yet) */ iocb->ki_run_list.next = iocb->ki_run_list.prev = NULL; spin_unlock_irq(&ctx->ctx_lock); /* Quit retrying if the i/o has been cancelled */ if (kiocbIsCancelled(iocb)) { ret = -EINTR; aio_complete(iocb, ret, 0); /* must not access the iocb after this */ goto out; } /* * Now we are all set to call the retry method in async * context. */ ret = retry(iocb); if (ret != -EIOCBRETRY && ret != -EIOCBQUEUED) { /* * There's no easy way to restart the syscall since other AIO's * may be already running. Just fail this IO with EINTR. */ if (unlikely(ret == -ERESTARTSYS || ret == -ERESTARTNOINTR || ret == -ERESTARTNOHAND || ret == -ERESTART_RESTARTBLOCK)) ret = -EINTR; aio_complete(iocb, ret, 0); } out: spin_lock_irq(&ctx->ctx_lock); if (-EIOCBRETRY == ret) { /* * OK, now that we are done with this iteration * and know that there is more left to go, * this is where we let go so that a subsequent * "kick" can start the next iteration */ /* will make __queue_kicked_iocb succeed from here on */ INIT_LIST_HEAD(&iocb->ki_run_list); /* we must queue the next iteration ourselves, if it * has already been kicked */ if (kiocbIsKicked(iocb)) { __queue_kicked_iocb(iocb); /* * __queue_kicked_iocb will always return 1 here, because * iocb->ki_run_list is empty at this point so it should * be safe to unconditionally queue the context into the * work queue. */ aio_queue_work(ctx); } } return ret; } /* * __aio_run_iocbs: * Process all pending retries queued on the ioctx * run list. * Assumes it is operating within the aio issuer's mm * context. */ static int __aio_run_iocbs(struct kioctx *ctx) { struct kiocb *iocb; struct list_head run_list; assert_spin_locked(&ctx->ctx_lock); list_replace_init(&ctx->run_list, &run_list); while (!list_empty(&run_list)) { iocb = list_entry(run_list.next, struct kiocb, ki_run_list); list_del(&iocb->ki_run_list); /* * Hold an extra reference while retrying i/o. */ iocb->ki_users++; /* grab extra reference */ aio_run_iocb(iocb); __aio_put_req(ctx, iocb); } if (!list_empty(&ctx->run_list)) return 1; return 0; } static void aio_queue_work(struct kioctx * ctx) { unsigned long timeout; /* * if someone is waiting, get the work started right * away, otherwise, use a longer delay */ smp_mb(); if (waitqueue_active(&ctx->wait)) timeout = 1; else timeout = HZ/10; queue_delayed_work(aio_wq, &ctx->wq, timeout); } /* * aio_run_all_iocbs: * Process all pending retries queued on the ioctx * run list, and keep running them until the list * stays empty. * Assumes it is operating within the aio issuer's mm context. */ static inline void aio_run_all_iocbs(struct kioctx *ctx) { spin_lock_irq(&ctx->ctx_lock); while (__aio_run_iocbs(ctx)) ; spin_unlock_irq(&ctx->ctx_lock); } /* * aio_kick_handler: * Work queue handler triggered to process pending * retries on an ioctx. Takes on the aio issuer's * mm context before running the iocbs, so that * copy_xxx_user operates on the issuer's address * space. * Run on aiod's context. */ static void aio_kick_handler(struct work_struct *work) { struct kioctx *ctx = container_of(work, struct kioctx, wq.work); mm_segment_t oldfs = get_fs(); struct mm_struct *mm; int requeue; set_fs(USER_DS); use_mm(ctx->mm); spin_lock_irq(&ctx->ctx_lock); requeue =__aio_run_iocbs(ctx); mm = ctx->mm; spin_unlock_irq(&ctx->ctx_lock); unuse_mm(mm); set_fs(oldfs); /* * we're in a worker thread already, don't use queue_delayed_work, */ if (requeue) queue_delayed_work(aio_wq, &ctx->wq, 0); } /* * Called by kick_iocb to queue the kiocb for retry * and if required activate the aio work queue to process * it */ static void try_queue_kicked_iocb(struct kiocb *iocb) { struct kioctx *ctx = iocb->ki_ctx; unsigned long flags; int run = 0; spin_lock_irqsave(&ctx->ctx_lock, flags); /* set this inside the lock so that we can't race with aio_run_iocb() * testing it and putting the iocb on the run list under the lock */ if (!kiocbTryKick(iocb)) run = __queue_kicked_iocb(iocb); spin_unlock_irqrestore(&ctx->ctx_lock, flags); if (run) aio_queue_work(ctx); } /* * kick_iocb: * Called typically from a wait queue callback context * to trigger a retry of the iocb. * The retry is usually executed by aio workqueue * threads (See aio_kick_handler). */ void kick_iocb(struct kiocb *iocb) { /* sync iocbs are easy: they can only ever be executing from a * single context. */ if (is_sync_kiocb(iocb)) { kiocbSetKicked(iocb); wake_up_process(iocb->ki_obj.tsk); return; } try_queue_kicked_iocb(iocb); } EXPORT_SYMBOL(kick_iocb); /* aio_complete * Called when the io request on the given iocb is complete. * Returns true if this is the last user of the request. The * only other user of the request can be the cancellation code. */ int aio_complete(struct kiocb *iocb, long res, long res2) { struct kioctx *ctx = iocb->ki_ctx; struct aio_ring_info *info; struct aio_ring *ring; struct io_event *event; unsigned long flags; unsigned long tail; int ret; /* * Special case handling for sync iocbs: * - events go directly into the iocb for fast handling * - the sync task with the iocb in its stack holds the single iocb * ref, no other paths have a way to get another ref * - the sync task helpfully left a reference to itself in the iocb */ if (is_sync_kiocb(iocb)) { BUG_ON(iocb->ki_users != 1); iocb->ki_user_data = res; iocb->ki_users = 0; wake_up_process(iocb->ki_obj.tsk); return 1; } info = &ctx->ring_info; /* add a completion event to the ring buffer. * must be done holding ctx->ctx_lock to prevent * other code from messing with the tail * pointer since we might be called from irq * context. */ spin_lock_irqsave(&ctx->ctx_lock, flags); if (iocb->ki_run_list.prev && !list_empty(&iocb->ki_run_list)) list_del_init(&iocb->ki_run_list); /* * cancelled requests don't get events, userland was given one * when the event got cancelled. */ if (kiocbIsCancelled(iocb)) goto put_rq; ring = kmap_atomic(info->ring_pages[0], KM_IRQ1); tail = info->tail; event = aio_ring_event(info, tail, KM_IRQ0); if (++tail >= info->nr) tail = 0; event->obj = (u64)(unsigned long)iocb->ki_obj.user; event->data = iocb->ki_user_data; event->res = res; event->res2 = res2; dprintk("aio_complete: %p[%lu]: %p: %p %Lx %lx %lx\n", ctx, tail, iocb, iocb->ki_obj.user, iocb->ki_user_data, res, res2); /* after flagging the request as done, we * must never even look at it again */ smp_wmb(); /* make event visible before updating tail */ info->tail = tail; ring->tail = tail; put_aio_ring_event(event, KM_IRQ0); kunmap_atomic(ring, KM_IRQ1); pr_debug("added to ring %p at [%lu]\n", iocb, tail); /* * Check if the user asked us to deliver the result through an * eventfd. The eventfd_signal() function is safe to be called * from IRQ context. */ if (iocb->ki_eventfd != NULL) eventfd_signal(iocb->ki_eventfd, 1); put_rq: /* everything turned out well, dispose of the aiocb. */ ret = __aio_put_req(ctx, iocb); /* * We have to order our ring_info tail store above and test * of the wait list below outside the wait lock. This is * like in wake_up_bit() where clearing a bit has to be * ordered with the unlocked test. */ smp_mb(); if (waitqueue_active(&ctx->wait)) wake_up(&ctx->wait); spin_unlock_irqrestore(&ctx->ctx_lock, flags); return ret; } EXPORT_SYMBOL(aio_complete); /* aio_read_evt * Pull an event off of the ioctx's event ring. Returns the number of * events fetched (0 or 1 ;-) * FIXME: make this use cmpxchg. * TODO: make the ringbuffer user mmap()able (requires FIXME). */ static int aio_read_evt(struct kioctx *ioctx, struct io_event *ent) { struct aio_ring_info *info = &ioctx->ring_info; struct aio_ring *ring; unsigned long head; int ret = 0; ring = kmap_atomic(info->ring_pages[0], KM_USER0); dprintk("in aio_read_evt h%lu t%lu m%lu\n", (unsigned long)ring->head, (unsigned long)ring->tail, (unsigned long)ring->nr); if (ring->head == ring->tail) goto out; spin_lock(&info->ring_lock); head = ring->head % info->nr; if (head != ring->tail) { struct io_event *evp = aio_ring_event(info, head, KM_USER1); *ent = *evp; head = (head + 1) % info->nr; smp_mb(); /* finish reading the event before updatng the head */ ring->head = head; ret = 1; put_aio_ring_event(evp, KM_USER1); } spin_unlock(&info->ring_lock); out: kunmap_atomic(ring, KM_USER0); dprintk("leaving aio_read_evt: %d h%lu t%lu\n", ret, (unsigned long)ring->head, (unsigned long)ring->tail); return ret; } struct aio_timeout { struct timer_list timer; int timed_out; struct task_struct *p; }; static void timeout_func(unsigned long data) { struct aio_timeout *to = (struct aio_timeout *)data; to->timed_out = 1; wake_up_process(to->p); } static inline void init_timeout(struct aio_timeout *to) { setup_timer_on_stack(&to->timer, timeout_func, (unsigned long) to); to->timed_out = 0; to->p = current; } static inline void set_timeout(long start_jiffies, struct aio_timeout *to, const struct timespec *ts) { to->timer.expires = start_jiffies + timespec_to_jiffies(ts); if (time_after(to->timer.expires, jiffies)) add_timer(&to->timer); else to->timed_out = 1; } static inline void clear_timeout(struct aio_timeout *to) { del_singleshot_timer_sync(&to->timer); } static int read_events(struct kioctx *ctx, long min_nr, long nr, struct io_event __user *event, struct timespec __user *timeout) { long start_jiffies = jiffies; struct task_struct *tsk = current; DECLARE_WAITQUEUE(wait, tsk); int ret; int i = 0; struct io_event ent; struct aio_timeout to; int retry = 0; /* needed to zero any padding within an entry (there shouldn't be * any, but C is fun! */ memset(&ent, 0, sizeof(ent)); retry: ret = 0; while (likely(i < nr)) { ret = aio_read_evt(ctx, &ent); if (unlikely(ret <= 0)) break; dprintk("read event: %Lx %Lx %Lx %Lx\n", ent.data, ent.obj, ent.res, ent.res2); /* Could we split the check in two? */ ret = -EFAULT; if (unlikely(copy_to_user(event, &ent, sizeof(ent)))) { dprintk("aio: lost an event due to EFAULT.\n"); break; } ret = 0; /* Good, event copied to userland, update counts. */ event ++; i ++; } if (min_nr <= i) return i; if (ret) return ret; /* End fast path */ /* racey check, but it gets redone */ if (!retry && unlikely(!list_empty(&ctx->run_list))) { retry = 1; aio_run_all_iocbs(ctx); goto retry; } init_timeout(&to); if (timeout) { struct timespec ts; ret = -EFAULT; if (unlikely(copy_from_user(&ts, timeout, sizeof(ts)))) goto out; set_timeout(start_jiffies, &to, &ts); } while (likely(i < nr)) { add_wait_queue_exclusive(&ctx->wait, &wait); do { set_task_state(tsk, TASK_INTERRUPTIBLE); ret = aio_read_evt(ctx, &ent); if (ret) break; if (min_nr <= i) break; if (unlikely(ctx->dead)) { ret = -EINVAL; break; } if (to.timed_out) /* Only check after read evt */ break; /* Try to only show up in io wait if there are ops * in flight */ if (ctx->reqs_active) io_schedule(); else schedule(); if (signal_pending(tsk)) { ret = -EINTR; break; } /*ret = aio_read_evt(ctx, &ent);*/ } while (1) ; set_task_state(tsk, TASK_RUNNING); remove_wait_queue(&ctx->wait, &wait); if (unlikely(ret <= 0)) break; ret = -EFAULT; if (unlikely(copy_to_user(event, &ent, sizeof(ent)))) { dprintk("aio: lost an event due to EFAULT.\n"); break; } /* Good, event copied to userland, update counts. */ event ++; i ++; } if (timeout) clear_timeout(&to); out: destroy_timer_on_stack(&to.timer); return i ? i : ret; } /* Take an ioctx and remove it from the list of ioctx's. Protects * against races with itself via ->dead. */ static void io_destroy(struct kioctx *ioctx) { struct mm_struct *mm = current->mm; int was_dead; /* delete the entry from the list is someone else hasn't already */ spin_lock(&mm->ioctx_lock); was_dead = ioctx->dead; ioctx->dead = 1; hlist_del_rcu(&ioctx->list); spin_unlock(&mm->ioctx_lock); dprintk("aio_release(%p)\n", ioctx); if (likely(!was_dead)) put_ioctx(ioctx); /* twice for the list */ aio_cancel_all(ioctx); wait_for_all_aios(ioctx); /* * Wake up any waiters. The setting of ctx->dead must be seen * by other CPUs at this point. Right now, we rely on the * locking done by the above calls to ensure this consistency. */ wake_up_all(&ioctx->wait); put_ioctx(ioctx); /* once for the lookup */ } /* sys_io_setup: * Create an aio_context capable of receiving at least nr_events. * ctxp must not point to an aio_context that already exists, and * must be initialized to 0 prior to the call. On successful * creation of the aio_context, *ctxp is filled in with the resulting * handle. May fail with -EINVAL if *ctxp is not initialized, * if the specified nr_events exceeds internal limits. May fail * with -EAGAIN if the specified nr_events exceeds the user's limit * of available events. May fail with -ENOMEM if insufficient kernel * resources are available. May fail with -EFAULT if an invalid * pointer is passed for ctxp. Will fail with -ENOSYS if not * implemented. */ SYSCALL_DEFINE2(io_setup, unsigned, nr_events, aio_context_t __user *, ctxp) { struct kioctx *ioctx = NULL; unsigned long ctx; long ret; ret = get_user(ctx, ctxp); if (unlikely(ret)) goto out; ret = -EINVAL; if (unlikely(ctx || nr_events == 0)) { pr_debug("EINVAL: io_setup: ctx %lu nr_events %u\n", ctx, nr_events); goto out; } ioctx = ioctx_alloc(nr_events); ret = PTR_ERR(ioctx); if (!IS_ERR(ioctx)) { ret = put_user(ioctx->user_id, ctxp); if (!ret) return 0; get_ioctx(ioctx); /* io_destroy() expects us to hold a ref */ io_destroy(ioctx); } out: return ret; } /* sys_io_destroy: * Destroy the aio_context specified. May cancel any outstanding * AIOs and block on completion. Will fail with -ENOSYS if not * implemented. May fail with -EINVAL if the context pointed to * is invalid. */ SYSCALL_DEFINE1(io_destroy, aio_context_t, ctx) { struct kioctx *ioctx = lookup_ioctx(ctx); if (likely(NULL != ioctx)) { io_destroy(ioctx); return 0; } pr_debug("EINVAL: io_destroy: invalid context id\n"); return -EINVAL; } static void aio_advance_iovec(struct kiocb *iocb, ssize_t ret) { struct iovec *iov = &iocb->ki_iovec[iocb->ki_cur_seg]; BUG_ON(ret <= 0); while (iocb->ki_cur_seg < iocb->ki_nr_segs && ret > 0) { ssize_t this = min((ssize_t)iov->iov_len, ret); iov->iov_base += this; iov->iov_len -= this; iocb->ki_left -= this; ret -= this; if (iov->iov_len == 0) { iocb->ki_cur_seg++; iov++; } } /* the caller should not have done more io than what fit in * the remaining iovecs */ BUG_ON(ret > 0 && iocb->ki_left == 0); } static ssize_t aio_rw_vect_retry(struct kiocb *iocb) { struct file *file = iocb->ki_filp; struct address_space *mapping = file->f_mapping; struct inode *inode = mapping->host; ssize_t (*rw_op)(struct kiocb *, const struct iovec *, unsigned long, loff_t); ssize_t ret = 0; unsigned short opcode; if ((iocb->ki_opcode == IOCB_CMD_PREADV) || (iocb->ki_opcode == IOCB_CMD_PREAD)) { rw_op = file->f_op->aio_read; opcode = IOCB_CMD_PREADV; } else { rw_op = file->f_op->aio_write; opcode = IOCB_CMD_PWRITEV; } /* This matches the pread()/pwrite() logic */ if (iocb->ki_pos < 0) return -EINVAL; do { ret = rw_op(iocb, &iocb->ki_iovec[iocb->ki_cur_seg], iocb->ki_nr_segs - iocb->ki_cur_seg, iocb->ki_pos); if (ret > 0) aio_advance_iovec(iocb, ret); /* retry all partial writes. retry partial reads as long as its a * regular file. */ } while (ret > 0 && iocb->ki_left > 0 && (opcode == IOCB_CMD_PWRITEV || (!S_ISFIFO(inode->i_mode) && !S_ISSOCK(inode->i_mode)))); /* This means we must have transferred all that we could */ /* No need to retry anymore */ if ((ret == 0) || (iocb->ki_left == 0)) ret = iocb->ki_nbytes - iocb->ki_left; /* If we managed to write some out we return that, rather than * the eventual error. */ if (opcode == IOCB_CMD_PWRITEV && ret < 0 && ret != -EIOCBQUEUED && ret != -EIOCBRETRY && iocb->ki_nbytes - iocb->ki_left) ret = iocb->ki_nbytes - iocb->ki_left; return ret; } static ssize_t aio_fdsync(struct kiocb *iocb) { struct file *file = iocb->ki_filp; ssize_t ret = -EINVAL; if (file->f_op->aio_fsync) ret = file->f_op->aio_fsync(iocb, 1); return ret; } static ssize_t aio_fsync(struct kiocb *iocb) { struct file *file = iocb->ki_filp; ssize_t ret = -EINVAL; if (file->f_op->aio_fsync) ret = file->f_op->aio_fsync(iocb, 0); return ret; } static ssize_t aio_setup_vectored_rw(int type, struct kiocb *kiocb, bool compat) { ssize_t ret; #ifdef CONFIG_COMPAT if (compat) ret = compat_rw_copy_check_uvector(type, (struct compat_iovec __user *)kiocb->ki_buf, kiocb->ki_nbytes, 1, &kiocb->ki_inline_vec, &kiocb->ki_iovec, 1); else #endif ret = rw_copy_check_uvector(type, (struct iovec __user *)kiocb->ki_buf, kiocb->ki_nbytes, 1, &kiocb->ki_inline_vec, &kiocb->ki_iovec, 1); if (ret < 0) goto out; kiocb->ki_nr_segs = kiocb->ki_nbytes; kiocb->ki_cur_seg = 0; /* ki_nbytes/left now reflect bytes instead of segs */ kiocb->ki_nbytes = ret; kiocb->ki_left = ret; ret = 0; out: return ret; } static ssize_t aio_setup_single_vector(struct kiocb *kiocb) { kiocb->ki_iovec = &kiocb->ki_inline_vec; kiocb->ki_iovec->iov_base = kiocb->ki_buf; kiocb->ki_iovec->iov_len = kiocb->ki_left; kiocb->ki_nr_segs = 1; kiocb->ki_cur_seg = 0; return 0; } /* * aio_setup_iocb: * Performs the initial checks and aio retry method * setup for the kiocb at the time of io submission. */ static ssize_t aio_setup_iocb(struct kiocb *kiocb, bool compat) { struct file *file = kiocb->ki_filp; ssize_t ret = 0; switch (kiocb->ki_opcode) { case IOCB_CMD_PREAD: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_READ))) break; ret = -EFAULT; if (unlikely(!access_ok(VERIFY_WRITE, kiocb->ki_buf, kiocb->ki_left))) break; ret = security_file_permission(file, MAY_READ); if (unlikely(ret)) break; ret = aio_setup_single_vector(kiocb); if (ret) break; ret = -EINVAL; if (file->f_op->aio_read) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PWRITE: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_WRITE))) break; ret = -EFAULT; if (unlikely(!access_ok(VERIFY_READ, kiocb->ki_buf, kiocb->ki_left))) break; ret = security_file_permission(file, MAY_WRITE); if (unlikely(ret)) break; ret = aio_setup_single_vector(kiocb); if (ret) break; ret = -EINVAL; if (file->f_op->aio_write) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PREADV: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_READ))) break; ret = security_file_permission(file, MAY_READ); if (unlikely(ret)) break; ret = aio_setup_vectored_rw(READ, kiocb, compat); if (ret) break; ret = -EINVAL; if (file->f_op->aio_read) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_PWRITEV: ret = -EBADF; if (unlikely(!(file->f_mode & FMODE_WRITE))) break; ret = security_file_permission(file, MAY_WRITE); if (unlikely(ret)) break; ret = aio_setup_vectored_rw(WRITE, kiocb, compat); if (ret) break; ret = -EINVAL; if (file->f_op->aio_write) kiocb->ki_retry = aio_rw_vect_retry; break; case IOCB_CMD_FDSYNC: ret = -EINVAL; if (file->f_op->aio_fsync) kiocb->ki_retry = aio_fdsync; break; case IOCB_CMD_FSYNC: ret = -EINVAL; if (file->f_op->aio_fsync) kiocb->ki_retry = aio_fsync; break; default: dprintk("EINVAL: io_submit: no operation provided\n"); ret = -EINVAL; } if (!kiocb->ki_retry) return ret; return 0; } static int io_submit_one(struct kioctx *ctx, struct iocb __user *user_iocb, struct iocb *iocb, struct kiocb_batch *batch, bool compat) { struct kiocb *req; struct file *file; ssize_t ret; /* enforce forwards compatibility on users */ if (unlikely(iocb->aio_reserved1 || iocb->aio_reserved2)) { pr_debug("EINVAL: io_submit: reserve field set\n"); return -EINVAL; } /* prevent overflows */ if (unlikely( (iocb->aio_buf != (unsigned long)iocb->aio_buf) || (iocb->aio_nbytes != (size_t)iocb->aio_nbytes) || ((ssize_t)iocb->aio_nbytes < 0) )) { pr_debug("EINVAL: io_submit: overflow check\n"); return -EINVAL; } file = fget(iocb->aio_fildes); if (unlikely(!file)) return -EBADF; req = aio_get_req(ctx, batch); /* returns with 2 references to req */ if (unlikely(!req)) { fput(file); return -EAGAIN; } req->ki_filp = file; if (iocb->aio_flags & IOCB_FLAG_RESFD) { /* * If the IOCB_FLAG_RESFD flag of aio_flags is set, get an * instance of the file* now. The file descriptor must be * an eventfd() fd, and will be signaled for each completed * event using the eventfd_signal() function. */ req->ki_eventfd = eventfd_ctx_fdget((int) iocb->aio_resfd); if (IS_ERR(req->ki_eventfd)) { ret = PTR_ERR(req->ki_eventfd); req->ki_eventfd = NULL; goto out_put_req; } } ret = put_user(req->ki_key, &user_iocb->aio_key); if (unlikely(ret)) { dprintk("EFAULT: aio_key\n"); goto out_put_req; } req->ki_obj.user = user_iocb; req->ki_user_data = iocb->aio_data; req->ki_pos = iocb->aio_offset; req->ki_buf = (char __user *)(unsigned long)iocb->aio_buf; req->ki_left = req->ki_nbytes = iocb->aio_nbytes; req->ki_opcode = iocb->aio_lio_opcode; ret = aio_setup_iocb(req, compat); if (ret) goto out_put_req; spin_lock_irq(&ctx->ctx_lock); /* * We could have raced with io_destroy() and are currently holding a * reference to ctx which should be destroyed. We cannot submit IO * since ctx gets freed as soon as io_submit() puts its reference. The * check here is reliable: io_destroy() sets ctx->dead before waiting * for outstanding IO and the barrier between these two is realized by * unlock of mm->ioctx_lock and lock of ctx->ctx_lock. Analogously we * increment ctx->reqs_active before checking for ctx->dead and the * barrier is realized by unlock and lock of ctx->ctx_lock. Thus if we * don't see ctx->dead set here, io_destroy() waits for our IO to * finish. */ if (ctx->dead) { spin_unlock_irq(&ctx->ctx_lock); ret = -EINVAL; goto out_put_req; } aio_run_iocb(req); if (!list_empty(&ctx->run_list)) { /* drain the run list */ while (__aio_run_iocbs(ctx)) ; } spin_unlock_irq(&ctx->ctx_lock); aio_put_req(req); /* drop extra ref to req */ return 0; out_put_req: aio_put_req(req); /* drop extra ref to req */ aio_put_req(req); /* drop i/o ref to req */ return ret; } long do_io_submit(aio_context_t ctx_id, long nr, struct iocb __user *__user *iocbpp, bool compat) { struct kioctx *ctx; long ret = 0; int i = 0; struct blk_plug plug; struct kiocb_batch batch; if (unlikely(nr < 0)) return -EINVAL; if (unlikely(nr > LONG_MAX/sizeof(*iocbpp))) nr = LONG_MAX/sizeof(*iocbpp); if (unlikely(!access_ok(VERIFY_READ, iocbpp, (nr*sizeof(*iocbpp))))) return -EFAULT; ctx = lookup_ioctx(ctx_id); if (unlikely(!ctx)) { pr_debug("EINVAL: io_submit: invalid context id\n"); return -EINVAL; } kiocb_batch_init(&batch, nr); blk_start_plug(&plug); /* * AKPM: should this return a partial result if some of the IOs were * successfully submitted? */ for (i=0; i<nr; i++) { struct iocb __user *user_iocb; struct iocb tmp; if (unlikely(__get_user(user_iocb, iocbpp + i))) { ret = -EFAULT; break; } if (unlikely(copy_from_user(&tmp, user_iocb, sizeof(tmp)))) { ret = -EFAULT; break; } ret = io_submit_one(ctx, user_iocb, &tmp, &batch, compat); if (ret) break; } blk_finish_plug(&plug); kiocb_batch_free(&batch); put_ioctx(ctx); return i ? i : ret; } /* sys_io_submit: * Queue the nr iocbs pointed to by iocbpp for processing. Returns * the number of iocbs queued. May return -EINVAL if the aio_context * specified by ctx_id is invalid, if nr is < 0, if the iocb at * *iocbpp[0] is not properly initialized, if the operation specified * is invalid for the file descriptor in the iocb. May fail with * -EFAULT if any of the data structures point to invalid data. May * fail with -EBADF if the file descriptor specified in the first * iocb is invalid. May fail with -EAGAIN if insufficient resources * are available to queue any iocbs. Will return 0 if nr is 0. Will * fail with -ENOSYS if not implemented. */ SYSCALL_DEFINE3(io_submit, aio_context_t, ctx_id, long, nr, struct iocb __user * __user *, iocbpp) { return do_io_submit(ctx_id, nr, iocbpp, 0); } /* lookup_kiocb * Finds a given iocb for cancellation. */ static struct kiocb *lookup_kiocb(struct kioctx *ctx, struct iocb __user *iocb, u32 key) { struct list_head *pos; assert_spin_locked(&ctx->ctx_lock); /* TODO: use a hash or array, this sucks. */ list_for_each(pos, &ctx->active_reqs) { struct kiocb *kiocb = list_kiocb(pos); if (kiocb->ki_obj.user == iocb && kiocb->ki_key == key) return kiocb; } return NULL; } /* sys_io_cancel: * Attempts to cancel an iocb previously passed to io_submit. If * the operation is successfully cancelled, the resulting event is * copied into the memory pointed to by result without being placed * into the completion queue and 0 is returned. May fail with * -EFAULT if any of the data structures pointed to are invalid. * May fail with -EINVAL if aio_context specified by ctx_id is * invalid. May fail with -EAGAIN if the iocb specified was not * cancelled. Will fail with -ENOSYS if not implemented. */ SYSCALL_DEFINE3(io_cancel, aio_context_t, ctx_id, struct iocb __user *, iocb, struct io_event __user *, result) { int (*cancel)(struct kiocb *iocb, struct io_event *res); struct kioctx *ctx; struct kiocb *kiocb; u32 key; int ret; ret = get_user(key, &iocb->aio_key); if (unlikely(ret)) return -EFAULT; ctx = lookup_ioctx(ctx_id); if (unlikely(!ctx)) return -EINVAL; spin_lock_irq(&ctx->ctx_lock); ret = -EAGAIN; kiocb = lookup_kiocb(ctx, iocb, key); if (kiocb && kiocb->ki_cancel) { cancel = kiocb->ki_cancel; kiocb->ki_users ++; kiocbSetCancelled(kiocb); } else cancel = NULL; spin_unlock_irq(&ctx->ctx_lock); if (NULL != cancel) { struct io_event tmp; pr_debug("calling cancel\n"); memset(&tmp, 0, sizeof(tmp)); tmp.obj = (u64)(unsigned long)kiocb->ki_obj.user; tmp.data = kiocb->ki_user_data; ret = cancel(kiocb, &tmp); if (!ret) { /* Cancellation succeeded -- copy the result * into the user's buffer. */ if (copy_to_user(result, &tmp, sizeof(tmp))) ret = -EFAULT; } } else ret = -EINVAL; put_ioctx(ctx); return ret; } /* io_getevents: * Attempts to read at least min_nr events and up to nr events from * the completion queue for the aio_context specified by ctx_id. If * it succeeds, the number of read events is returned. May fail with * -EINVAL if ctx_id is invalid, if min_nr is out of range, if nr is * out of range, if timeout is out of range. May fail with -EFAULT * if any of the memory specified is invalid. May return 0 or * < min_nr if the timeout specified by timeout has elapsed * before sufficient events are available, where timeout == NULL * specifies an infinite timeout. Note that the timeout pointed to by * timeout is relative and will be updated if not NULL and the * operation blocks. Will fail with -ENOSYS if not implemented. */ SYSCALL_DEFINE5(io_getevents, aio_context_t, ctx_id, long, min_nr, long, nr, struct io_event __user *, events, struct timespec __user *, timeout) { struct kioctx *ioctx = lookup_ioctx(ctx_id); long ret = -EINVAL; if (likely(ioctx)) { if (likely(min_nr <= nr && min_nr >= 0)) ret = read_events(ioctx, min_nr, nr, events, timeout); put_ioctx(ioctx); } asmlinkage_protect(5, ret, ctx_id, min_nr, nr, events, timeout); return ret; }
./CrossVul/dataset_final_sorted/CWE-399/c/bad_3573_0
crossvul-cpp_data_bad_5561_0
/* * Copyright (C) 2004 Andrew Beekhof <andrew@beekhof.net> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This software 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 library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <crm_internal.h> #include <sys/param.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <grp.h> #include <stdlib.h> #include <errno.h> #include <fcntl.h> #include <crm/crm.h> #include <crm/cib.h> #include <crm/msg_xml.h> #include <crm/common/ipc.h> #include <crm/cluster/internal.h> #include <crm/common/xml.h> #include <cibio.h> #include <callbacks.h> #include <cibmessages.h> #include <notify.h> #include "common.h" extern GMainLoop *mainloop; extern gboolean cib_shutdown_flag; extern gboolean stand_alone; extern const char *cib_root; static unsigned long cib_local_bcast_num = 0; typedef struct cib_local_notify_s { xmlNode *notify_src; char *client_id; gboolean from_peer; gboolean sync_reply; } cib_local_notify_t; qb_ipcs_service_t *ipcs_ro = NULL; qb_ipcs_service_t *ipcs_rw = NULL; qb_ipcs_service_t *ipcs_shm = NULL; extern crm_cluster_t crm_cluster; extern int cib_update_counter(xmlNode * xml_obj, const char *field, gboolean reset); extern void GHFunc_count_peers(gpointer key, gpointer value, gpointer user_data); gint cib_GCompareFunc(gconstpointer a, gconstpointer b); gboolean can_write(int flags); void send_cib_replace(const xmlNode * sync_request, const char *host); void cib_process_request(xmlNode * request, gboolean privileged, gboolean force_synchronous, gboolean from_peer, cib_client_t * cib_client); extern GHashTable *client_list; extern GHashTable *local_notify_queue; int next_client_id = 0; extern const char *cib_our_uname; extern unsigned long cib_num_ops, cib_num_local, cib_num_updates, cib_num_fail; extern unsigned long cib_bad_connects, cib_num_timeouts; extern int cib_status; int cib_process_command(xmlNode * request, xmlNode ** reply, xmlNode ** cib_diff, gboolean privileged); gboolean cib_common_callback(qb_ipcs_connection_t *c, void *data, size_t size, gboolean privileged); static int32_t cib_ipc_accept(qb_ipcs_connection_t *c, uid_t uid, gid_t gid) { cib_client_t *new_client = NULL; #if ENABLE_ACL struct group *crm_grp = NULL; #endif crm_trace("Connecting %p for uid=%d gid=%d pid=%d", c, uid, gid, crm_ipcs_client_pid(c)); if (cib_shutdown_flag) { crm_info("Ignoring new client [%d] during shutdown", crm_ipcs_client_pid(c)); return -EPERM; } new_client = calloc(1, sizeof(cib_client_t)); new_client->ipc = c; CRM_CHECK(new_client->id == NULL, free(new_client->id)); new_client->id = crm_generate_uuid(); #if ENABLE_ACL crm_grp = getgrnam(CRM_DAEMON_GROUP); if (crm_grp) { qb_ipcs_connection_auth_set(c, -1, crm_grp->gr_gid, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); } new_client->user = uid2username(uid); #endif /* make sure we can find ourselves later for sync calls * redirected to the master instance */ g_hash_table_insert(client_list, new_client->id, new_client); qb_ipcs_context_set(c, new_client); return 0; } static void cib_ipc_created(qb_ipcs_connection_t *c) { cib_client_t *cib_client = qb_ipcs_context_get(c); crm_trace("%p connected for client %s", c, cib_client->id); } static int32_t cib_ipc_dispatch_rw(qb_ipcs_connection_t *c, void *data, size_t size) { cib_client_t *cib_client = qb_ipcs_context_get(c); crm_trace("%p message from %s", c, cib_client->id); return cib_common_callback(c, data, size, TRUE); } static int32_t cib_ipc_dispatch_ro(qb_ipcs_connection_t *c, void *data, size_t size) { cib_client_t *cib_client = qb_ipcs_context_get(c); crm_trace("%p message from %s", c, cib_client->id); return cib_common_callback(c, data, size, FALSE); } /* Error code means? */ static int32_t cib_ipc_closed(qb_ipcs_connection_t *c) { cib_client_t *cib_client = qb_ipcs_context_get(c); crm_trace("Connection %p closed", c); CRM_ASSERT(cib_client != NULL); CRM_ASSERT(cib_client->id != NULL); if (!g_hash_table_remove(client_list, cib_client->id)) { crm_err("Client %s not found in the hashtable", cib_client->name); } return 0; } static void cib_ipc_destroy(qb_ipcs_connection_t *c) { cib_client_t *cib_client = qb_ipcs_context_get(c); CRM_ASSERT(cib_client != NULL); CRM_ASSERT(cib_client->id != NULL); /* In case we arrive here without a call to cib_ipc_close() */ g_hash_table_remove(client_list, cib_client->id); crm_trace("Destroying %s (%p)", cib_client->name, c); free(cib_client->name); free(cib_client->callback_id); free(cib_client->id); free(cib_client->user); free(cib_client); crm_trace("Freed the cib client"); if (cib_shutdown_flag) { cib_shutdown(0); } } struct qb_ipcs_service_handlers ipc_ro_callbacks = { .connection_accept = cib_ipc_accept, .connection_created = cib_ipc_created, .msg_process = cib_ipc_dispatch_ro, .connection_closed = cib_ipc_closed, .connection_destroyed = cib_ipc_destroy }; struct qb_ipcs_service_handlers ipc_rw_callbacks = { .connection_accept = cib_ipc_accept, .connection_created = cib_ipc_created, .msg_process = cib_ipc_dispatch_rw, .connection_closed = cib_ipc_closed, .connection_destroyed = cib_ipc_destroy }; void cib_common_callback_worker(uint32_t id, uint32_t flags, xmlNode * op_request, cib_client_t * cib_client, gboolean privileged) { const char *op = crm_element_value(op_request, F_CIB_OPERATION); if (crm_str_eq(op, CRM_OP_REGISTER, TRUE)) { if(flags & crm_ipc_client_response) { xmlNode *ack = create_xml_node(NULL, __FUNCTION__); crm_xml_add(ack, F_CIB_OPERATION, CRM_OP_REGISTER); crm_xml_add(ack, F_CIB_CLIENTID, cib_client->id); crm_ipcs_send(cib_client->ipc, id, ack, FALSE); cib_client->request_id = 0; free_xml(ack); } return; } else if (crm_str_eq(op, T_CIB_NOTIFY, TRUE)) { /* Update the notify filters for this client */ int on_off = 0; const char *type = crm_element_value(op_request, F_CIB_NOTIFY_TYPE); crm_element_value_int(op_request, F_CIB_NOTIFY_ACTIVATE, &on_off); crm_debug("Setting %s callbacks for %s (%s): %s", type, cib_client->name, cib_client->id, on_off ? "on" : "off"); if (safe_str_eq(type, T_CIB_POST_NOTIFY)) { cib_client->post_notify = on_off; } else if (safe_str_eq(type, T_CIB_PRE_NOTIFY)) { cib_client->pre_notify = on_off; } else if (safe_str_eq(type, T_CIB_UPDATE_CONFIRM)) { cib_client->confirmations = on_off; } else if (safe_str_eq(type, T_CIB_DIFF_NOTIFY)) { cib_client->diffs = on_off; } else if (safe_str_eq(type, T_CIB_REPLACE_NOTIFY)) { cib_client->replace = on_off; } if(flags & crm_ipc_client_response) { /* TODO - include rc */ crm_ipcs_send_ack(cib_client->ipc, id, "ack", __FUNCTION__, __LINE__); cib_client->request_id = 0; } return; } cib_client->num_calls++; cib_process_request(op_request, FALSE, privileged, FALSE, cib_client); } int32_t cib_common_callback(qb_ipcs_connection_t *c, void *data, size_t size, gboolean privileged) { uint32_t id = 0; uint32_t flags = 0; int call_options = 0; xmlNode *op_request = crm_ipcs_recv(c, data, size, &id, &flags); cib_client_t *cib_client = qb_ipcs_context_get(c); if(op_request) { crm_element_value_int(op_request, F_CIB_CALLOPTS, &call_options); } crm_trace("Inbound: %.200s", data); if (op_request == NULL || cib_client == NULL) { crm_ipcs_send_ack(c, id, "nack", __FUNCTION__, __LINE__); return 0; } if(is_set(call_options, cib_sync_call)) { CRM_ASSERT(flags & crm_ipc_client_response); } if(flags & crm_ipc_client_response) { CRM_LOG_ASSERT(cib_client->request_id == 0); /* This means the client has two synchronous events in-flight */ cib_client->request_id = id; /* Reply only to the last one */ } if (cib_client->name == NULL) { const char *value = crm_element_value(op_request, F_CIB_CLIENTNAME); if (value == NULL) { cib_client->name = crm_itoa(crm_ipcs_client_pid(c)); } else { cib_client->name = strdup(value); } } if (cib_client->callback_id == NULL) { const char *value = crm_element_value(op_request, F_CIB_CALLBACK_TOKEN); if (value != NULL) { cib_client->callback_id = strdup(value); } else { cib_client->callback_id = strdup(cib_client->id); } } crm_xml_add(op_request, F_CIB_CLIENTID, cib_client->id); crm_xml_add(op_request, F_CIB_CLIENTNAME, cib_client->name); #if ENABLE_ACL determine_request_user(cib_client->user, op_request, F_CIB_USER); #endif crm_log_xml_trace(op_request, "Client[inbound]"); cib_common_callback_worker(id, flags, op_request, cib_client, privileged); free_xml(op_request); return 0; } static void do_local_notify(xmlNode * notify_src, const char *client_id, gboolean sync_reply, gboolean from_peer) { /* send callback to originating child */ cib_client_t *client_obj = NULL; int local_rc = pcmk_ok; if (client_id != NULL) { client_obj = g_hash_table_lookup(client_list, client_id); } else { crm_trace("No client to sent the response to. F_CIB_CLIENTID not set."); } if (client_obj == NULL) { local_rc = -ECONNRESET; } else { int rid = 0; if(sync_reply) { CRM_LOG_ASSERT(client_obj->request_id); rid = client_obj->request_id; client_obj->request_id = 0; crm_trace("Sending response %d to %s %s", rid, client_obj->name, from_peer?"(originator of delegated request)":""); } else { crm_trace("Sending an event to %s %s", client_obj->name, from_peer?"(originator of delegated request)":""); } if (client_obj->ipc && crm_ipcs_send(client_obj->ipc, rid, notify_src, !sync_reply) < 0) { local_rc = -ENOMSG; #ifdef HAVE_GNUTLS_GNUTLS_H } else if (client_obj->session) { crm_send_remote_msg(client_obj->session, notify_src, client_obj->encrypted); #endif } else if(client_obj->ipc == NULL) { crm_err("Unknown transport for %s", client_obj->name); } } if (local_rc != pcmk_ok && client_obj != NULL) { crm_warn("%sSync reply to %s failed: %s", sync_reply ? "" : "A-", client_obj ? client_obj->name : "<unknown>", pcmk_strerror(local_rc)); } } static void local_notify_destroy_callback(gpointer data) { cib_local_notify_t *notify = data; free_xml(notify->notify_src); free(notify->client_id); free(notify); } static void check_local_notify(int bcast_id) { cib_local_notify_t *notify = NULL; if (!local_notify_queue) { return; } notify = g_hash_table_lookup(local_notify_queue, GINT_TO_POINTER(bcast_id)); if (notify) { do_local_notify(notify->notify_src, notify->client_id, notify->sync_reply, notify->from_peer); g_hash_table_remove(local_notify_queue, GINT_TO_POINTER(bcast_id)); } } static void queue_local_notify(xmlNode * notify_src, const char *client_id, gboolean sync_reply, gboolean from_peer) { cib_local_notify_t *notify = calloc(1, sizeof(cib_local_notify_t)); notify->notify_src = notify_src; notify->client_id = strdup(client_id); notify->sync_reply = sync_reply; notify->from_peer = from_peer; if (!local_notify_queue) { local_notify_queue = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, local_notify_destroy_callback); } g_hash_table_insert(local_notify_queue, GINT_TO_POINTER(cib_local_bcast_num), notify); } static void parse_local_options(cib_client_t * cib_client, int call_type, int call_options, const char *host, const char *op, gboolean * local_notify, gboolean * needs_reply, gboolean * process, gboolean * needs_forward) { if (cib_op_modifies(call_type) && !(call_options & cib_inhibit_bcast)) { /* we need to send an update anyway */ *needs_reply = TRUE; } else { *needs_reply = FALSE; } if (host == NULL && (call_options & cib_scope_local)) { crm_trace("Processing locally scoped %s op from %s", op, cib_client->name); *local_notify = TRUE; } else if (host == NULL && cib_is_master) { crm_trace("Processing master %s op locally from %s", op, cib_client->name); *local_notify = TRUE; } else if (safe_str_eq(host, cib_our_uname)) { crm_trace("Processing locally addressed %s op from %s", op, cib_client->name); *local_notify = TRUE; } else if (stand_alone) { *needs_forward = FALSE; *local_notify = TRUE; *process = TRUE; } else { crm_trace("%s op from %s needs to be forwarded to %s", op, cib_client->name, host ? host : "the master instance"); *needs_forward = TRUE; *process = FALSE; } } static gboolean parse_peer_options(int call_type, xmlNode * request, gboolean * local_notify, gboolean * needs_reply, gboolean * process, gboolean * needs_forward) { const char *op = NULL; const char *host = NULL; const char *delegated = NULL; const char *originator = crm_element_value(request, F_ORIG); const char *reply_to = crm_element_value(request, F_CIB_ISREPLY); const char *update = crm_element_value(request, F_CIB_GLOBAL_UPDATE); gboolean is_reply = safe_str_eq(reply_to, cib_our_uname); if (crm_is_true(update)) { *needs_reply = FALSE; if (is_reply) { *local_notify = TRUE; crm_trace("Processing global/peer update from %s" " that originated from us", originator); } else { crm_trace("Processing global/peer update from %s", originator); } return TRUE; } host = crm_element_value(request, F_CIB_HOST); if (host != NULL && safe_str_eq(host, cib_our_uname)) { crm_trace("Processing request sent to us from %s", originator); return TRUE; } else if (host == NULL && cib_is_master == TRUE) { crm_trace("Processing request sent to master instance from %s", originator); return TRUE; } op = crm_element_value(request, F_CIB_OPERATION); if(safe_str_eq(op, "cib_shutdown_req")) { /* Always process these */ *local_notify = FALSE; if(reply_to == NULL || is_reply) { *process = TRUE; } if(is_reply) { *needs_reply = FALSE; } return *process; } if (is_reply) { crm_trace("Forward reply sent from %s to local clients", originator); *process = FALSE; *needs_reply = FALSE; *local_notify = TRUE; return TRUE; } delegated = crm_element_value(request, F_CIB_DELEGATED); if (delegated != NULL) { crm_trace("Ignoring msg for master instance"); } else if (host != NULL) { /* this is for a specific instance and we're not it */ crm_trace("Ignoring msg for instance on %s", crm_str(host)); } else if (reply_to == NULL && cib_is_master == FALSE) { /* this is for the master instance and we're not it */ crm_trace("Ignoring reply to %s", crm_str(reply_to)); } else if (safe_str_eq(op, "cib_shutdown_req")) { if (reply_to != NULL) { crm_debug("Processing %s from %s", op, host); *needs_reply = FALSE; } else { crm_debug("Processing %s reply from %s", op, host); } return TRUE; } else { crm_err("Nothing for us to do?"); crm_log_xml_err(request, "Peer[inbound]"); } return FALSE; } static void forward_request(xmlNode * request, cib_client_t * cib_client, int call_options) { const char *op = crm_element_value(request, F_CIB_OPERATION); const char *host = crm_element_value(request, F_CIB_HOST); crm_xml_add(request, F_CIB_DELEGATED, cib_our_uname); if (host != NULL) { crm_trace("Forwarding %s op to %s", op, host); send_cluster_message(crm_get_peer(0, host), crm_msg_cib, request, FALSE); } else { crm_trace("Forwarding %s op to master instance", op); send_cluster_message(NULL, crm_msg_cib, request, FALSE); } /* Return the request to its original state */ xml_remove_prop(request, F_CIB_DELEGATED); if (call_options & cib_discard_reply) { crm_trace("Client not interested in reply"); } } static gboolean send_peer_reply(xmlNode * msg, xmlNode * result_diff, const char *originator, gboolean broadcast) { CRM_ASSERT(msg != NULL); if (broadcast) { /* this (successful) call modified the CIB _and_ the * change needs to be broadcast... * send via HA to other nodes */ int diff_add_updates = 0; int diff_add_epoch = 0; int diff_add_admin_epoch = 0; int diff_del_updates = 0; int diff_del_epoch = 0; int diff_del_admin_epoch = 0; const char *digest = NULL; digest = crm_element_value(result_diff, XML_ATTR_DIGEST); cib_diff_version_details(result_diff, &diff_add_admin_epoch, &diff_add_epoch, &diff_add_updates, &diff_del_admin_epoch, &diff_del_epoch, &diff_del_updates); crm_trace("Sending update diff %d.%d.%d -> %d.%d.%d %s", diff_del_admin_epoch, diff_del_epoch, diff_del_updates, diff_add_admin_epoch, diff_add_epoch, diff_add_updates, digest); crm_xml_add(msg, F_CIB_ISREPLY, originator); crm_xml_add(msg, F_CIB_GLOBAL_UPDATE, XML_BOOLEAN_TRUE); crm_xml_add(msg, F_CIB_OPERATION, CIB_OP_APPLY_DIFF); CRM_ASSERT(digest != NULL); add_message_xml(msg, F_CIB_UPDATE_DIFF, result_diff); crm_log_xml_trace(msg, "copy"); return send_cluster_message(NULL, crm_msg_cib, msg, TRUE); } else if (originator != NULL) { /* send reply via HA to originating node */ crm_trace("Sending request result to originator only"); crm_xml_add(msg, F_CIB_ISREPLY, originator); return send_cluster_message(crm_get_peer(0, originator), crm_msg_cib, msg, FALSE); } return FALSE; } void cib_process_request(xmlNode * request, gboolean force_synchronous, gboolean privileged, gboolean from_peer, cib_client_t * cib_client) { int call_type = 0; int call_options = 0; gboolean process = TRUE; gboolean is_update = TRUE; gboolean needs_reply = TRUE; gboolean local_notify = FALSE; gboolean needs_forward = FALSE; gboolean global_update = crm_is_true(crm_element_value(request, F_CIB_GLOBAL_UPDATE)); xmlNode *op_reply = NULL; xmlNode *result_diff = NULL; int rc = pcmk_ok; const char *op = crm_element_value(request, F_CIB_OPERATION); const char *originator = crm_element_value(request, F_ORIG); const char *host = crm_element_value(request, F_CIB_HOST); const char *client_id = crm_element_value(request, F_CIB_CLIENTID); crm_trace("%s Processing msg %s", cib_our_uname, crm_element_value(request, F_SEQ)); cib_num_ops++; if (cib_num_ops == 0) { cib_num_fail = 0; cib_num_local = 0; cib_num_updates = 0; crm_info("Stats wrapped around"); } if (host != NULL && strlen(host) == 0) { host = NULL; } crm_element_value_int(request, F_CIB_CALLOPTS, &call_options); if (force_synchronous) { call_options |= cib_sync_call; } crm_trace("Processing %s message (%s) for %s...", from_peer ? "peer" : "local", from_peer ? originator : cib_our_uname, host ? host : "master"); rc = cib_get_operation_id(op, &call_type); if (rc != pcmk_ok) { /* TODO: construct error reply? */ crm_err("Pre-processing of command failed: %s", pcmk_strerror(rc)); return; } is_update = cib_op_modifies(call_type); if (is_update) { cib_num_updates++; } if (from_peer == FALSE) { parse_local_options(cib_client, call_type, call_options, host, op, &local_notify, &needs_reply, &process, &needs_forward); } else if (parse_peer_options(call_type, request, &local_notify, &needs_reply, &process, &needs_forward) == FALSE) { return; } crm_trace("Finished determining processing actions"); if (call_options & cib_discard_reply) { needs_reply = is_update; local_notify = FALSE; } if (needs_forward) { forward_request(request, cib_client, call_options); return; } if (cib_status != pcmk_ok) { rc = cib_status; crm_err("Operation ignored, cluster configuration is invalid." " Please repair and restart: %s", pcmk_strerror(cib_status)); op_reply = cib_construct_reply(request, the_cib, cib_status); } else if (process) { int level = LOG_INFO; const char *section = crm_element_value(request, F_CIB_SECTION); cib_num_local++; rc = cib_process_command(request, &op_reply, &result_diff, privileged); if (global_update) { switch (rc) { case pcmk_ok: case -pcmk_err_old_data: case -pcmk_err_diff_resync: case -pcmk_err_diff_failed: level = LOG_DEBUG_2; break; default: level = LOG_ERR; } } else if (safe_str_eq(op, CIB_OP_QUERY)) { level = LOG_DEBUG_2; } else if (rc != pcmk_ok) { cib_num_fail++; level = LOG_WARNING; } else if (safe_str_eq(op, CIB_OP_SLAVE)) { level = LOG_DEBUG_2; } else if (safe_str_eq(section, XML_CIB_TAG_STATUS)) { level = LOG_DEBUG_2; } do_crm_log_unlikely(level, "Operation complete: op %s for section %s (origin=%s/%s/%s, version=%s.%s.%s): %s (rc=%d)", op, section ? section : "'all'", originator ? originator : "local", crm_element_value(request, F_CIB_CLIENTNAME), crm_element_value(request, F_CIB_CALLID), the_cib ? crm_element_value(the_cib, XML_ATTR_GENERATION_ADMIN) : "0", the_cib ? crm_element_value(the_cib, XML_ATTR_GENERATION) : "0", the_cib ? crm_element_value(the_cib, XML_ATTR_NUMUPDATES) : "0", pcmk_strerror(rc), rc); if (op_reply == NULL && (needs_reply || local_notify)) { crm_err("Unexpected NULL reply to message"); crm_log_xml_err(request, "null reply"); needs_reply = FALSE; local_notify = FALSE; } } crm_trace("processing response cases %.16x %.16x", call_options, cib_sync_call); /* from now on we are the server */ if (needs_reply == FALSE || stand_alone) { /* nothing more to do... * this was a non-originating slave update */ crm_trace("Completed slave update"); } else if (rc == pcmk_ok && result_diff != NULL && !(call_options & cib_inhibit_bcast)) { gboolean broadcast = FALSE; cib_local_bcast_num++; crm_xml_add_int(request, F_CIB_LOCAL_NOTIFY_ID, cib_local_bcast_num); broadcast = send_peer_reply(request, result_diff, originator, TRUE); if (broadcast && client_id && local_notify && op_reply) { /* If we have been asked to sync the reply, * and a bcast msg has gone out, we queue the local notify * until we know the bcast message has been received */ local_notify = FALSE; queue_local_notify(op_reply, client_id, (call_options & cib_sync_call), from_peer); op_reply = NULL; /* the reply is queued, so don't free here */ } } else if (call_options & cib_discard_reply) { crm_trace("Caller isn't interested in reply"); } else if (from_peer) { if (is_update == FALSE || result_diff == NULL) { crm_trace("Request not broadcast: R/O call"); } else if (call_options & cib_inhibit_bcast) { crm_trace("Request not broadcast: inhibited"); } else if (rc != pcmk_ok) { crm_trace("Request not broadcast: call failed: %s", pcmk_strerror(rc)); } else { crm_trace("Directing reply to %s", originator); } send_peer_reply(op_reply, result_diff, originator, FALSE); } if (local_notify && client_id) { if (process == FALSE) { do_local_notify(request, client_id, call_options & cib_sync_call, from_peer); } else { do_local_notify(op_reply, client_id, call_options & cib_sync_call, from_peer); } } free_xml(op_reply); free_xml(result_diff); return; } xmlNode * cib_construct_reply(xmlNode * request, xmlNode * output, int rc) { int lpc = 0; xmlNode *reply = NULL; const char *name = NULL; const char *value = NULL; const char *names[] = { F_CIB_OPERATION, F_CIB_CALLID, F_CIB_CLIENTID, F_CIB_CALLOPTS }; static int max = DIMOF(names); crm_trace("Creating a basic reply"); reply = create_xml_node(NULL, "cib-reply"); crm_xml_add(reply, F_TYPE, T_CIB); for (lpc = 0; lpc < max; lpc++) { name = names[lpc]; value = crm_element_value(request, name); crm_xml_add(reply, name, value); } crm_xml_add_int(reply, F_CIB_RC, rc); if (output != NULL) { crm_trace("Attaching reply output"); add_message_xml(reply, F_CIB_CALLDATA, output); } return reply; } int cib_process_command(xmlNode * request, xmlNode ** reply, xmlNode ** cib_diff, gboolean privileged) { xmlNode *input = NULL; xmlNode *output = NULL; xmlNode *result_cib = NULL; xmlNode *current_cib = NULL; #if ENABLE_ACL xmlNode *filtered_current_cib = NULL; #endif int call_type = 0; int call_options = 0; int log_level = LOG_DEBUG_4; const char *op = NULL; const char *section = NULL; int rc = pcmk_ok; int rc2 = pcmk_ok; gboolean send_r_notify = FALSE; gboolean global_update = FALSE; gboolean config_changed = FALSE; gboolean manage_counters = TRUE; CRM_ASSERT(cib_status == pcmk_ok); *reply = NULL; *cib_diff = NULL; current_cib = the_cib; /* Start processing the request... */ op = crm_element_value(request, F_CIB_OPERATION); crm_element_value_int(request, F_CIB_CALLOPTS, &call_options); rc = cib_get_operation_id(op, &call_type); if (rc == pcmk_ok && privileged == FALSE) { rc = cib_op_can_run(call_type, call_options, privileged, global_update); } rc2 = cib_op_prepare(call_type, request, &input, &section); if (rc == pcmk_ok) { rc = rc2; } if (rc != pcmk_ok) { crm_trace("Call setup failed: %s", pcmk_strerror(rc)); goto done; } else if (cib_op_modifies(call_type) == FALSE) { #if ENABLE_ACL if (acl_enabled(config_hash) == FALSE || acl_filter_cib(request, current_cib, current_cib, &filtered_current_cib) == FALSE) { rc = cib_perform_op(op, call_options, cib_op_func(call_type), TRUE, section, request, input, FALSE, &config_changed, current_cib, &result_cib, NULL, &output); } else if (filtered_current_cib == NULL) { crm_debug("Pre-filtered the entire cib"); rc = -EACCES; } else { crm_debug("Pre-filtered the queried cib according to the ACLs"); rc = cib_perform_op(op, call_options, cib_op_func(call_type), TRUE, section, request, input, FALSE, &config_changed, filtered_current_cib, &result_cib, NULL, &output); } #else rc = cib_perform_op(op, call_options, cib_op_func(call_type), TRUE, section, request, input, FALSE, &config_changed, current_cib, &result_cib, NULL, &output); #endif CRM_CHECK(result_cib == NULL, free_xml(result_cib)); goto done; } /* Handle a valid write action */ global_update = crm_is_true(crm_element_value(request, F_CIB_GLOBAL_UPDATE)); if (global_update) { manage_counters = FALSE; call_options |= cib_force_diff; CRM_CHECK(call_type == 3 || call_type == 4, crm_err("Call type: %d", call_type); crm_log_xml_err(request, "bad op")); } #ifdef SUPPORT_PRENOTIFY if ((call_options & cib_inhibit_notify) == 0) { cib_pre_notify(call_options, op, the_cib, input); } #endif if (rc == pcmk_ok) { if (call_options & cib_inhibit_bcast) { /* skip */ crm_trace("Skipping update: inhibit broadcast"); manage_counters = FALSE; } rc = cib_perform_op(op, call_options, cib_op_func(call_type), FALSE, section, request, input, manage_counters, &config_changed, current_cib, &result_cib, cib_diff, &output); #if ENABLE_ACL if (acl_enabled(config_hash) == TRUE && acl_check_diff(request, current_cib, result_cib, *cib_diff) == FALSE) { rc = -EACCES; } #endif if (rc == pcmk_ok && config_changed) { time_t now; char *now_str = NULL; const char *validation = crm_element_value(result_cib, XML_ATTR_VALIDATION); if (validation) { int current_version = get_schema_version(validation); int support_version = get_schema_version("pacemaker-1.1"); /* Once the later schemas support the "update-*" attributes, change "==" to ">=" -- Changed */ if (current_version >= support_version) { const char *origin = crm_element_value(request, F_ORIG); crm_xml_replace(result_cib, XML_ATTR_UPDATE_ORIG, origin ? origin : cib_our_uname); crm_xml_replace(result_cib, XML_ATTR_UPDATE_CLIENT, crm_element_value(request, F_CIB_CLIENTNAME)); #if ENABLE_ACL crm_xml_replace(result_cib, XML_ATTR_UPDATE_USER, crm_element_value(request, F_CIB_USER)); #endif } } now = time(NULL); now_str = ctime(&now); now_str[24] = EOS; /* replace the newline */ crm_xml_replace(result_cib, XML_CIB_ATTR_WRITTEN, now_str); } if (manage_counters == FALSE) { config_changed = cib_config_changed(current_cib, result_cib, cib_diff); } /* Always write to disk for replace ops, * this negates the need to detect ordering changes */ if (config_changed == FALSE && crm_str_eq(CIB_OP_REPLACE, op, TRUE)) { config_changed = TRUE; } } cib_add_digest(result_cib, *cib_diff); if (rc == pcmk_ok && (call_options & cib_dryrun) == 0) { rc = activateCibXml(result_cib, config_changed, op); if (rc == pcmk_ok && cib_internal_config_changed(*cib_diff)) { cib_read_config(config_hash, result_cib); } if (crm_str_eq(CIB_OP_REPLACE, op, TRUE)) { if (section == NULL) { send_r_notify = TRUE; } else if (safe_str_eq(section, XML_TAG_CIB)) { send_r_notify = TRUE; } else if (safe_str_eq(section, XML_CIB_TAG_NODES)) { send_r_notify = TRUE; } else if (safe_str_eq(section, XML_CIB_TAG_STATUS)) { send_r_notify = TRUE; } } else if (crm_str_eq(CIB_OP_ERASE, op, TRUE)) { send_r_notify = TRUE; } } else if (rc == -pcmk_err_dtd_validation) { if (output != NULL) { crm_log_xml_info(output, "cib:output"); free_xml(output); } #if ENABLE_ACL { xmlNode *filtered_result_cib = NULL; if (acl_enabled(config_hash) == FALSE || acl_filter_cib(request, current_cib, result_cib, &filtered_result_cib) == FALSE) { output = result_cib; } else { crm_debug("Filtered the result cib for output according to the ACLs"); output = filtered_result_cib; if (result_cib != NULL) { free_xml(result_cib); } } } #else output = result_cib; #endif } else { free_xml(result_cib); } if ((call_options & cib_inhibit_notify) == 0) { const char *call_id = crm_element_value(request, F_CIB_CALLID); const char *client = crm_element_value(request, F_CIB_CLIENTNAME); #ifdef SUPPORT_POSTNOTIFY cib_post_notify(call_options, op, input, rc, the_cib); #endif cib_diff_notify(call_options, client, call_id, op, input, rc, *cib_diff); } if (send_r_notify) { const char *origin = crm_element_value(request, F_ORIG); cib_replace_notify(origin, the_cib, rc, *cib_diff); } if (rc != pcmk_ok) { log_level = LOG_DEBUG_4; if (rc == -pcmk_err_dtd_validation && global_update) { log_level = LOG_WARNING; crm_log_xml_info(input, "cib:global_update"); } } else if (config_changed) { log_level = LOG_DEBUG_3; if (cib_is_master) { log_level = LOG_NOTICE; } } else if (cib_is_master) { log_level = LOG_DEBUG_2; } log_cib_diff(log_level, *cib_diff, "cib:diff"); done: if ((call_options & cib_discard_reply) == 0) { *reply = cib_construct_reply(request, output, rc); crm_log_xml_trace(*reply, "cib:reply"); } #if ENABLE_ACL if (filtered_current_cib != NULL) { free_xml(filtered_current_cib); } #endif if (call_type >= 0) { cib_op_cleanup(call_type, call_options, &input, &output); } return rc; } gint cib_GCompareFunc(gconstpointer a, gconstpointer b) { const xmlNode *a_msg = a; const xmlNode *b_msg = b; int msg_a_id = 0; int msg_b_id = 0; const char *value = NULL; value = crm_element_value_const(a_msg, F_CIB_CALLID); msg_a_id = crm_parse_int(value, NULL); value = crm_element_value_const(b_msg, F_CIB_CALLID); msg_b_id = crm_parse_int(value, NULL); if (msg_a_id == msg_b_id) { return 0; } else if (msg_a_id < msg_b_id) { return -1; } return 1; } #if SUPPORT_HEARTBEAT void cib_ha_peer_callback(HA_Message * msg, void *private_data) { xmlNode *xml = convert_ha_message(NULL, msg, __FUNCTION__); cib_peer_callback(xml, private_data); free_xml(xml); } #endif void cib_peer_callback(xmlNode * msg, void *private_data) { const char *reason = NULL; const char *originator = crm_element_value(msg, F_ORIG); if (originator == NULL || crm_str_eq(originator, cib_our_uname, TRUE)) { /* message is from ourselves */ int bcast_id = 0; if (!(crm_element_value_int(msg, F_CIB_LOCAL_NOTIFY_ID, &bcast_id))) { check_local_notify(bcast_id); } return; } else if (crm_peer_cache == NULL) { reason = "membership not established"; goto bail; } if (crm_element_value(msg, F_CIB_CLIENTNAME) == NULL) { crm_xml_add(msg, F_CIB_CLIENTNAME, originator); } /* crm_log_xml_trace("Peer[inbound]", msg); */ cib_process_request(msg, FALSE, TRUE, TRUE, NULL); return; bail: if (reason) { const char *seq = crm_element_value(msg, F_SEQ); const char *op = crm_element_value(msg, F_CIB_OPERATION); crm_warn("Discarding %s message (%s) from %s: %s", op, seq, originator, reason); } } #if SUPPORT_HEARTBEAT extern oc_ev_t *cib_ev_token; static void *ccm_library = NULL; int (*ccm_api_callback_done) (void *cookie) = NULL; int (*ccm_api_handle_event) (const oc_ev_t * token) = NULL; void cib_client_status_callback(const char *node, const char *client, const char *status, void *private) { crm_node_t *peer = NULL; if (safe_str_eq(client, CRM_SYSTEM_CIB)) { crm_info("Status update: Client %s/%s now has status [%s]", node, client, status); if (safe_str_eq(status, JOINSTATUS)) { status = ONLINESTATUS; } else if (safe_str_eq(status, LEAVESTATUS)) { status = OFFLINESTATUS; } peer = crm_get_peer(0, node); crm_update_peer_proc(__FUNCTION__, peer, crm_proc_cib, status); } return; } int cib_ccm_dispatch(gpointer user_data) { int rc = 0; oc_ev_t *ccm_token = (oc_ev_t *) user_data; crm_trace("received callback"); if (ccm_api_handle_event == NULL) { ccm_api_handle_event = find_library_function(&ccm_library, CCM_LIBRARY, "oc_ev_handle_event", 1); } rc = (*ccm_api_handle_event) (ccm_token); if (0 == rc) { return 0; } crm_err("CCM connection appears to have failed: rc=%d.", rc); /* eventually it might be nice to recover and reconnect... but until then... */ crm_err("Exiting to recover from CCM connection failure"); crm_exit(2); return -1; } int current_instance = 0; void cib_ccm_msg_callback(oc_ed_t event, void *cookie, size_t size, const void *data) { gboolean update_id = FALSE; const oc_ev_membership_t *membership = data; CRM_ASSERT(membership != NULL); crm_info("Processing CCM event=%s (id=%d)", ccm_event_name(event), membership->m_instance); if (current_instance > membership->m_instance) { crm_err("Membership instance ID went backwards! %d->%d", current_instance, membership->m_instance); CRM_ASSERT(current_instance <= membership->m_instance); } switch (event) { case OC_EV_MS_NEW_MEMBERSHIP: case OC_EV_MS_INVALID: update_id = TRUE; break; case OC_EV_MS_PRIMARY_RESTORED: update_id = TRUE; break; case OC_EV_MS_NOT_PRIMARY: crm_trace("Ignoring transitional CCM event: %s", ccm_event_name(event)); break; case OC_EV_MS_EVICTED: crm_err("Evicted from CCM: %s", ccm_event_name(event)); break; default: crm_err("Unknown CCM event: %d", event); } if (update_id) { unsigned int lpc = 0; CRM_CHECK(membership != NULL, return); current_instance = membership->m_instance; for (lpc = 0; lpc < membership->m_n_out; lpc++) { crm_update_ccm_node(membership, lpc + membership->m_out_idx, CRM_NODE_LOST, current_instance); } for (lpc = 0; lpc < membership->m_n_member; lpc++) { crm_update_ccm_node(membership, lpc + membership->m_memb_idx, CRM_NODE_ACTIVE, current_instance); } } if (ccm_api_callback_done == NULL) { ccm_api_callback_done = find_library_function(&ccm_library, CCM_LIBRARY, "oc_ev_callback_done", 1); } (*ccm_api_callback_done) (cookie); return; } #endif gboolean can_write(int flags) { return TRUE; } static gboolean cib_force_exit(gpointer data) { crm_notice("Forcing exit!"); terminate_cib(__FUNCTION__, TRUE); return FALSE; } static void disconnect_remote_client(gpointer key, gpointer value, gpointer user_data) { cib_client_t *a_client = value; crm_err("Disconnecting %s... Not implemented", crm_str(a_client->name)); } void cib_shutdown(int nsig) { struct qb_ipcs_stats srv_stats; if (cib_shutdown_flag == FALSE) { int disconnects = 0; qb_ipcs_connection_t *c = NULL; cib_shutdown_flag = TRUE; c = qb_ipcs_connection_first_get(ipcs_rw); while(c != NULL) { qb_ipcs_connection_t *last = c; c = qb_ipcs_connection_next_get(ipcs_rw, last); crm_debug("Disconnecting r/w client %p...", last); qb_ipcs_disconnect(last); qb_ipcs_connection_unref(last); disconnects++; } c = qb_ipcs_connection_first_get(ipcs_ro); while(c != NULL) { qb_ipcs_connection_t *last = c; c = qb_ipcs_connection_next_get(ipcs_ro, last); crm_debug("Disconnecting r/o client %p...", last); qb_ipcs_disconnect(last); qb_ipcs_connection_unref(last); disconnects++; } c = qb_ipcs_connection_first_get(ipcs_shm); while(c != NULL) { qb_ipcs_connection_t *last = c; c = qb_ipcs_connection_next_get(ipcs_shm, last); crm_debug("Disconnecting non-blocking r/w client %p...", last); qb_ipcs_disconnect(last); qb_ipcs_connection_unref(last); disconnects++; } disconnects += g_hash_table_size(client_list); crm_debug("Disconnecting %d remote clients", g_hash_table_size(client_list)); g_hash_table_foreach(client_list, disconnect_remote_client, NULL); crm_info("Disconnected %d clients", disconnects); } qb_ipcs_stats_get(ipcs_rw, &srv_stats, QB_FALSE); if(g_hash_table_size(client_list) == 0) { crm_info("All clients disconnected (%d)", srv_stats.active_connections); initiate_exit(); } else { crm_info("Waiting on %d clients to disconnect (%d)", g_hash_table_size(client_list), srv_stats.active_connections); } } void initiate_exit(void) { int active = 0; xmlNode *leaving = NULL; active = crm_active_peers(); if (active < 2) { terminate_cib(__FUNCTION__, FALSE); return; } crm_info("Sending disconnect notification to %d peers...", active); leaving = create_xml_node(NULL, "exit-notification"); crm_xml_add(leaving, F_TYPE, "cib"); crm_xml_add(leaving, F_CIB_OPERATION, "cib_shutdown_req"); send_cluster_message(NULL, crm_msg_cib, leaving, TRUE); free_xml(leaving); g_timeout_add(crm_get_msec("5s"), cib_force_exit, NULL); } extern int remote_fd; extern int remote_tls_fd; extern void terminate_cs_connection(void); void terminate_cib(const char *caller, gboolean fast) { if (remote_fd > 0) { close(remote_fd); remote_fd = 0; } if (remote_tls_fd > 0) { close(remote_tls_fd); remote_tls_fd = 0; } if(!fast) { crm_info("%s: Disconnecting from cluster infrastructure", caller); crm_cluster_disconnect(&crm_cluster); } uninitializeCib(); crm_info("%s: Exiting%s...", caller, fast?" fast":mainloop?" from mainloop":""); if(fast == FALSE && mainloop != NULL && g_main_is_running(mainloop)) { g_main_quit(mainloop); } else { qb_ipcs_destroy(ipcs_ro); qb_ipcs_destroy(ipcs_rw); qb_ipcs_destroy(ipcs_shm); if (fast) { crm_exit(EX_USAGE); } else { crm_exit(EX_OK); } } }
./CrossVul/dataset_final_sorted/CWE-399/c/bad_5561_0
crossvul-cpp_data_good_3486_6
/* * linux/arch/arm/mm/fault.c * * Copyright (C) 1995 Linus Torvalds * Modifications for ARM processor (c) 1995-2004 Russell King * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/module.h> #include <linux/signal.h> #include <linux/mm.h> #include <linux/hardirq.h> #include <linux/init.h> #include <linux/kprobes.h> #include <linux/uaccess.h> #include <linux/page-flags.h> #include <linux/sched.h> #include <linux/highmem.h> #include <linux/perf_event.h> #include <asm/system.h> #include <asm/pgtable.h> #include <asm/tlbflush.h> #include "fault.h" /* * Fault status register encodings. We steal bit 31 for our own purposes. */ #define FSR_LNX_PF (1 << 31) #define FSR_WRITE (1 << 11) #define FSR_FS4 (1 << 10) #define FSR_FS3_0 (15) static inline int fsr_fs(unsigned int fsr) { return (fsr & FSR_FS3_0) | (fsr & FSR_FS4) >> 6; } #ifdef CONFIG_MMU #ifdef CONFIG_KPROBES static inline int notify_page_fault(struct pt_regs *regs, unsigned int fsr) { int ret = 0; if (!user_mode(regs)) { /* kprobe_running() needs smp_processor_id() */ preempt_disable(); if (kprobe_running() && kprobe_fault_handler(regs, fsr)) ret = 1; preempt_enable(); } return ret; } #else static inline int notify_page_fault(struct pt_regs *regs, unsigned int fsr) { return 0; } #endif /* * This is useful to dump out the page tables associated with * 'addr' in mm 'mm'. */ void show_pte(struct mm_struct *mm, unsigned long addr) { pgd_t *pgd; if (!mm) mm = &init_mm; printk(KERN_ALERT "pgd = %p\n", mm->pgd); pgd = pgd_offset(mm, addr); printk(KERN_ALERT "[%08lx] *pgd=%08llx", addr, (long long)pgd_val(*pgd)); do { pud_t *pud; pmd_t *pmd; pte_t *pte; if (pgd_none(*pgd)) break; if (pgd_bad(*pgd)) { printk("(bad)"); break; } pud = pud_offset(pgd, addr); if (PTRS_PER_PUD != 1) printk(", *pud=%08lx", pud_val(*pud)); if (pud_none(*pud)) break; if (pud_bad(*pud)) { printk("(bad)"); break; } pmd = pmd_offset(pud, addr); if (PTRS_PER_PMD != 1) printk(", *pmd=%08llx", (long long)pmd_val(*pmd)); if (pmd_none(*pmd)) break; if (pmd_bad(*pmd)) { printk("(bad)"); break; } /* We must not map this if we have highmem enabled */ if (PageHighMem(pfn_to_page(pmd_val(*pmd) >> PAGE_SHIFT))) break; pte = pte_offset_map(pmd, addr); printk(", *pte=%08llx", (long long)pte_val(*pte)); printk(", *ppte=%08llx", (long long)pte_val(pte[PTE_HWTABLE_PTRS])); pte_unmap(pte); } while(0); printk("\n"); } #else /* CONFIG_MMU */ void show_pte(struct mm_struct *mm, unsigned long addr) { } #endif /* CONFIG_MMU */ /* * Oops. The kernel tried to access some page that wasn't present. */ static void __do_kernel_fault(struct mm_struct *mm, unsigned long addr, unsigned int fsr, struct pt_regs *regs) { /* * Are we prepared to handle this kernel fault? */ if (fixup_exception(regs)) return; /* * No handler, we'll have to terminate things with extreme prejudice. */ bust_spinlocks(1); printk(KERN_ALERT "Unable to handle kernel %s at virtual address %08lx\n", (addr < PAGE_SIZE) ? "NULL pointer dereference" : "paging request", addr); show_pte(mm, addr); die("Oops", regs, fsr); bust_spinlocks(0); do_exit(SIGKILL); } /* * Something tried to access memory that isn't in our memory map.. * User mode accesses just cause a SIGSEGV */ static void __do_user_fault(struct task_struct *tsk, unsigned long addr, unsigned int fsr, unsigned int sig, int code, struct pt_regs *regs) { struct siginfo si; #ifdef CONFIG_DEBUG_USER if (user_debug & UDBG_SEGV) { printk(KERN_DEBUG "%s: unhandled page fault (%d) at 0x%08lx, code 0x%03x\n", tsk->comm, sig, addr, fsr); show_pte(tsk->mm, addr); show_regs(regs); } #endif tsk->thread.address = addr; tsk->thread.error_code = fsr; tsk->thread.trap_no = 14; si.si_signo = sig; si.si_errno = 0; si.si_code = code; si.si_addr = (void __user *)addr; force_sig_info(sig, &si, tsk); } void do_bad_area(unsigned long addr, unsigned int fsr, struct pt_regs *regs) { struct task_struct *tsk = current; struct mm_struct *mm = tsk->active_mm; /* * If we are in kernel mode at this point, we * have no context to handle this fault with. */ if (user_mode(regs)) __do_user_fault(tsk, addr, fsr, SIGSEGV, SEGV_MAPERR, regs); else __do_kernel_fault(mm, addr, fsr, regs); } #ifdef CONFIG_MMU #define VM_FAULT_BADMAP 0x010000 #define VM_FAULT_BADACCESS 0x020000 /* * Check that the permissions on the VMA allow for the fault which occurred. * If we encountered a write fault, we must have write permission, otherwise * we allow any permission. */ static inline bool access_error(unsigned int fsr, struct vm_area_struct *vma) { unsigned int mask = VM_READ | VM_WRITE | VM_EXEC; if (fsr & FSR_WRITE) mask = VM_WRITE; if (fsr & FSR_LNX_PF) mask = VM_EXEC; return vma->vm_flags & mask ? false : true; } static int __kprobes __do_page_fault(struct mm_struct *mm, unsigned long addr, unsigned int fsr, struct task_struct *tsk) { struct vm_area_struct *vma; int fault; vma = find_vma(mm, addr); fault = VM_FAULT_BADMAP; if (unlikely(!vma)) goto out; if (unlikely(vma->vm_start > addr)) goto check_stack; /* * Ok, we have a good vm_area for this * memory access, so we can handle it. */ good_area: if (access_error(fsr, vma)) { fault = VM_FAULT_BADACCESS; goto out; } /* * If for any reason at all we couldn't handle the fault, make * sure we exit gracefully rather than endlessly redo the fault. */ fault = handle_mm_fault(mm, vma, addr & PAGE_MASK, (fsr & FSR_WRITE) ? FAULT_FLAG_WRITE : 0); if (unlikely(fault & VM_FAULT_ERROR)) return fault; if (fault & VM_FAULT_MAJOR) tsk->maj_flt++; else tsk->min_flt++; return fault; check_stack: if (vma->vm_flags & VM_GROWSDOWN && !expand_stack(vma, addr)) goto good_area; out: return fault; } static int __kprobes do_page_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs) { struct task_struct *tsk; struct mm_struct *mm; int fault, sig, code; if (notify_page_fault(regs, fsr)) return 0; tsk = current; mm = tsk->mm; /* * If we're in an interrupt or have no user * context, we must not take the fault.. */ if (in_atomic() || !mm) goto no_context; /* * As per x86, we may deadlock here. However, since the kernel only * validly references user space from well defined areas of the code, * we can bug out early if this is from code which shouldn't. */ if (!down_read_trylock(&mm->mmap_sem)) { if (!user_mode(regs) && !search_exception_tables(regs->ARM_pc)) goto no_context; down_read(&mm->mmap_sem); } else { /* * The above down_read_trylock() might have succeeded in * which case, we'll have missed the might_sleep() from * down_read() */ might_sleep(); #ifdef CONFIG_DEBUG_VM if (!user_mode(regs) && !search_exception_tables(regs->ARM_pc)) goto no_context; #endif } fault = __do_page_fault(mm, addr, fsr, tsk); up_read(&mm->mmap_sem); perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS, 1, regs, addr); if (fault & VM_FAULT_MAJOR) perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MAJ, 1, regs, addr); else if (fault & VM_FAULT_MINOR) perf_sw_event(PERF_COUNT_SW_PAGE_FAULTS_MIN, 1, regs, addr); /* * Handle the "normal" case first - VM_FAULT_MAJOR / VM_FAULT_MINOR */ if (likely(!(fault & (VM_FAULT_ERROR | VM_FAULT_BADMAP | VM_FAULT_BADACCESS)))) return 0; if (fault & VM_FAULT_OOM) { /* * We ran out of memory, call the OOM killer, and return to * userspace (which will retry the fault, or kill us if we * got oom-killed) */ pagefault_out_of_memory(); return 0; } /* * If we are in kernel mode at this point, we * have no context to handle this fault with. */ if (!user_mode(regs)) goto no_context; if (fault & VM_FAULT_SIGBUS) { /* * We had some memory, but were unable to * successfully fix up this page fault. */ sig = SIGBUS; code = BUS_ADRERR; } else { /* * Something tried to access memory that * isn't in our memory map.. */ sig = SIGSEGV; code = fault == VM_FAULT_BADACCESS ? SEGV_ACCERR : SEGV_MAPERR; } __do_user_fault(tsk, addr, fsr, sig, code, regs); return 0; no_context: __do_kernel_fault(mm, addr, fsr, regs); return 0; } #else /* CONFIG_MMU */ static int do_page_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs) { return 0; } #endif /* CONFIG_MMU */ /* * First Level Translation Fault Handler * * We enter here because the first level page table doesn't contain * a valid entry for the address. * * If the address is in kernel space (>= TASK_SIZE), then we are * probably faulting in the vmalloc() area. * * If the init_task's first level page tables contains the relevant * entry, we copy the it to this task. If not, we send the process * a signal, fixup the exception, or oops the kernel. * * NOTE! We MUST NOT take any locks for this case. We may be in an * interrupt or a critical region, and should only copy the information * from the master page table, nothing more. */ #ifdef CONFIG_MMU static int __kprobes do_translation_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs) { unsigned int index; pgd_t *pgd, *pgd_k; pud_t *pud, *pud_k; pmd_t *pmd, *pmd_k; if (addr < TASK_SIZE) return do_page_fault(addr, fsr, regs); if (user_mode(regs)) goto bad_area; index = pgd_index(addr); /* * FIXME: CP15 C1 is write only on ARMv3 architectures. */ pgd = cpu_get_pgd() + index; pgd_k = init_mm.pgd + index; if (pgd_none(*pgd_k)) goto bad_area; if (!pgd_present(*pgd)) set_pgd(pgd, *pgd_k); pud = pud_offset(pgd, addr); pud_k = pud_offset(pgd_k, addr); if (pud_none(*pud_k)) goto bad_area; if (!pud_present(*pud)) set_pud(pud, *pud_k); pmd = pmd_offset(pud, addr); pmd_k = pmd_offset(pud_k, addr); /* * On ARM one Linux PGD entry contains two hardware entries (see page * tables layout in pgtable.h). We normally guarantee that we always * fill both L1 entries. But create_mapping() doesn't follow the rule. * It can create inidividual L1 entries, so here we have to call * pmd_none() check for the entry really corresponded to address, not * for the first of pair. */ index = (addr >> SECTION_SHIFT) & 1; if (pmd_none(pmd_k[index])) goto bad_area; copy_pmd(pmd, pmd_k); return 0; bad_area: do_bad_area(addr, fsr, regs); return 0; } #else /* CONFIG_MMU */ static int do_translation_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs) { return 0; } #endif /* CONFIG_MMU */ /* * Some section permission faults need to be handled gracefully. * They can happen due to a __{get,put}_user during an oops. */ static int do_sect_fault(unsigned long addr, unsigned int fsr, struct pt_regs *regs) { do_bad_area(addr, fsr, regs); return 0; } /* * This abort handler always returns "fault". */ static int do_bad(unsigned long addr, unsigned int fsr, struct pt_regs *regs) { return 1; } static struct fsr_info { int (*fn)(unsigned long addr, unsigned int fsr, struct pt_regs *regs); int sig; int code; const char *name; } fsr_info[] = { /* * The following are the standard ARMv3 and ARMv4 aborts. ARMv5 * defines these to be "precise" aborts. */ { do_bad, SIGSEGV, 0, "vector exception" }, { do_bad, SIGBUS, BUS_ADRALN, "alignment exception" }, { do_bad, SIGKILL, 0, "terminal exception" }, { do_bad, SIGBUS, BUS_ADRALN, "alignment exception" }, { do_bad, SIGBUS, 0, "external abort on linefetch" }, { do_translation_fault, SIGSEGV, SEGV_MAPERR, "section translation fault" }, { do_bad, SIGBUS, 0, "external abort on linefetch" }, { do_page_fault, SIGSEGV, SEGV_MAPERR, "page translation fault" }, { do_bad, SIGBUS, 0, "external abort on non-linefetch" }, { do_bad, SIGSEGV, SEGV_ACCERR, "section domain fault" }, { do_bad, SIGBUS, 0, "external abort on non-linefetch" }, { do_bad, SIGSEGV, SEGV_ACCERR, "page domain fault" }, { do_bad, SIGBUS, 0, "external abort on translation" }, { do_sect_fault, SIGSEGV, SEGV_ACCERR, "section permission fault" }, { do_bad, SIGBUS, 0, "external abort on translation" }, { do_page_fault, SIGSEGV, SEGV_ACCERR, "page permission fault" }, /* * The following are "imprecise" aborts, which are signalled by bit * 10 of the FSR, and may not be recoverable. These are only * supported if the CPU abort handler supports bit 10. */ { do_bad, SIGBUS, 0, "unknown 16" }, { do_bad, SIGBUS, 0, "unknown 17" }, { do_bad, SIGBUS, 0, "unknown 18" }, { do_bad, SIGBUS, 0, "unknown 19" }, { do_bad, SIGBUS, 0, "lock abort" }, /* xscale */ { do_bad, SIGBUS, 0, "unknown 21" }, { do_bad, SIGBUS, BUS_OBJERR, "imprecise external abort" }, /* xscale */ { do_bad, SIGBUS, 0, "unknown 23" }, { do_bad, SIGBUS, 0, "dcache parity error" }, /* xscale */ { do_bad, SIGBUS, 0, "unknown 25" }, { do_bad, SIGBUS, 0, "unknown 26" }, { do_bad, SIGBUS, 0, "unknown 27" }, { do_bad, SIGBUS, 0, "unknown 28" }, { do_bad, SIGBUS, 0, "unknown 29" }, { do_bad, SIGBUS, 0, "unknown 30" }, { do_bad, SIGBUS, 0, "unknown 31" } }; void __init hook_fault_code(int nr, int (*fn)(unsigned long, unsigned int, struct pt_regs *), int sig, int code, const char *name) { if (nr < 0 || nr >= ARRAY_SIZE(fsr_info)) BUG(); fsr_info[nr].fn = fn; fsr_info[nr].sig = sig; fsr_info[nr].code = code; fsr_info[nr].name = name; } /* * Dispatch a data abort to the relevant handler. */ asmlinkage void __exception do_DataAbort(unsigned long addr, unsigned int fsr, struct pt_regs *regs) { const struct fsr_info *inf = fsr_info + fsr_fs(fsr); struct siginfo info; if (!inf->fn(addr, fsr & ~FSR_LNX_PF, regs)) return; printk(KERN_ALERT "Unhandled fault: %s (0x%03x) at 0x%08lx\n", inf->name, fsr, addr); info.si_signo = inf->sig; info.si_errno = 0; info.si_code = inf->code; info.si_addr = (void __user *)addr; arm_notify_die("", regs, &info, fsr, 0); } static struct fsr_info ifsr_info[] = { { do_bad, SIGBUS, 0, "unknown 0" }, { do_bad, SIGBUS, 0, "unknown 1" }, { do_bad, SIGBUS, 0, "debug event" }, { do_bad, SIGSEGV, SEGV_ACCERR, "section access flag fault" }, { do_bad, SIGBUS, 0, "unknown 4" }, { do_translation_fault, SIGSEGV, SEGV_MAPERR, "section translation fault" }, { do_bad, SIGSEGV, SEGV_ACCERR, "page access flag fault" }, { do_page_fault, SIGSEGV, SEGV_MAPERR, "page translation fault" }, { do_bad, SIGBUS, 0, "external abort on non-linefetch" }, { do_bad, SIGSEGV, SEGV_ACCERR, "section domain fault" }, { do_bad, SIGBUS, 0, "unknown 10" }, { do_bad, SIGSEGV, SEGV_ACCERR, "page domain fault" }, { do_bad, SIGBUS, 0, "external abort on translation" }, { do_sect_fault, SIGSEGV, SEGV_ACCERR, "section permission fault" }, { do_bad, SIGBUS, 0, "external abort on translation" }, { do_page_fault, SIGSEGV, SEGV_ACCERR, "page permission fault" }, { do_bad, SIGBUS, 0, "unknown 16" }, { do_bad, SIGBUS, 0, "unknown 17" }, { do_bad, SIGBUS, 0, "unknown 18" }, { do_bad, SIGBUS, 0, "unknown 19" }, { do_bad, SIGBUS, 0, "unknown 20" }, { do_bad, SIGBUS, 0, "unknown 21" }, { do_bad, SIGBUS, 0, "unknown 22" }, { do_bad, SIGBUS, 0, "unknown 23" }, { do_bad, SIGBUS, 0, "unknown 24" }, { do_bad, SIGBUS, 0, "unknown 25" }, { do_bad, SIGBUS, 0, "unknown 26" }, { do_bad, SIGBUS, 0, "unknown 27" }, { do_bad, SIGBUS, 0, "unknown 28" }, { do_bad, SIGBUS, 0, "unknown 29" }, { do_bad, SIGBUS, 0, "unknown 30" }, { do_bad, SIGBUS, 0, "unknown 31" }, }; void __init hook_ifault_code(int nr, int (*fn)(unsigned long, unsigned int, struct pt_regs *), int sig, int code, const char *name) { if (nr < 0 || nr >= ARRAY_SIZE(ifsr_info)) BUG(); ifsr_info[nr].fn = fn; ifsr_info[nr].sig = sig; ifsr_info[nr].code = code; ifsr_info[nr].name = name; } asmlinkage void __exception do_PrefetchAbort(unsigned long addr, unsigned int ifsr, struct pt_regs *regs) { const struct fsr_info *inf = ifsr_info + fsr_fs(ifsr); struct siginfo info; if (!inf->fn(addr, ifsr | FSR_LNX_PF, regs)) return; printk(KERN_ALERT "Unhandled prefetch abort: %s (0x%03x) at 0x%08lx\n", inf->name, ifsr, addr); info.si_signo = inf->sig; info.si_errno = 0; info.si_code = inf->code; info.si_addr = (void __user *)addr; arm_notify_die("", regs, &info, ifsr, 0); } static int __init exceptions_init(void) { if (cpu_architecture() >= CPU_ARCH_ARMv6) { hook_fault_code(4, do_translation_fault, SIGSEGV, SEGV_MAPERR, "I-cache maintenance fault"); } if (cpu_architecture() >= CPU_ARCH_ARMv7) { /* * TODO: Access flag faults introduced in ARMv6K. * Runtime check for 'K' extension is needed */ hook_fault_code(3, do_bad, SIGSEGV, SEGV_MAPERR, "section access flag fault"); hook_fault_code(6, do_bad, SIGSEGV, SEGV_MAPERR, "section access flag fault"); } return 0; } arch_initcall(exceptions_init);
./CrossVul/dataset_final_sorted/CWE-399/c/good_3486_6
crossvul-cpp_data_bad_2262_2
/* * linux/fs/isofs/rock.c * * (C) 1992, 1993 Eric Youngdale * * Rock Ridge Extensions to iso9660 */ #include <linux/slab.h> #include <linux/pagemap.h> #include "isofs.h" #include "rock.h" /* * These functions are designed to read the system areas of a directory record * and extract relevant information. There are different functions provided * depending upon what information we need at the time. One function fills * out an inode structure, a second one extracts a filename, a third one * returns a symbolic link name, and a fourth one returns the extent number * for the file. */ #define SIG(A,B) ((A) | ((B) << 8)) /* isonum_721() */ struct rock_state { void *buffer; unsigned char *chr; int len; int cont_size; int cont_extent; int cont_offset; struct inode *inode; }; /* * This is a way of ensuring that we have something in the system * use fields that is compatible with Rock Ridge. Return zero on success. */ static int check_sp(struct rock_ridge *rr, struct inode *inode) { if (rr->u.SP.magic[0] != 0xbe) return -1; if (rr->u.SP.magic[1] != 0xef) return -1; ISOFS_SB(inode->i_sb)->s_rock_offset = rr->u.SP.skip; return 0; } static void setup_rock_ridge(struct iso_directory_record *de, struct inode *inode, struct rock_state *rs) { rs->len = sizeof(struct iso_directory_record) + de->name_len[0]; if (rs->len & 1) (rs->len)++; rs->chr = (unsigned char *)de + rs->len; rs->len = *((unsigned char *)de) - rs->len; if (rs->len < 0) rs->len = 0; if (ISOFS_SB(inode->i_sb)->s_rock_offset != -1) { rs->len -= ISOFS_SB(inode->i_sb)->s_rock_offset; rs->chr += ISOFS_SB(inode->i_sb)->s_rock_offset; if (rs->len < 0) rs->len = 0; } } static void init_rock_state(struct rock_state *rs, struct inode *inode) { memset(rs, 0, sizeof(*rs)); rs->inode = inode; } /* * Returns 0 if the caller should continue scanning, 1 if the scan must end * and -ve on error. */ static int rock_continue(struct rock_state *rs) { int ret = 1; int blocksize = 1 << rs->inode->i_blkbits; const int min_de_size = offsetof(struct rock_ridge, u); kfree(rs->buffer); rs->buffer = NULL; if ((unsigned)rs->cont_offset > blocksize - min_de_size || (unsigned)rs->cont_size > blocksize || (unsigned)(rs->cont_offset + rs->cont_size) > blocksize) { printk(KERN_NOTICE "rock: corrupted directory entry. " "extent=%d, offset=%d, size=%d\n", rs->cont_extent, rs->cont_offset, rs->cont_size); ret = -EIO; goto out; } if (rs->cont_extent) { struct buffer_head *bh; rs->buffer = kmalloc(rs->cont_size, GFP_KERNEL); if (!rs->buffer) { ret = -ENOMEM; goto out; } ret = -EIO; bh = sb_bread(rs->inode->i_sb, rs->cont_extent); if (bh) { memcpy(rs->buffer, bh->b_data + rs->cont_offset, rs->cont_size); put_bh(bh); rs->chr = rs->buffer; rs->len = rs->cont_size; rs->cont_extent = 0; rs->cont_size = 0; rs->cont_offset = 0; return 0; } printk("Unable to read rock-ridge attributes\n"); } out: kfree(rs->buffer); rs->buffer = NULL; return ret; } /* * We think there's a record of type `sig' at rs->chr. Parse the signature * and make sure that there's really room for a record of that type. */ static int rock_check_overflow(struct rock_state *rs, int sig) { int len; switch (sig) { case SIG('S', 'P'): len = sizeof(struct SU_SP_s); break; case SIG('C', 'E'): len = sizeof(struct SU_CE_s); break; case SIG('E', 'R'): len = sizeof(struct SU_ER_s); break; case SIG('R', 'R'): len = sizeof(struct RR_RR_s); break; case SIG('P', 'X'): len = sizeof(struct RR_PX_s); break; case SIG('P', 'N'): len = sizeof(struct RR_PN_s); break; case SIG('S', 'L'): len = sizeof(struct RR_SL_s); break; case SIG('N', 'M'): len = sizeof(struct RR_NM_s); break; case SIG('C', 'L'): len = sizeof(struct RR_CL_s); break; case SIG('P', 'L'): len = sizeof(struct RR_PL_s); break; case SIG('T', 'F'): len = sizeof(struct RR_TF_s); break; case SIG('Z', 'F'): len = sizeof(struct RR_ZF_s); break; default: len = 0; break; } len += offsetof(struct rock_ridge, u); if (len > rs->len) { printk(KERN_NOTICE "rock: directory entry would overflow " "storage\n"); printk(KERN_NOTICE "rock: sig=0x%02x, size=%d, remaining=%d\n", sig, len, rs->len); return -EIO; } return 0; } /* * return length of name field; 0: not found, -1: to be ignored */ int get_rock_ridge_filename(struct iso_directory_record *de, char *retname, struct inode *inode) { struct rock_state rs; struct rock_ridge *rr; int sig; int retnamlen = 0; int truncate = 0; int ret = 0; if (!ISOFS_SB(inode->i_sb)->s_rock) return 0; *retname = 0; init_rock_state(&rs, inode); setup_rock_ridge(de, inode, &rs); repeat: while (rs.len > 2) { /* There may be one byte for padding somewhere */ rr = (struct rock_ridge *)rs.chr; /* * Ignore rock ridge info if rr->len is out of range, but * don't return -EIO because that would make the file * invisible. */ if (rr->len < 3) goto out; /* Something got screwed up here */ sig = isonum_721(rs.chr); if (rock_check_overflow(&rs, sig)) goto eio; rs.chr += rr->len; rs.len -= rr->len; /* * As above, just ignore the rock ridge info if rr->len * is bogus. */ if (rs.len < 0) goto out; /* Something got screwed up here */ switch (sig) { case SIG('R', 'R'): if ((rr->u.RR.flags[0] & RR_NM) == 0) goto out; break; case SIG('S', 'P'): if (check_sp(rr, inode)) goto out; break; case SIG('C', 'E'): rs.cont_extent = isonum_733(rr->u.CE.extent); rs.cont_offset = isonum_733(rr->u.CE.offset); rs.cont_size = isonum_733(rr->u.CE.size); break; case SIG('N', 'M'): if (truncate) break; if (rr->len < 5) break; /* * If the flags are 2 or 4, this indicates '.' or '..'. * We don't want to do anything with this, because it * screws up the code that calls us. We don't really * care anyways, since we can just use the non-RR * name. */ if (rr->u.NM.flags & 6) break; if (rr->u.NM.flags & ~1) { printk("Unsupported NM flag settings (%d)\n", rr->u.NM.flags); break; } if ((strlen(retname) + rr->len - 5) >= 254) { truncate = 1; break; } strncat(retname, rr->u.NM.name, rr->len - 5); retnamlen += rr->len - 5; break; case SIG('R', 'E'): kfree(rs.buffer); return -1; default: break; } } ret = rock_continue(&rs); if (ret == 0) goto repeat; if (ret == 1) return retnamlen; /* If 0, this file did not have a NM field */ out: kfree(rs.buffer); return ret; eio: ret = -EIO; goto out; } static int parse_rock_ridge_inode_internal(struct iso_directory_record *de, struct inode *inode, int regard_xa) { int symlink_len = 0; int cnt, sig; struct inode *reloc; struct rock_ridge *rr; int rootflag; struct rock_state rs; int ret = 0; if (!ISOFS_SB(inode->i_sb)->s_rock) return 0; init_rock_state(&rs, inode); setup_rock_ridge(de, inode, &rs); if (regard_xa) { rs.chr += 14; rs.len -= 14; if (rs.len < 0) rs.len = 0; } repeat: while (rs.len > 2) { /* There may be one byte for padding somewhere */ rr = (struct rock_ridge *)rs.chr; /* * Ignore rock ridge info if rr->len is out of range, but * don't return -EIO because that would make the file * invisible. */ if (rr->len < 3) goto out; /* Something got screwed up here */ sig = isonum_721(rs.chr); if (rock_check_overflow(&rs, sig)) goto eio; rs.chr += rr->len; rs.len -= rr->len; /* * As above, just ignore the rock ridge info if rr->len * is bogus. */ if (rs.len < 0) goto out; /* Something got screwed up here */ switch (sig) { #ifndef CONFIG_ZISOFS /* No flag for SF or ZF */ case SIG('R', 'R'): if ((rr->u.RR.flags[0] & (RR_PX | RR_TF | RR_SL | RR_CL)) == 0) goto out; break; #endif case SIG('S', 'P'): if (check_sp(rr, inode)) goto out; break; case SIG('C', 'E'): rs.cont_extent = isonum_733(rr->u.CE.extent); rs.cont_offset = isonum_733(rr->u.CE.offset); rs.cont_size = isonum_733(rr->u.CE.size); break; case SIG('E', 'R'): ISOFS_SB(inode->i_sb)->s_rock = 1; printk(KERN_DEBUG "ISO 9660 Extensions: "); { int p; for (p = 0; p < rr->u.ER.len_id; p++) printk("%c", rr->u.ER.data[p]); } printk("\n"); break; case SIG('P', 'X'): inode->i_mode = isonum_733(rr->u.PX.mode); set_nlink(inode, isonum_733(rr->u.PX.n_links)); i_uid_write(inode, isonum_733(rr->u.PX.uid)); i_gid_write(inode, isonum_733(rr->u.PX.gid)); break; case SIG('P', 'N'): { int high, low; high = isonum_733(rr->u.PN.dev_high); low = isonum_733(rr->u.PN.dev_low); /* * The Rock Ridge standard specifies that if * sizeof(dev_t) <= 4, then the high field is * unused, and the device number is completely * stored in the low field. Some writers may * ignore this subtlety, * and as a result we test to see if the entire * device number is * stored in the low field, and use that. */ if ((low & ~0xff) && high == 0) { inode->i_rdev = MKDEV(low >> 8, low & 0xff); } else { inode->i_rdev = MKDEV(high, low); } } break; case SIG('T', 'F'): /* * Some RRIP writers incorrectly place ctime in the * TF_CREATE field. Try to handle this correctly for * either case. */ /* Rock ridge never appears on a High Sierra disk */ cnt = 0; if (rr->u.TF.flags & TF_CREATE) { inode->i_ctime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_ctime.tv_nsec = 0; } if (rr->u.TF.flags & TF_MODIFY) { inode->i_mtime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_mtime.tv_nsec = 0; } if (rr->u.TF.flags & TF_ACCESS) { inode->i_atime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_atime.tv_nsec = 0; } if (rr->u.TF.flags & TF_ATTRIBUTES) { inode->i_ctime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_ctime.tv_nsec = 0; } break; case SIG('S', 'L'): { int slen; struct SL_component *slp; struct SL_component *oldslp; slen = rr->len - 5; slp = &rr->u.SL.link; inode->i_size = symlink_len; while (slen > 1) { rootflag = 0; switch (slp->flags & ~1) { case 0: inode->i_size += slp->len; break; case 2: inode->i_size += 1; break; case 4: inode->i_size += 2; break; case 8: rootflag = 1; inode->i_size += 1; break; default: printk("Symlink component flag " "not implemented\n"); } slen -= slp->len + 2; oldslp = slp; slp = (struct SL_component *) (((char *)slp) + slp->len + 2); if (slen < 2) { if (((rr->u.SL. flags & 1) != 0) && ((oldslp-> flags & 1) == 0)) inode->i_size += 1; break; } /* * If this component record isn't * continued, then append a '/'. */ if (!rootflag && (oldslp->flags & 1) == 0) inode->i_size += 1; } } symlink_len = inode->i_size; break; case SIG('R', 'E'): printk(KERN_WARNING "Attempt to read inode for " "relocated directory\n"); goto out; case SIG('C', 'L'): ISOFS_I(inode)->i_first_extent = isonum_733(rr->u.CL.location); reloc = isofs_iget(inode->i_sb, ISOFS_I(inode)->i_first_extent, 0); if (IS_ERR(reloc)) { ret = PTR_ERR(reloc); goto out; } inode->i_mode = reloc->i_mode; set_nlink(inode, reloc->i_nlink); inode->i_uid = reloc->i_uid; inode->i_gid = reloc->i_gid; inode->i_rdev = reloc->i_rdev; inode->i_size = reloc->i_size; inode->i_blocks = reloc->i_blocks; inode->i_atime = reloc->i_atime; inode->i_ctime = reloc->i_ctime; inode->i_mtime = reloc->i_mtime; iput(reloc); break; #ifdef CONFIG_ZISOFS case SIG('Z', 'F'): { int algo; if (ISOFS_SB(inode->i_sb)->s_nocompress) break; algo = isonum_721(rr->u.ZF.algorithm); if (algo == SIG('p', 'z')) { int block_shift = isonum_711(&rr->u.ZF.parms[1]); if (block_shift > 17) { printk(KERN_WARNING "isofs: " "Can't handle ZF block " "size of 2^%d\n", block_shift); } else { /* * Note: we don't change * i_blocks here */ ISOFS_I(inode)->i_file_format = isofs_file_compressed; /* * Parameters to compression * algorithm (header size, * block size) */ ISOFS_I(inode)->i_format_parm[0] = isonum_711(&rr->u.ZF.parms[0]); ISOFS_I(inode)->i_format_parm[1] = isonum_711(&rr->u.ZF.parms[1]); inode->i_size = isonum_733(rr->u.ZF. real_size); } } else { printk(KERN_WARNING "isofs: Unknown ZF compression " "algorithm: %c%c\n", rr->u.ZF.algorithm[0], rr->u.ZF.algorithm[1]); } break; } #endif default: break; } } ret = rock_continue(&rs); if (ret == 0) goto repeat; if (ret == 1) ret = 0; out: kfree(rs.buffer); return ret; eio: ret = -EIO; goto out; } static char *get_symlink_chunk(char *rpnt, struct rock_ridge *rr, char *plimit) { int slen; int rootflag; struct SL_component *oldslp; struct SL_component *slp; slen = rr->len - 5; slp = &rr->u.SL.link; while (slen > 1) { rootflag = 0; switch (slp->flags & ~1) { case 0: if (slp->len > plimit - rpnt) return NULL; memcpy(rpnt, slp->text, slp->len); rpnt += slp->len; break; case 2: if (rpnt >= plimit) return NULL; *rpnt++ = '.'; break; case 4: if (2 > plimit - rpnt) return NULL; *rpnt++ = '.'; *rpnt++ = '.'; break; case 8: if (rpnt >= plimit) return NULL; rootflag = 1; *rpnt++ = '/'; break; default: printk("Symlink component flag not implemented (%d)\n", slp->flags); } slen -= slp->len + 2; oldslp = slp; slp = (struct SL_component *)((char *)slp + slp->len + 2); if (slen < 2) { /* * If there is another SL record, and this component * record isn't continued, then add a slash. */ if ((!rootflag) && (rr->u.SL.flags & 1) && !(oldslp->flags & 1)) { if (rpnt >= plimit) return NULL; *rpnt++ = '/'; } break; } /* * If this component record isn't continued, then append a '/'. */ if (!rootflag && !(oldslp->flags & 1)) { if (rpnt >= plimit) return NULL; *rpnt++ = '/'; } } return rpnt; } int parse_rock_ridge_inode(struct iso_directory_record *de, struct inode *inode) { int result = parse_rock_ridge_inode_internal(de, inode, 0); /* * if rockridge flag was reset and we didn't look for attributes * behind eventual XA attributes, have a look there */ if ((ISOFS_SB(inode->i_sb)->s_rock_offset == -1) && (ISOFS_SB(inode->i_sb)->s_rock == 2)) { result = parse_rock_ridge_inode_internal(de, inode, 14); } return result; } /* * readpage() for symlinks: reads symlink contents into the page and either * makes it uptodate and returns 0 or returns error (-EIO) */ static int rock_ridge_symlink_readpage(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct iso_inode_info *ei = ISOFS_I(inode); struct isofs_sb_info *sbi = ISOFS_SB(inode->i_sb); char *link = kmap(page); unsigned long bufsize = ISOFS_BUFFER_SIZE(inode); struct buffer_head *bh; char *rpnt = link; unsigned char *pnt; struct iso_directory_record *raw_de; unsigned long block, offset; int sig; struct rock_ridge *rr; struct rock_state rs; int ret; if (!sbi->s_rock) goto error; init_rock_state(&rs, inode); block = ei->i_iget5_block; bh = sb_bread(inode->i_sb, block); if (!bh) goto out_noread; offset = ei->i_iget5_offset; pnt = (unsigned char *)bh->b_data + offset; raw_de = (struct iso_directory_record *)pnt; /* * If we go past the end of the buffer, there is some sort of error. */ if (offset + *pnt > bufsize) goto out_bad_span; /* * Now test for possible Rock Ridge extensions which will override * some of these numbers in the inode structure. */ setup_rock_ridge(raw_de, inode, &rs); repeat: while (rs.len > 2) { /* There may be one byte for padding somewhere */ rr = (struct rock_ridge *)rs.chr; if (rr->len < 3) goto out; /* Something got screwed up here */ sig = isonum_721(rs.chr); if (rock_check_overflow(&rs, sig)) goto out; rs.chr += rr->len; rs.len -= rr->len; if (rs.len < 0) goto out; /* corrupted isofs */ switch (sig) { case SIG('R', 'R'): if ((rr->u.RR.flags[0] & RR_SL) == 0) goto out; break; case SIG('S', 'P'): if (check_sp(rr, inode)) goto out; break; case SIG('S', 'L'): rpnt = get_symlink_chunk(rpnt, rr, link + (PAGE_SIZE - 1)); if (rpnt == NULL) goto out; break; case SIG('C', 'E'): /* This tells is if there is a continuation record */ rs.cont_extent = isonum_733(rr->u.CE.extent); rs.cont_offset = isonum_733(rr->u.CE.offset); rs.cont_size = isonum_733(rr->u.CE.size); default: break; } } ret = rock_continue(&rs); if (ret == 0) goto repeat; if (ret < 0) goto fail; if (rpnt == link) goto fail; brelse(bh); *rpnt = '\0'; SetPageUptodate(page); kunmap(page); unlock_page(page); return 0; /* error exit from macro */ out: kfree(rs.buffer); goto fail; out_noread: printk("unable to read i-node block"); goto fail; out_bad_span: printk("symlink spans iso9660 blocks\n"); fail: brelse(bh); error: SetPageError(page); kunmap(page); unlock_page(page); return -EIO; } const struct address_space_operations isofs_symlink_aops = { .readpage = rock_ridge_symlink_readpage };
./CrossVul/dataset_final_sorted/CWE-399/c/bad_2262_2
crossvul-cpp_data_bad_3431_3
/* * 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/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 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); #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 MonoObject *mono_get_object_from_blob (MonoDomain *domain, MonoType *type, const char *blob); 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_method_builder (MonoClass *class); static gboolean is_sre_ctor_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 (MonoReflectionGenericClass *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 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: if (val->vtable->klass->enumtype) { *ret_type = mono_class_enum_basetype (val->vtable->klass)->type; goto handle_enum; } else g_error ("we can't encode valuetypes"); 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); 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 */ 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; } } 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 = klass->reflection_info; token = MONO_TYPEDEFORREF_TYPEDEF | (tb->table_idx << MONO_TYPEDEFORREF_BITS); mono_g_hash_table_insert (assembly->tokens, GUINT_TO_POINTER (token), klass->reflection_info); 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), klass->reflection_info); 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 /* * 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) { MonoDynamicTable *table; guint32 *values; guint32 token, pclass; guint32 parent; parent = mono_image_typedef_or_ref (assembly, type); 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; } 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; ReflectionMethodBuilder rmb; char *name; 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; token = mono_image_get_memberref_token (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)rmb.type), name, method_builder_encode_signature (assembly, &rmb)); 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 (g_hash_table_lookup (assembly->handleref, mb)); if (token) return token; token = mono_image_get_methodref_token_for_methodbuilder (assembly, mb); g_hash_table_insert (assembly->handleref, mb, GUINT_TO_POINTER(token)); return token; } static guint32 mono_image_get_ctorbuilder_token (MonoDynamicImage *assembly, MonoReflectionCtorBuilder *mb) { guint32 token; ReflectionMethodBuilder rmb; char *name; token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, mb)); if (token) return token; reflection_methodbuilder_from_ctor_builder (&rmb, mb); name = mono_string_to_utf8 (rmb.name); token = mono_image_get_memberref_token (assembly, mono_reflection_type_get_handle ((MonoReflectionType*)rmb.type), name, method_builder_encode_signature (assembly, &rmb)); g_free (name); g_hash_table_insert (assembly->handleref, 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) { MonoDynamicGenericClass *dgclass; int field_index; g_assert (is_field_on_inst (field)); dgclass = (MonoDynamicGenericClass*)field->parent->generic_class; field_index = field - dgclass->fields; g_assert (field_index >= 0 && field_index < dgclass->count_fields); return dgclass->field_generic_types [field_index]; } #ifndef DISABLE_REFLECTION_EMIT static guint32 mono_image_get_fieldref_token (MonoDynamicImage *assembly, MonoReflectionField *f) { MonoType *type; guint32 token; MonoClassField *field; token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, f)); if (token) return token; g_assert (f->field->parent); field = f->field; 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 (f->field)) type = get_field_on_inst_generic_type (f->field); else type = f->field->type; } token = mono_image_get_memberref_token (assembly, &f->field->parent->byval_arg, mono_field_get_name (f->field), fieldref_encode_signature (assembly, field->parent->image, type)); g_hash_table_insert (assembly->handleref, 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; MonoReflectionFieldBuilder *fb = f->fb; MonoType *type; char *name; token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, f)); if (token) return token; 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); g_hash_table_insert (assembly->handleref, 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; MonoDynamicGenericClass *dgclass; MonoReflectionCtorBuilder *cb = c->cb; ReflectionMethodBuilder rmb; MonoType *type; char *name; /* A ctor cannot be a generic method, so we can ignore create_methodspec */ token = GPOINTER_TO_UINT (g_hash_table_lookup (assembly->handleref, c)); if (token) return token; 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); g_hash_table_insert (assembly->handleref, 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; MonoClass *klass; MonoGenericClass *gclass; MonoReflectionMethodBuilder *mb = m->mb; ReflectionMethodBuilder rmb; MonoType *type; char *name; 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 (g_hash_table_lookup (assembly->handleref, m)); if (token) return token; 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); g_hash_table_insert (assembly->handleref, 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 (g_hash_table_lookup (assembly->handleref, 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 ++; g_hash_table_insert (assembly->handleref, 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 (GPtrArray *types, MonoReflectionTypeBuilder *type) { int i; g_ptr_array_add (types, type); /* FIXME: GC object added to unmanaged memory */ 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 guint32 add_exported_type (MonoReflectionAssemblyBuilder *assemblyb, MonoDynamicImage *assembly, MonoClass *klass) { MonoDynamicTable *table; guint32 *values; guint32 scope, idx, res, impl; gboolean forwarder = TRUE; if (klass->nested_in) { impl = add_exported_type (assemblyb, assembly, klass->nested_in); forwarder = FALSE; } else { scope = resolution_scope_from_image (assembly, klass->image); g_assert ((scope & MONO_RESOLTION_SCOPE_MASK) == MONO_RESOLTION_SCOPE_ASSEMBLYREF); idx = scope >> MONO_RESOLTION_SCOPE_BITS; impl = (idx << MONO_IMPLEMENTATION_BITS) + MONO_IMPLEMENTATION_ASSEMBLYREF; } 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] = 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); res = (table->next_idx << MONO_IMPLEMENTATION_BITS) + MONO_IMPLEMENTATION_EXP_TYPE; table->next_idx++; return res; } 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); } } #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; if (mono_framework_version () > 1) { *p++ = 2; /* version */ *p++ = 0; } else { *p++ = 1; /* 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; GPtrArray *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 */ types = g_ptr_array_new (); if (moduleb->types) for (i = 0; i < moduleb->num_types; ++i) { MonoReflectionTypeBuilder *type = mono_array_get (moduleb->types, MonoReflectionTypeBuilder*, i); collect_types (types, type); } g_ptr_array_sort (types, (GCompareFunc)compare_types_by_table_idx); table = &assembly->tables [MONO_TABLE_TYPEDEF]; table->rows += types->len; 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 < types->len; ++i) { MonoReflectionTypeBuilder *tb = g_ptr_array_index (types, i); string_heap_insert_mstring (&assembly->sheap, tb->nspace); } for (i = 0; i < types->len; ++i) { MonoReflectionTypeBuilder *tb = g_ptr_array_index (types, i); string_heap_insert_mstring (&assembly->sheap, tb->name); } for (i = 0; i < types->len; ++i) { MonoReflectionTypeBuilder *type = g_ptr_array_index (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 < types->len; ++i) { MonoReflectionTypeBuilder *type = g_ptr_array_index (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); } } } g_ptr_array_free (types, TRUE); 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; klass = obj->vtable->klass; if (strcmp (klass->name, "MonoMethod") == 0) { MonoMethod *method = ((MonoReflectionMethod *)obj)->method; MonoMethodSignature *sig, *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; char *name; reflection_methodbuilder_from_method_builder (&rmb, mb); rmb.opt_types = opt_param_types; sig = 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); g_free (name); } else { g_error ("requested method token for %s\n", klass->name); } 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 { token = fb->table_idx | MONO_TOKEN_FIELD_DEF; } } 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); 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, f); } /*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 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->handleref = g_hash_table_new (NULL, NULL); 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->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); } 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); 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 = 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); if (mono_framework_version () > 1) cli_header->ch_runtime_minor = GUINT16_FROM_LE (5); else cli_header->ch_runtime_minor = GUINT16_FROM_LE (0); 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 *System_Reflection_Assembly; MonoReflectionAssembly *res; CHECK_OBJECT (MonoReflectionAssembly *, assembly, NULL); if (!System_Reflection_Assembly) System_Reflection_Assembly = mono_class_from_name ( mono_defaults.corlib, "System.Reflection", "Assembly"); res = (MonoReflectionAssembly *)mono_object_new (domain, System_Reflection_Assembly); res->assembly = assembly; CACHE_OBJECT (MonoReflectionAssembly *, assembly, res, NULL); } MonoReflectionModule* mono_module_get_object (MonoDomain *domain, MonoImage *image) { static MonoClass *System_Reflection_Module; MonoReflectionModule *res; char* basename; CHECK_OBJECT (MonoReflectionModule *, image, NULL); if (!System_Reflection_Module) System_Reflection_Module = mono_class_from_name ( mono_defaults.corlib, "System.Reflection", "Module"); res = (MonoReflectionModule *)mono_object_new (domain, System_Reflection_Module); 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 *System_Reflection_Module; MonoReflectionModule *res; MonoTableInfo *table; guint32 cols [MONO_FILE_SIZE]; const char *name; guint32 i, name_idx; const char *val; if (!System_Reflection_Module) System_Reflection_Module = mono_class_from_name ( mono_defaults.corlib, "System.Reflection", "Module"); res = (MonoReflectionModule *)mono_object_new (domain, System_Reflection_Module); 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) ^ g_str_hash (t1->data.klass->name); 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; } } return hash; } static MonoReflectionGenericClass* mono_generic_class_get_object (MonoDomain *domain, MonoType *geninst) { static MonoClass *System_Reflection_MonoGenericClass; MonoReflectionGenericClass *res; MonoClass *klass, *gklass; MonoGenericInst *ginst; MonoArray *type_args; int i; if (!System_Reflection_MonoGenericClass) { System_Reflection_MonoGenericClass = mono_class_from_name ( mono_defaults.corlib, "System.Reflection", "MonoGenericClass"); g_assert (System_Reflection_MonoGenericClass); } klass = mono_class_from_mono_type (geninst); gklass = klass->generic_class->container_class; mono_class_init (klass); #ifdef HAVE_SGEN_GC res = (MonoReflectionGenericClass *) mono_gc_alloc_pinned_obj (mono_class_vtable (domain, System_Reflection_MonoGenericClass), mono_class_instance_size (System_Reflection_MonoGenericClass)); #else res = (MonoReflectionGenericClass *) mono_object_new (domain, System_Reflection_MonoGenericClass); #endif res->type.type = geninst; g_assert (gklass->reflection_info); g_assert (!strcmp (((MonoObject*)gklass->reflection_info)->vtable->klass->name, "TypeBuilder")); MONO_OBJECT_SETREF (res, generic_type, gklass->reflection_info); ginst = klass->generic_class->context.class_inst; type_args = mono_array_new (domain, mono_defaults.systemtype_class, ginst->type_argc); for (i = 0; i < ginst->type_argc; ++i) mono_array_setref (type_args, i, mono_type_get_object (domain, ginst->type_argv [i])); MONO_OBJECT_SETREF (res, type_arguments, type_args); return res; } 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; } /* * 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) { 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; } /* Create a MonoGenericClass object for instantiations of not finished TypeBuilders */ if ((type->type == MONO_TYPE_GENERICINST) && type->data.generic_class->is_dynamic && !type->data.generic_class->container_class->wastypebuilder) { res = (MonoReflectionType *)mono_generic_class_get_object (domain, type); mono_g_hash_table_insert (domain->type_hash, type, res); mono_domain_unlock (domain); mono_loader_unlock (); return res; } 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 (klass->reflection_info && !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 klass->reflection_info; } } // FIXME: Get rid of this, do it in the icalls for Type mono_class_init (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; else res->attrs = field->type->attrs; MONO_OBJECT_SETREF (res, type, mono_type_get_object (domain, field->type)); 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; MonoMethodNormal *mn; MonoMethodHeader *header; MonoImage *image; guint32 method_rva, local_var_sig_token; char *ptr; unsigned char format, flags; int i; /* for compatibility with .net */ if (method->dynamic) mono_raise_exception (mono_get_exception_invalid_operation (NULL)); 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; mn = (MonoMethodNormal *)method; 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); } 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; } static 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; mono_class_init (klass); 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); } mono_class_init (klass); } 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); token = mono_class_from_mono_type (type)->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) { MonoReflectionModule *m = (MonoReflectionModule*)obj; token = m->token; } else if (strcmp (klass->name, "Assembly") == 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 { 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); 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 (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; 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; } static MonoObject* create_custom_attr_data (MonoImage *image, MonoMethod *method, const guchar *data, guint32 len) { MonoArray *typedargs, *namedargs; static MonoMethod *ctor; MonoDomain *domain; MonoObject *attr; void *params [3]; CattrNamedArg *arginfo; int i; mono_class_init (method->klass); if (!ctor) ctor = mono_class_get_method_from_name (mono_defaults.customattribute_data_class, ".ctor", 3); domain = mono_domain_get (); if (len == 0) { /* This is for Attributes with no parameters */ attr = mono_object_new (domain, mono_defaults.customattribute_data_class); params [0] = mono_method_get_object (domain, method, NULL); params [1] = params [2] = NULL; mono_runtime_invoke (method, attr, params, NULL); return attr; } mono_reflection_create_custom_attr_data_args (image, method, data, len, &typedargs, &namedargs, &arginfo); if (!typedargs || !namedargs) return NULL; 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); } attr = mono_object_new (domain, mono_defaults.customattribute_data_class); params [0] = mono_method_get_object (domain, method, NULL); params [1] = typedargs; params [2] = namedargs; 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].ctor, cinfo->attrs [i].data, cinfo->attrs [i].data_size); 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; } 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); 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); cinfo = mono_custom_attrs_from_class (klass); } else if (strcmp ("Assembly", klass->name) == 0) { MonoReflectionAssembly *rassembly = (MonoReflectionAssembly*)obj; cinfo = mono_custom_attrs_from_assembly (rassembly->assembly); } else if (strcmp ("Module", 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); } 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); } 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) { MonoMethod *method_get_underlying_system_type; method_get_underlying_system_type = mono_object_get_virtual_method ((MonoObject *) t, mono_class_get_method_from_name (mono_object_class (t), "get_UnderlyingSystemType", 0)); return (MonoReflectionType *) mono_runtime_invoke (method_get_underlying_system_type, t, NULL, NULL); } #ifndef DISABLE_REFLECTION_EMIT static gboolean is_corlib_type (MonoClass *class) { return class->image == mono_defaults.corlib; } static gboolean is_usertype (MonoReflectionType *ref) { MonoClass *class = mono_object_class (ref); return class->image != mono_defaults.corlib || strcmp ("TypeDelegator", class->name) == 0; } #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) \ 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_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_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"); } static gboolean is_sr_mono_property (MonoClass *class) { check_corlib_type_cached (class, "System.Reflection", "MonoProperty"); } 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"); } 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); } 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); g_assert (!is_usertype (ref)); /*FIXME fail better*/ 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); } res = mono_reflection_bind_generic_parameters ((MonoReflectionType*)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; } 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; } void mono_reflection_create_unmanaged_type (MonoReflectionType *type) { mono_reflection_type_get_handle (type); } /** * 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; } } #endif /* !DISABLE_REFLECTION_EMIT */ /* * 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; MOVING_GC_REGISTER (&klass->reflection_info); klass->reflection_info = tb; /* Put into cache so mono_class_get () will find it */ mono_image_add_to_name_cache (klass->image, klass->name_space, klass->name, tb->table_idx); 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; MonoMethodNormal *pm; 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 if (rmb->refs) m = (MonoMethod *)image_g_new0 (image, MonoMethodWrapper, 1); else m = (MonoMethod *)image_g_new0 (image, MonoMethodNormal, 1); pm = (MonoMethodNormal*)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->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); } pm->header = header; } if (rmb->generic_params) { int count = mono_array_length (rmb->generic_params); MonoGenericContainer *container; container = rmb->generic_container; if (container) { m->is_generic = TRUE; mono_method_set_generic_container (m, container); } container->type_argc = count; container->type_params = image_g_new0 (image, MonoGenericParamFull, count); container->owner.method = m; 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; } 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 (!strcmp (((MonoObject *) type)->vtable->klass->name, "TypeBuilder")) { tb = (MonoReflectionTypeBuilder *) type; is_dynamic = TRUE; } else if (!strcmp (((MonoObject *) type)->vtable->klass->name, "MonoGenericClass")) { MonoReflectionGenericClass *rgi = (MonoReflectionGenericClass *) type; tb = rgi->generic_type; 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 *) klass->reflection_info; 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; 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; 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 (); } if (!mono_verifier_is_method_valid_generic_instantiation (inflated)) mono_raise_exception (mono_get_exception_argument ("typeArguments", "Invalid generic arguments")); 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) { /* 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 (MonoReflectionGenericClass *type, MonoObject *obj) { MonoMethod *method; MonoClass *gklass; gklass = mono_class_from_mono_type (mono_reflection_type_get_handle ((MonoReflectionType*)type->generic_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; g_assert (gclass->is_dynamic); 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->count_properties = properties ? mono_array_length (properties) : 0; dgclass->count_events = events ? mono_array_length (events) : 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->properties = g_new0 (MonoProperty, dgclass->count_properties); dgclass->events = g_new0 (MonoEvent, dgclass->count_events); 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 (type, obj); } for (i = 0; i < dgclass->count_ctors; i++) { MonoObject *obj = mono_array_get (ctors, gpointer, i); dgclass->ctors [i] = inflate_method (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); } } for (i = 0; i < dgclass->count_properties; i++) { MonoObject *obj = mono_array_get (properties, gpointer, i); MonoProperty *property = &dgclass->properties [i]; if (!strcmp (obj->vtable->klass->name, "PropertyBuilder")) { MonoReflectionPropertyBuilder *pb = (MonoReflectionPropertyBuilder *) obj; property->parent = klass; property->attrs = pb->attrs; property->name = mono_string_to_utf8 (pb->name); if (pb->get_method) property->get = inflate_method (type, (MonoObject *) pb->get_method); if (pb->set_method) property->set = inflate_method (type, (MonoObject *) pb->set_method); } else if (!strcmp (obj->vtable->klass->name, "MonoProperty")) { *property = *((MonoReflectionProperty *) obj)->property; property->name = g_strdup (property->name); if (property->get) property->get = inflate_mono_method (klass, property->get, NULL); if (property->set) property->set = inflate_mono_method (klass, property->set, NULL); } else g_assert_not_reached (); } for (i = 0; i < dgclass->count_events; i++) { MonoObject *obj = mono_array_get (events, gpointer, i); MonoEvent *event = &dgclass->events [i]; if (!strcmp (obj->vtable->klass->name, "EventBuilder")) { MonoReflectionEventBuilder *eb = (MonoReflectionEventBuilder *) obj; event->parent = klass; event->attrs = eb->attrs; event->name = mono_string_to_utf8 (eb->name); if (eb->add_method) event->add = inflate_method (type, (MonoObject *) eb->add_method); if (eb->remove_method) event->remove = inflate_method (type, (MonoObject *) eb->remove_method); } else if (!strcmp (obj->vtable->klass->name, "MonoEvent")) { *event = *((MonoReflectionMonoEvent *) obj)->event; event->name = g_strdup (event->name); if (event->add) event->add = inflate_mono_method (klass, event->add, NULL); if (event->remove) event->remove = inflate_mono_method (klass, event->remove, NULL); } else g_assert_not_reached (); } dgclass->initialized = TRUE; } static void ensure_generic_class_runtime_vtable (MonoClass *klass) { MonoClass *gklass = klass->generic_class->container_class; int i; if (klass->wastypebuilder) return; ensure_runtime_vtable (gklass); 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)); } klass->interface_count = gklass->interface_count; klass->interfaces = mono_image_alloc (klass->image, sizeof (MonoClass*) * klass->interface_count); for (i = 0; i < klass->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; /*We can only finish with this klass once it's parent has as well*/ if (gklass->wastypebuilder) klass->wastypebuilder = TRUE; return; } static void ensure_runtime_vtable (MonoClass *klass) { MonoReflectionTypeBuilder *tb = klass->reflection_info; 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; 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 (!klass->reflection_info) return; g_assert (strcmp (((MonoObject*)klass->reflection_info)->vtable->klass->name, "TypeBuilder") == 0); tb = (MonoReflectionTypeBuilder*)klass->reflection_info; 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 = klass->reflection_info; 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 (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 = klass->reflection_info; 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); } } MonoReflectionEvent * mono_reflection_event_builder_get_event_info (MonoReflectionTypeBuilder *tb, MonoReflectionEventBuilder *eb) { MonoEvent *event = g_new0 (MonoEvent, 1); MonoClass *klass; int j; 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; if (eb->other_methods) { 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; } } return mono_event_get_object (mono_object_domain (tb), klass, event); } static void typebuilder_setup_events (MonoClass *klass, MonoError *error) { MonoReflectionTypeBuilder *tb = klass->reflection_info; MonoReflectionEventBuilder *eb; MonoImage *image = klass->image; MonoEvent *events; int i, j; 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; if (eb->other_methods) { 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; } } mono_save_custom_attrs (klass->image, &events [i], eb->cattrs); } } static gboolean remove_instantiations_of (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)) 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; #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. */ if (domain->type_hash && klass->generic_container) mono_g_hash_table_foreach_remove (domain->type_hash, remove_instantiations_of, 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; MOVING_GC_REGISTER (&pklass->reflection_info); pklass->reflection_info = gparam; /* FIXME: GC pin 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; } #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) { MonoReflectionTypeBuilder *tb = klass->reflection_info; 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); 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; type = mono_class_inflate_generic_type (mono_reflection_type_get_handle ((MonoReflectionType*)f->inst), context); inflated = mono_class_from_mono_type (type); g_assert (f->fb->handle); result = mono_class_get_field_from_name (inflated, mono_field_get_name (f->fb->handle)); 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); g_assert (c->cb->mhandle); result = inflate_mono_method (inflated_klass, c->cb->mhandle, (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); } 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); g_assert (m->mb->mhandle); result = inflate_mono_method (inflated_klass, m->mb->mhandle, (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 klass->reflection_info. */ g_assert (klass->reflection_info); g_assert (!strcmp (((MonoObject*)(klass->reflection_info))->vtable->klass->name, "TypeBuilder")); params [0] = mono_type_get_object (mono_domain_get (), &oklass->byval_arg); res = mono_runtime_invoke (method, (MonoObject*)(klass->reflection_info), params, &exc); if (exc) return FALSE; else return *(MonoBoolean*)mono_object_unbox (res); }
./CrossVul/dataset_final_sorted/CWE-399/c/bad_3431_3
crossvul-cpp_data_bad_931_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % AAA N N N N OOO TTTTT AAA TTTTT EEEEE % % A A NN N NN N O O T A A T E % % AAAAA N N N N N N O O T AAAAA T EEE % % A A N NN N NN O O T A A T E % % A A N N N N OOO T A A T EEEEE % % % % % % MagickCore Image Annotation Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 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://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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Digital Applications (www.digapp.com) contributed the stroked text algorithm. % It was written by Leonard Rosenthol. % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/annotate.h" #include "MagickCore/annotate-private.h" #include "MagickCore/attribute.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/client.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/constitute.h" #include "MagickCore/draw.h" #include "MagickCore/draw-private.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image-private.h" #include "MagickCore/log.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/token.h" #include "MagickCore/token-private.h" #include "MagickCore/transform.h" #include "MagickCore/transform-private.h" #include "MagickCore/type.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/xwindow.h" #include "MagickCore/xwindow-private.h" #if defined(MAGICKCORE_FREETYPE_DELEGATE) #if defined(__MINGW32__) # undef interface #endif #include <ft2build.h> #if defined(FT_FREETYPE_H) # include FT_FREETYPE_H #else # include <freetype/freetype.h> #endif #if defined(FT_GLYPH_H) # include FT_GLYPH_H #else # include <freetype/ftglyph.h> #endif #if defined(FT_OUTLINE_H) # include FT_OUTLINE_H #else # include <freetype/ftoutln.h> #endif #if defined(FT_BBOX_H) # include FT_BBOX_H #else # include <freetype/ftbbox.h> #endif /* defined(FT_BBOX_H) */ #endif #if defined(MAGICKCORE_RAQM_DELEGATE) #include <raqm.h> #endif typedef struct _GraphemeInfo { size_t index, x_offset, x_advance, y_offset; size_t cluster; } GraphemeInfo; /* Annotate semaphores. */ static SemaphoreInfo *annotate_semaphore = (SemaphoreInfo *) NULL; /* Forward declarations. */ static MagickBooleanType RenderType(Image *,const DrawInfo *,const PointInfo *,TypeMetric *, ExceptionInfo *), RenderPostscript(Image *,const DrawInfo *,const PointInfo *,TypeMetric *, ExceptionInfo *), RenderFreetype(Image *,const DrawInfo *,const char *,const PointInfo *, TypeMetric *,ExceptionInfo *), RenderX11(Image *,const DrawInfo *,const PointInfo *,TypeMetric *, ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A n n o t a t e C o m p o n e n t G e n e s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AnnotateComponentGenesis() instantiates the annotate component. % % The format of the AnnotateComponentGenesis method is: % % MagickBooleanType AnnotateComponentGenesis(void) % */ MagickPrivate MagickBooleanType AnnotateComponentGenesis(void) { if (annotate_semaphore == (SemaphoreInfo *) NULL) annotate_semaphore=AcquireSemaphoreInfo(); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A n n o t a t e C o m p o n e n t T e r m i n u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AnnotateComponentTerminus() destroys the annotate component. % % The format of the AnnotateComponentTerminus method is: % % AnnotateComponentTerminus(void) % */ MagickPrivate void AnnotateComponentTerminus(void) { if (annotate_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&annotate_semaphore); RelinquishSemaphoreInfo(&annotate_semaphore); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A n n o t a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AnnotateImage() annotates an image with text. % % The format of the AnnotateImage method is: % % MagickBooleanType AnnotateImage(Image *image,DrawInfo *draw_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType AnnotateImage(Image *image, const DrawInfo *draw_info,ExceptionInfo *exception) { char *p, primitive[MagickPathExtent], *text, **textlist; DrawInfo *annotate, *annotate_info; GeometryInfo geometry_info; MagickBooleanType status; PointInfo offset; RectangleInfo geometry; register ssize_t i; TypeMetric metrics; size_t height, number_lines; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->signature == MagickCoreSignature); if (draw_info->text == (char *) NULL) return(MagickFalse); if (*draw_info->text == '\0') return(MagickTrue); annotate=CloneDrawInfo((ImageInfo *) NULL,draw_info); text=annotate->text; annotate->text=(char *) NULL; annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); number_lines=1; for (p=text; *p != '\0'; p++) if (*p == '\n') number_lines++; textlist=AcquireQuantumMemory(number_lines+1,sizeof(*textlist)); if (textlist == (char **) NULL) return(MagickFalse); p=text; for (i=0; i < number_lines; i++) { char *q; textlist[i]=p; for (q=p; *q != '\0'; q++) if ((*q == '\r') || (*q == '\n')) break; if (*q == '\r') { *q='\0'; q++; } *q='\0'; p=q+1; } textlist[i]=(char *) NULL; SetGeometry(image,&geometry); SetGeometryInfo(&geometry_info); if (annotate_info->geometry != (char *) NULL) { (void) ParsePageGeometry(image,annotate_info->geometry,&geometry, exception); (void) ParseGeometry(annotate_info->geometry,&geometry_info); } if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); status=MagickTrue; (void) memset(&metrics,0,sizeof(metrics)); for (i=0; textlist[i] != (char *) NULL; i++) { if (*textlist[i] == '\0') continue; /* Position text relative to image. */ annotate_info->affine.tx=geometry_info.xi-image->page.x; annotate_info->affine.ty=geometry_info.psi-image->page.y; (void) CloneString(&annotate->text,textlist[i]); if ((metrics.width == 0) || (annotate->gravity != NorthWestGravity)) (void) GetTypeMetrics(image,annotate,&metrics,exception); height=(ssize_t) (metrics.ascent-metrics.descent+ draw_info->interline_spacing+0.5); switch (annotate->gravity) { case UndefinedGravity: default: { offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height; offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height; break; } case NorthWestGravity: { offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i* annotate_info->affine.ry*height+annotate_info->affine.ry* (metrics.ascent+metrics.descent); offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i* annotate_info->affine.sy*height+annotate_info->affine.sy* metrics.ascent; break; } case NorthGravity: { offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+ geometry.width/2.0+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry* (metrics.ascent+metrics.descent); offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i* annotate_info->affine.sy*height+annotate_info->affine.sy* metrics.ascent-annotate_info->affine.rx*metrics.width/2.0; break; } case NorthEastGravity: { offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+ geometry.width+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width+annotate_info->affine.ry* (metrics.ascent+metrics.descent)-1.0; offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i* annotate_info->affine.sy*height+annotate_info->affine.sy* metrics.ascent-annotate_info->affine.rx*metrics.width; break; } case WestGravity: { offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i* annotate_info->affine.ry*height+annotate_info->affine.ry* (metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0; offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+ geometry.height/2.0+i*annotate_info->affine.sy*height+ annotate_info->affine.sy*(metrics.ascent+metrics.descent- (number_lines-1.0)*height)/2.0; break; } case CenterGravity: { offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+ geometry.width/2.0+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry* (metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0; offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+ geometry.height/2.0+i*annotate_info->affine.sy*height- annotate_info->affine.rx*metrics.width/2.0+annotate_info->affine.sy* (metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0; break; } case EastGravity: { offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+ geometry.width+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width+ annotate_info->affine.ry*(metrics.ascent+metrics.descent- (number_lines-1.0)*height)/2.0-1.0; offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+ geometry.height/2.0+i*annotate_info->affine.sy*height- annotate_info->affine.rx*metrics.width+ annotate_info->affine.sy*(metrics.ascent+metrics.descent- (number_lines-1.0)*height)/2.0; break; } case SouthWestGravity: { offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i* annotate_info->affine.ry*height-annotate_info->affine.ry* (number_lines-1.0)*height; offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+ geometry.height+i*annotate_info->affine.sy*height- annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent; break; } case SouthGravity: { offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+ geometry.width/2.0+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width/2.0- annotate_info->affine.ry*(number_lines-1.0)*height/2.0; offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+ geometry.height+i*annotate_info->affine.sy*height- annotate_info->affine.rx*metrics.width/2.0- annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent; break; } case SouthEastGravity: { offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+ geometry.width+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width- annotate_info->affine.ry*(number_lines-1.0)*height-1.0; offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+ geometry.height+i*annotate_info->affine.sy*height- annotate_info->affine.rx*metrics.width- annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent; break; } } switch (annotate->align) { case LeftAlign: { offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height; offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height; break; } case CenterAlign: { offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width/2.0; offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height- annotate_info->affine.rx*metrics.width/2.0; break; } case RightAlign: { offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height- annotate_info->affine.sx*metrics.width; offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height- annotate_info->affine.rx*metrics.width; break; } default: break; } if (draw_info->undercolor.alpha != TransparentAlpha) { DrawInfo *undercolor_info; /* Text box. */ undercolor_info=CloneDrawInfo((ImageInfo *) NULL,(DrawInfo *) NULL); undercolor_info->fill=draw_info->undercolor; undercolor_info->affine=draw_info->affine; undercolor_info->affine.tx=offset.x-draw_info->affine.ry*metrics.ascent; undercolor_info->affine.ty=offset.y-draw_info->affine.sy*metrics.ascent; (void) FormatLocaleString(primitive,MagickPathExtent, "rectangle 0.0,0.0 %g,%g",metrics.origin.x,(double) height); (void) CloneString(&undercolor_info->primitive,primitive); (void) DrawImage(image,undercolor_info,exception); (void) DestroyDrawInfo(undercolor_info); } annotate_info->affine.tx=offset.x; annotate_info->affine.ty=offset.y; (void) FormatLocaleString(primitive,MagickPathExtent,"stroke-width %g " "line 0,0 %g,0",metrics.underline_thickness,metrics.width); if (annotate->decorate == OverlineDecoration) { annotate_info->affine.ty-=(draw_info->affine.sy*(metrics.ascent+ metrics.descent-metrics.underline_position)); (void) CloneString(&annotate_info->primitive,primitive); (void) DrawImage(image,annotate_info,exception); } else if (annotate->decorate == UnderlineDecoration) { annotate_info->affine.ty-=(draw_info->affine.sy* metrics.underline_position); (void) CloneString(&annotate_info->primitive,primitive); (void) DrawImage(image,annotate_info,exception); } /* Annotate image with text. */ status=RenderType(image,annotate,&offset,&metrics,exception); if (status == MagickFalse) break; if (annotate->decorate == LineThroughDecoration) { annotate_info->affine.ty-=(draw_info->affine.sy*(height+ metrics.underline_position+metrics.descent)/2.0); (void) CloneString(&annotate_info->primitive,primitive); (void) DrawImage(image,annotate_info,exception); } } /* Relinquish resources. */ annotate_info=DestroyDrawInfo(annotate_info); annotate=DestroyDrawInfo(annotate); textlist=(char **) RelinquishMagickMemory(textlist); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r m a t M a g i c k C a p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FormatMagickCaption() formats a caption so that it fits within the image % width. It returns the number of lines in the formatted caption. % % The format of the FormatMagickCaption method is: % % ssize_t FormatMagickCaption(Image *image,DrawInfo *draw_info, % const MagickBooleanType split,TypeMetric *metrics,char **caption, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image: The image. % % o draw_info: the draw info. % % o split: when no convenient line breaks-- insert newline. % % o metrics: Return the font metrics in this structure. % % o caption: the caption. % % o exception: return any errors or warnings in this structure. % */ MagickExport ssize_t FormatMagickCaption(Image *image,DrawInfo *draw_info, const MagickBooleanType split,TypeMetric *metrics,char **caption, ExceptionInfo *exception) { MagickBooleanType status; register char *p, *q, *s; register ssize_t i; size_t width; ssize_t n; q=draw_info->text; s=(char *) NULL; for (p=(*caption); GetUTFCode(p) != 0; p+=GetUTFOctets(p)) { if (IsUTFSpace(GetUTFCode(p)) != MagickFalse) s=p; if (GetUTFCode(p) == '\n') { q=draw_info->text; continue; } for (i=0; i < (ssize_t) GetUTFOctets(p); i++) *q++=(*(p+i)); *q='\0'; status=GetTypeMetrics(image,draw_info,metrics,exception); if (status == MagickFalse) break; width=(size_t) floor(metrics->width+draw_info->stroke_width+0.5); if (width <= image->columns) continue; if (s != (char *) NULL) { *s='\n'; p=s; } else if (split != MagickFalse) { /* No convenient line breaks-- insert newline. */ n=p-(*caption); if ((n > 0) && ((*caption)[n-1] != '\n')) { char *target; target=AcquireString(*caption); CopyMagickString(target,*caption,n+1); ConcatenateMagickString(target,"\n",strlen(*caption)+1); ConcatenateMagickString(target,p,strlen(*caption)+2); (void) DestroyString(*caption); *caption=target; p=(*caption)+n; } } q=draw_info->text; s=(char *) NULL; } n=0; for (p=(*caption); GetUTFCode(p) != 0; p+=GetUTFOctets(p)) if (GetUTFCode(p) == '\n') n++; return(n); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t M u l t i l i n e T y p e M e t r i c s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMultilineTypeMetrics() returns the following information for the % specified font and text: % % character width % character height % ascender % descender % text width % text height % maximum horizontal advance % bounds: x1 % bounds: y1 % bounds: x2 % bounds: y2 % origin: x % origin: y % underline position % underline thickness % % This method is like GetTypeMetrics() but it returns the maximum text width % and height for multiple lines of text. % % The format of the GetMultilineTypeMetrics method is: % % MagickBooleanType GetMultilineTypeMetrics(Image *image, % const DrawInfo *draw_info,TypeMetric *metrics,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o metrics: Return the font metrics in this structure. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetMultilineTypeMetrics(Image *image, const DrawInfo *draw_info,TypeMetric *metrics,ExceptionInfo *exception) { char **textlist; DrawInfo *annotate_info; MagickBooleanType status; register ssize_t i; size_t height, count; TypeMetric extent; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->text != (char *) NULL); assert(draw_info->signature == MagickCoreSignature); if (*draw_info->text == '\0') return(MagickFalse); annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); annotate_info->text=DestroyString(annotate_info->text); /* Convert newlines to multiple lines of text. */ textlist=StringToStrings(draw_info->text,&count); if (textlist == (char **) NULL) return(MagickFalse); annotate_info->render=MagickFalse; annotate_info->direction=UndefinedDirection; (void) memset(metrics,0,sizeof(*metrics)); (void) memset(&extent,0,sizeof(extent)); /* Find the widest of the text lines. */ annotate_info->text=textlist[0]; status=GetTypeMetrics(image,annotate_info,&extent,exception); *metrics=extent; height=(count*(size_t) (metrics->ascent-metrics->descent+ 0.5)+(count-1)*draw_info->interline_spacing); if (AcquireMagickResource(HeightResource,height) == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "WidthOrHeightExceedsLimit","`%s'",image->filename); status=MagickFalse; } else { for (i=1; i < (ssize_t) count; i++) { annotate_info->text=textlist[i]; status=GetTypeMetrics(image,annotate_info,&extent,exception); if (status == MagickFalse) break; if (extent.width > metrics->width) *metrics=extent; if (AcquireMagickResource(WidthResource,extent.width) == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "WidthOrHeightExceedsLimit","`%s'",image->filename); status=MagickFalse; break; } } metrics->height=(double) height; } /* Relinquish resources. */ annotate_info->text=(char *) NULL; annotate_info=DestroyDrawInfo(annotate_info); for (i=0; i < (ssize_t) count; i++) textlist[i]=DestroyString(textlist[i]); textlist=(char **) RelinquishMagickMemory(textlist); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t T y p e M e t r i c s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetTypeMetrics() returns the following information for the specified font % and text: % % character width % character height % ascender % descender % text width % text height % maximum horizontal advance % bounds: x1 % bounds: y1 % bounds: x2 % bounds: y2 % origin: x % origin: y % underline position % underline thickness % % The format of the GetTypeMetrics method is: % % MagickBooleanType GetTypeMetrics(Image *image,const DrawInfo *draw_info, % TypeMetric *metrics,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o metrics: Return the font metrics in this structure. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetTypeMetrics(Image *image, const DrawInfo *draw_info,TypeMetric *metrics,ExceptionInfo *exception) { DrawInfo *annotate_info; MagickBooleanType status; PointInfo offset; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(draw_info != (DrawInfo *) NULL); assert(draw_info->text != (char *) NULL); assert(draw_info->signature == MagickCoreSignature); annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); annotate_info->render=MagickFalse; annotate_info->direction=UndefinedDirection; (void) memset(metrics,0,sizeof(*metrics)); offset.x=0.0; offset.y=0.0; status=RenderType(image,annotate_info,&offset,metrics,exception); if (image->debug != MagickFalse) (void) LogMagickEvent(AnnotateEvent,GetMagickModule(),"Metrics: text: %s; " "width: %g; height: %g; ascent: %g; descent: %g; max advance: %g; " "bounds: %g,%g %g,%g; origin: %g,%g; pixels per em: %g,%g; " "underline position: %g; underline thickness: %g",annotate_info->text, metrics->width,metrics->height,metrics->ascent,metrics->descent, metrics->max_advance,metrics->bounds.x1,metrics->bounds.y1, metrics->bounds.x2,metrics->bounds.y2,metrics->origin.x,metrics->origin.y, metrics->pixels_per_em.x,metrics->pixels_per_em.y, metrics->underline_position,metrics->underline_thickness); annotate_info=DestroyDrawInfo(annotate_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e n d e r T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RenderType() renders text on the image. It also returns the bounding box of % the text relative to the image. % % The format of the RenderType method is: % % MagickBooleanType RenderType(Image *image,DrawInfo *draw_info, % const PointInfo *offset,TypeMetric *metrics,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o offset: (x,y) location of text relative to image. % % o metrics: bounding box of text. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType RenderType(Image *image,const DrawInfo *draw_info, const PointInfo *offset,TypeMetric *metrics,ExceptionInfo *exception) { const TypeInfo *type_info; DrawInfo *annotate_info; MagickBooleanType status; type_info=(const TypeInfo *) NULL; if (draw_info->font != (char *) NULL) { if (*draw_info->font == '@') { status=RenderFreetype(image,draw_info,draw_info->encoding,offset, metrics,exception); return(status); } if (*draw_info->font == '-') return(RenderX11(image,draw_info,offset,metrics,exception)); if (*draw_info->font == '^') return(RenderPostscript(image,draw_info,offset,metrics,exception)); if (IsPathAccessible(draw_info->font) != MagickFalse) { status=RenderFreetype(image,draw_info,draw_info->encoding,offset, metrics,exception); return(status); } type_info=GetTypeInfo(draw_info->font,exception); if (type_info == (const TypeInfo *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "UnableToReadFont","`%s'",draw_info->font); } if ((type_info == (const TypeInfo *) NULL) && (draw_info->family != (const char *) NULL)) { type_info=GetTypeInfoByFamily(draw_info->family,draw_info->style, draw_info->stretch,draw_info->weight,exception); if (type_info == (const TypeInfo *) NULL) { char **family; int number_families; register ssize_t i; /* Parse font family list. */ family=StringToArgv(draw_info->family,&number_families); for (i=1; i < (ssize_t) number_families; i++) { type_info=GetTypeInfoByFamily(family[i],draw_info->style, draw_info->stretch,draw_info->weight,exception); if (type_info != (const TypeInfo *) NULL) break; } for (i=0; i < (ssize_t) number_families; i++) family[i]=DestroyString(family[i]); family=(char **) RelinquishMagickMemory(family); if (type_info == (const TypeInfo *) NULL) (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "UnableToReadFont","`%s'",draw_info->family); } } if (type_info == (const TypeInfo *) NULL) type_info=GetTypeInfoByFamily("Arial",draw_info->style, draw_info->stretch,draw_info->weight,exception); if (type_info == (const TypeInfo *) NULL) type_info=GetTypeInfoByFamily("Helvetica",draw_info->style, draw_info->stretch,draw_info->weight,exception); if (type_info == (const TypeInfo *) NULL) type_info=GetTypeInfoByFamily("Century Schoolbook",draw_info->style, draw_info->stretch,draw_info->weight,exception); if (type_info == (const TypeInfo *) NULL) type_info=GetTypeInfoByFamily("Sans",draw_info->style, draw_info->stretch,draw_info->weight,exception); if (type_info == (const TypeInfo *) NULL) type_info=GetTypeInfoByFamily((const char *) NULL,draw_info->style, draw_info->stretch,draw_info->weight,exception); if (type_info == (const TypeInfo *) NULL) type_info=GetTypeInfo("*",exception); if (type_info == (const TypeInfo *) NULL) { status=RenderFreetype(image,draw_info,draw_info->encoding,offset,metrics, exception); return(status); } annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); annotate_info->face=type_info->face; if (type_info->metrics != (char *) NULL) (void) CloneString(&annotate_info->metrics,type_info->metrics); if (type_info->glyphs != (char *) NULL) (void) CloneString(&annotate_info->font,type_info->glyphs); status=RenderFreetype(image,annotate_info,type_info->encoding,offset,metrics, exception); annotate_info=DestroyDrawInfo(annotate_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e n d e r F r e e t y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RenderFreetype() renders text on the image with a Truetype font. It also % returns the bounding box of the text relative to the image. % % The format of the RenderFreetype method is: % % MagickBooleanType RenderFreetype(Image *image,DrawInfo *draw_info, % const char *encoding,const PointInfo *offset,TypeMetric *metrics, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o encoding: the font encoding. % % o offset: (x,y) location of text relative to image. % % o metrics: bounding box of text. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FREETYPE_DELEGATE) static size_t ComplexTextLayout(const Image *image,const DrawInfo *draw_info, const char *text,const size_t length,const FT_Face face,const FT_Int32 flags, GraphemeInfo **grapheme,ExceptionInfo *exception) { #if defined(MAGICKCORE_RAQM_DELEGATE) const char *features; raqm_t *rq; raqm_glyph_t *glyphs; register ssize_t i; size_t extent; extent=0; rq=raqm_create(); if (rq == (raqm_t *) NULL) goto cleanup; if (raqm_set_text_utf8(rq,text,length) == 0) goto cleanup; if (raqm_set_par_direction(rq,(raqm_direction_t) draw_info->direction) == 0) goto cleanup; if (raqm_set_freetype_face(rq,face) == 0) goto cleanup; features=GetImageProperty(image,"type:features",exception); if (features != (const char *) NULL) { char breaker, quote, *token; int next, status_token; TokenInfo *token_info; next=0; token_info=AcquireTokenInfo(); token=AcquireString(""); status_token=Tokenizer(token_info,0,token,50,features,"",",","",'\0', &breaker,&next,&quote); while (status_token == 0) { raqm_add_font_feature(rq,token,strlen(token)); status_token=Tokenizer(token_info,0,token,50,features,"",",","",'\0', &breaker,&next,&quote); } token_info=DestroyTokenInfo(token_info); token=DestroyString(token); } if (raqm_layout(rq) == 0) goto cleanup; glyphs=raqm_get_glyphs(rq,&extent); if (glyphs == (raqm_glyph_t *) NULL) { extent=0; goto cleanup; } *grapheme=(GraphemeInfo *) AcquireQuantumMemory(extent,sizeof(**grapheme)); if (*grapheme == (GraphemeInfo *) NULL) { extent=0; goto cleanup; } for (i=0; i < (ssize_t) extent; i++) { (*grapheme)[i].index=glyphs[i].index; (*grapheme)[i].x_offset=glyphs[i].x_offset; (*grapheme)[i].x_advance=glyphs[i].x_advance; (*grapheme)[i].y_offset=glyphs[i].y_offset; (*grapheme)[i].cluster=glyphs[i].cluster; } cleanup: raqm_destroy(rq); return(extent); #else const char *p; FT_Error ft_status; register ssize_t i; ssize_t last_glyph; /* Simple layout for bi-directional text (right-to-left or left-to-right). */ magick_unreferenced(image); magick_unreferenced(exception); *grapheme=(GraphemeInfo *) AcquireQuantumMemory(length+1,sizeof(**grapheme)); if (*grapheme == (GraphemeInfo *) NULL) return(0); last_glyph=0; p=text; for (i=0; GetUTFCode(p) != 0; p+=GetUTFOctets(p), i++) { (*grapheme)[i].index=(ssize_t) FT_Get_Char_Index(face,GetUTFCode(p)); (*grapheme)[i].x_offset=0; (*grapheme)[i].y_offset=0; if (((*grapheme)[i].index != 0) && (last_glyph != 0)) { if (FT_HAS_KERNING(face)) { FT_Vector kerning; ft_status=FT_Get_Kerning(face,(FT_UInt) last_glyph,(FT_UInt) (*grapheme)[i].index,ft_kerning_default,&kerning); if (ft_status == 0) (*grapheme)[i-1].x_advance+=(FT_Pos) ((draw_info->direction == RightToLeftDirection ? -1.0 : 1.0)*kerning.x); } } ft_status=FT_Load_Glyph(face,(FT_UInt) (*grapheme)[i].index,flags); (*grapheme)[i].x_advance=face->glyph->advance.x; (*grapheme)[i].cluster=p-text; last_glyph=(*grapheme)[i].index; } return((size_t) i); #endif } static int TraceCubicBezier(FT_Vector *p,FT_Vector *q,FT_Vector *to, DrawInfo *draw_info) { AffineMatrix affine; char path[MagickPathExtent]; affine=draw_info->affine; (void) FormatLocaleString(path,MagickPathExtent,"C%g,%g %g,%g %g,%g", affine.tx+p->x/64.0,affine.ty-p->y/64.0,affine.tx+q->x/64.0,affine.ty- q->y/64.0,affine.tx+to->x/64.0,affine.ty-to->y/64.0); (void) ConcatenateString(&draw_info->primitive,path); return(0); } static int TraceLineTo(FT_Vector *to,DrawInfo *draw_info) { AffineMatrix affine; char path[MagickPathExtent]; affine=draw_info->affine; (void) FormatLocaleString(path,MagickPathExtent,"L%g,%g",affine.tx+to->x/64.0, affine.ty-to->y/64.0); (void) ConcatenateString(&draw_info->primitive,path); return(0); } static int TraceMoveTo(FT_Vector *to,DrawInfo *draw_info) { AffineMatrix affine; char path[MagickPathExtent]; affine=draw_info->affine; (void) FormatLocaleString(path,MagickPathExtent,"M%g,%g",affine.tx+to->x/64.0, affine.ty-to->y/64.0); (void) ConcatenateString(&draw_info->primitive,path); return(0); } static int TraceQuadraticBezier(FT_Vector *control,FT_Vector *to, DrawInfo *draw_info) { AffineMatrix affine; char path[MagickPathExtent]; affine=draw_info->affine; (void) FormatLocaleString(path,MagickPathExtent,"Q%g,%g %g,%g",affine.tx+ control->x/64.0,affine.ty-control->y/64.0,affine.tx+to->x/64.0,affine.ty- to->y/64.0); (void) ConcatenateString(&draw_info->primitive,path); return(0); } static MagickBooleanType RenderFreetype(Image *image,const DrawInfo *draw_info, const char *encoding,const PointInfo *offset,TypeMetric *metrics, ExceptionInfo *exception) { #if !defined(FT_OPEN_PATHNAME) #define FT_OPEN_PATHNAME ft_open_pathname #endif typedef struct _GlyphInfo { FT_UInt id; FT_Vector origin; FT_Glyph image; } GlyphInfo; const char *value; DrawInfo *annotate_info; FT_BBox bounds; FT_BitmapGlyph bitmap; FT_Encoding encoding_type; FT_Error ft_status; FT_Face face; FT_Int32 flags; FT_Library library; FT_Matrix affine; FT_Open_Args args; FT_Vector origin; GlyphInfo glyph, last_glyph; GraphemeInfo *grapheme; MagickBooleanType status; PointInfo point, resolution; register char *p; register ssize_t i; size_t length; ssize_t code, y; static FT_Outline_Funcs OutlineMethods = { (FT_Outline_MoveTo_Func) TraceMoveTo, (FT_Outline_LineTo_Func) TraceLineTo, (FT_Outline_ConicTo_Func) TraceQuadraticBezier, (FT_Outline_CubicTo_Func) TraceCubicBezier, 0, 0 }; unsigned char *utf8; /* Initialize Truetype library. */ ft_status=FT_Init_FreeType(&library); if (ft_status != 0) ThrowBinaryException(TypeError,"UnableToInitializeFreetypeLibrary", image->filename); args.flags=FT_OPEN_PATHNAME; if (draw_info->font == (char *) NULL) args.pathname=ConstantString("helvetica"); else if (*draw_info->font != '@') args.pathname=ConstantString(draw_info->font); else args.pathname=ConstantString(draw_info->font+1); face=(FT_Face) NULL; ft_status=FT_Open_Face(library,&args,(long) draw_info->face,&face); if (ft_status != 0) { (void) FT_Done_FreeType(library); (void) ThrowMagickException(exception,GetMagickModule(),TypeError, "UnableToReadFont","`%s'",args.pathname); args.pathname=DestroyString(args.pathname); return(MagickFalse); } args.pathname=DestroyString(args.pathname); if ((draw_info->metrics != (char *) NULL) && (IsPathAccessible(draw_info->metrics) != MagickFalse)) (void) FT_Attach_File(face,draw_info->metrics); encoding_type=FT_ENCODING_UNICODE; ft_status=FT_Select_Charmap(face,encoding_type); if ((ft_status != 0) && (face->num_charmaps != 0)) ft_status=FT_Set_Charmap(face,face->charmaps[0]); if (encoding != (const char *) NULL) { if (LocaleCompare(encoding,"AdobeCustom") == 0) encoding_type=FT_ENCODING_ADOBE_CUSTOM; if (LocaleCompare(encoding,"AdobeExpert") == 0) encoding_type=FT_ENCODING_ADOBE_EXPERT; if (LocaleCompare(encoding,"AdobeStandard") == 0) encoding_type=FT_ENCODING_ADOBE_STANDARD; if (LocaleCompare(encoding,"AppleRoman") == 0) encoding_type=FT_ENCODING_APPLE_ROMAN; if (LocaleCompare(encoding,"BIG5") == 0) encoding_type=FT_ENCODING_BIG5; #if defined(FT_ENCODING_PRC) if (LocaleCompare(encoding,"GB2312") == 0) encoding_type=FT_ENCODING_PRC; #endif #if defined(FT_ENCODING_JOHAB) if (LocaleCompare(encoding,"Johab") == 0) encoding_type=FT_ENCODING_JOHAB; #endif #if defined(FT_ENCODING_ADOBE_LATIN_1) if (LocaleCompare(encoding,"Latin-1") == 0) encoding_type=FT_ENCODING_ADOBE_LATIN_1; #endif #if defined(FT_ENCODING_ADOBE_LATIN_2) if (LocaleCompare(encoding,"Latin-2") == 0) encoding_type=FT_ENCODING_OLD_LATIN_2; #endif if (LocaleCompare(encoding,"None") == 0) encoding_type=FT_ENCODING_NONE; if (LocaleCompare(encoding,"SJIScode") == 0) encoding_type=FT_ENCODING_SJIS; if (LocaleCompare(encoding,"Symbol") == 0) encoding_type=FT_ENCODING_MS_SYMBOL; if (LocaleCompare(encoding,"Unicode") == 0) encoding_type=FT_ENCODING_UNICODE; if (LocaleCompare(encoding,"Wansung") == 0) encoding_type=FT_ENCODING_WANSUNG; ft_status=FT_Select_Charmap(face,encoding_type); if (ft_status != 0) { (void) FT_Done_Face(face); (void) FT_Done_FreeType(library); ThrowBinaryException(TypeError,"UnrecognizedFontEncoding",encoding); } } /* Set text size. */ resolution.x=DefaultResolution; resolution.y=DefaultResolution; if (draw_info->density != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType geometry_flags; geometry_flags=ParseGeometry(draw_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((geometry_flags & SigmaValue) == 0) resolution.y=resolution.x; } ft_status=FT_Set_Char_Size(face,(FT_F26Dot6) (64.0*draw_info->pointsize), (FT_F26Dot6) (64.0*draw_info->pointsize),(FT_UInt) resolution.x, (FT_UInt) resolution.y); if (ft_status != 0) { (void) FT_Done_Face(face); (void) FT_Done_FreeType(library); ThrowBinaryException(TypeError,"UnableToReadFont",draw_info->font); } metrics->pixels_per_em.x=face->size->metrics.x_ppem; metrics->pixels_per_em.y=face->size->metrics.y_ppem; metrics->ascent=(double) face->size->metrics.ascender/64.0; metrics->descent=(double) face->size->metrics.descender/64.0; metrics->width=0; metrics->origin.x=0; metrics->origin.y=0; metrics->height=(double) face->size->metrics.height/64.0; metrics->max_advance=0.0; if (face->size->metrics.max_advance > MagickEpsilon) metrics->max_advance=(double) face->size->metrics.max_advance/64.0; metrics->bounds.x1=0.0; metrics->bounds.y1=metrics->descent; metrics->bounds.x2=metrics->ascent+metrics->descent; metrics->bounds.y2=metrics->ascent+metrics->descent; metrics->underline_position=face->underline_position/64.0; metrics->underline_thickness=face->underline_thickness/64.0; if ((draw_info->text == (char *) NULL) || (*draw_info->text == '\0')) { (void) FT_Done_Face(face); (void) FT_Done_FreeType(library); return(MagickTrue); } /* Compute bounding box. */ if (image->debug != MagickFalse) (void) LogMagickEvent(AnnotateEvent,GetMagickModule(),"Font %s; " "font-encoding %s; text-encoding %s; pointsize %g", draw_info->font != (char *) NULL ? draw_info->font : "none", encoding != (char *) NULL ? encoding : "none", draw_info->encoding != (char *) NULL ? draw_info->encoding : "none", draw_info->pointsize); flags=FT_LOAD_DEFAULT; if (draw_info->render == MagickFalse) flags=FT_LOAD_NO_BITMAP; if (draw_info->text_antialias == MagickFalse) flags|=FT_LOAD_TARGET_MONO; else { #if defined(FT_LOAD_TARGET_LIGHT) flags|=FT_LOAD_TARGET_LIGHT; #elif defined(FT_LOAD_TARGET_LCD) flags|=FT_LOAD_TARGET_LCD; #endif } value=GetImageProperty(image,"type:hinting",exception); if ((value != (const char *) NULL) && (LocaleCompare(value,"off") == 0)) flags|=FT_LOAD_NO_HINTING; glyph.id=0; glyph.image=NULL; last_glyph.id=0; last_glyph.image=NULL; origin.x=0; origin.y=0; affine.xx=65536L; affine.yx=0L; affine.xy=0L; affine.yy=65536L; if (draw_info->render != MagickFalse) { affine.xx=(FT_Fixed) (65536L*draw_info->affine.sx+0.5); affine.yx=(FT_Fixed) (-65536L*draw_info->affine.rx+0.5); affine.xy=(FT_Fixed) (-65536L*draw_info->affine.ry+0.5); affine.yy=(FT_Fixed) (65536L*draw_info->affine.sy+0.5); } annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); if (annotate_info->dash_pattern != (double *) NULL) annotate_info->dash_pattern[0]=0.0; (void) CloneString(&annotate_info->primitive,"path '"); status=MagickTrue; if (draw_info->render != MagickFalse) { if (image->storage_class != DirectClass) (void) SetImageStorageClass(image,DirectClass,exception); if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); } point.x=0.0; point.y=0.0; for (p=draw_info->text; GetUTFCode(p) != 0; p+=GetUTFOctets(p)) if (GetUTFCode(p) < 0) break; utf8=(unsigned char *) NULL; if (GetUTFCode(p) == 0) p=draw_info->text; else { utf8=ConvertLatin1ToUTF8((unsigned char *) draw_info->text); if (utf8 != (unsigned char *) NULL) p=(char *) utf8; } grapheme=(GraphemeInfo *) NULL; length=ComplexTextLayout(image,draw_info,p,strlen(p),face,flags,&grapheme, exception); code=0; for (i=0; i < (ssize_t) length; i++) { FT_Outline outline; /* Render UTF-8 sequence. */ glyph.id=(FT_UInt) grapheme[i].index; if (glyph.id == 0) glyph.id=FT_Get_Char_Index(face,' '); if ((glyph.id != 0) && (last_glyph.id != 0)) origin.x+=(FT_Pos) (64.0*draw_info->kerning); glyph.origin=origin; glyph.origin.x+=(FT_Pos) grapheme[i].x_offset; glyph.origin.y+=(FT_Pos) grapheme[i].y_offset; glyph.image=0; ft_status=FT_Load_Glyph(face,glyph.id,flags); if (ft_status != 0) continue; ft_status=FT_Get_Glyph(face->glyph,&glyph.image); if (ft_status != 0) continue; outline=((FT_OutlineGlyph) glyph.image)->outline; ft_status=FT_Outline_Get_BBox(&outline,&bounds); if (ft_status != 0) continue; if ((p == draw_info->text) || (bounds.xMin < metrics->bounds.x1)) if (bounds.xMin != 0) metrics->bounds.x1=(double) bounds.xMin; if ((p == draw_info->text) || (bounds.yMin < metrics->bounds.y1)) if (bounds.yMin != 0) metrics->bounds.y1=(double) bounds.yMin; if ((p == draw_info->text) || (bounds.xMax > metrics->bounds.x2)) if (bounds.xMax != 0) metrics->bounds.x2=(double) bounds.xMax; if ((p == draw_info->text) || (bounds.yMax > metrics->bounds.y2)) if (bounds.yMax != 0) metrics->bounds.y2=(double) bounds.yMax; if (((draw_info->stroke.alpha != TransparentAlpha) || (draw_info->stroke_pattern != (Image *) NULL)) && ((status != MagickFalse) && (draw_info->render != MagickFalse))) { /* Trace the glyph. */ annotate_info->affine.tx=glyph.origin.x/64.0; annotate_info->affine.ty=(-glyph.origin.y/64.0); if ((outline.n_contours > 0) && (outline.n_points > 0)) ft_status=FT_Outline_Decompose(&outline,&OutlineMethods, annotate_info); } FT_Vector_Transform(&glyph.origin,&affine); (void) FT_Glyph_Transform(glyph.image,&affine,&glyph.origin); ft_status=FT_Glyph_To_Bitmap(&glyph.image,ft_render_mode_normal, (FT_Vector *) NULL,MagickTrue); if (ft_status != 0) continue; bitmap=(FT_BitmapGlyph) glyph.image; point.x=offset->x+bitmap->left; if (bitmap->bitmap.pixel_mode == ft_pixel_mode_mono) point.x=offset->x+(origin.x >> 6); point.y=offset->y-bitmap->top; if (draw_info->render != MagickFalse) { CacheView *image_view; MagickBooleanType transparent_fill; register unsigned char *r; /* Rasterize the glyph. */ transparent_fill=((draw_info->fill.alpha == TransparentAlpha) && (draw_info->fill_pattern == (Image *) NULL) && (draw_info->stroke.alpha == TransparentAlpha) && (draw_info->stroke_pattern == (Image *) NULL)) ? MagickTrue : MagickFalse; image_view=AcquireAuthenticCacheView(image,exception); r=bitmap->bitmap.buffer; for (y=0; y < (ssize_t) bitmap->bitmap.rows; y++) { double fill_opacity; MagickBooleanType active, sync; PixelInfo fill_color; register Quantum *magick_restrict q; register ssize_t x; ssize_t n, x_offset, y_offset; if (status == MagickFalse) continue; x_offset=(ssize_t) ceil(point.x-0.5); y_offset=(ssize_t) ceil(point.y+y-0.5); if ((y_offset < 0) || (y_offset >= (ssize_t) image->rows)) continue; q=(Quantum *) NULL; if ((x_offset < 0) || (x_offset >= (ssize_t) image->columns)) active=MagickFalse; else { q=GetCacheViewAuthenticPixels(image_view,x_offset,y_offset, bitmap->bitmap.width,1,exception); active=q != (Quantum *) NULL ? MagickTrue : MagickFalse; } n=y*bitmap->bitmap.pitch-1; for (x=0; x < (ssize_t) bitmap->bitmap.width; x++) { n++; x_offset++; if ((x_offset < 0) || (x_offset >= (ssize_t) image->columns)) { if (q != (Quantum *) NULL) q+=GetPixelChannels(image); continue; } if (bitmap->bitmap.pixel_mode != ft_pixel_mode_mono) fill_opacity=(double) (r[n])/(bitmap->bitmap.num_grays-1); else fill_opacity=((r[(x >> 3)+y*bitmap->bitmap.pitch] & (1 << (~x & 0x07)))) == 0 ? 0.0 : 1.0; if (draw_info->text_antialias == MagickFalse) fill_opacity=fill_opacity >= 0.5 ? 1.0 : 0.0; if (active == MagickFalse) q=GetCacheViewAuthenticPixels(image_view,x_offset,y_offset,1,1, exception); if (q == (Quantum *) NULL) continue; if (transparent_fill == MagickFalse) { GetPixelInfo(image,&fill_color); GetFillColor(draw_info,x_offset,y_offset,&fill_color,exception); fill_opacity=fill_opacity*fill_color.alpha; CompositePixelOver(image,&fill_color,fill_opacity,q, GetPixelAlpha(image,q),q); } else { double Sa, Da; Da=1.0-(QuantumScale*GetPixelAlpha(image,q)); Sa=fill_opacity; fill_opacity=(1.0-RoundToUnity(Sa+Da-Sa*Da))*QuantumRange; SetPixelAlpha(image,fill_opacity,q); } if (active == MagickFalse) { sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (((draw_info->stroke.alpha != TransparentAlpha) || (draw_info->stroke_pattern != (Image *) NULL)) && (status != MagickFalse)) { /* Draw text stroke. */ annotate_info->linejoin=RoundJoin; annotate_info->affine.tx=offset->x; annotate_info->affine.ty=offset->y; (void) ConcatenateString(&annotate_info->primitive,"'"); if (strlen(annotate_info->primitive) > 7) (void) DrawImage(image,annotate_info,exception); (void) CloneString(&annotate_info->primitive,"path '"); } } if ((fabs(draw_info->interword_spacing) >= MagickEpsilon) && (IsUTFSpace(GetUTFCode(p+grapheme[i].cluster)) != MagickFalse) && (IsUTFSpace(code) == MagickFalse)) origin.x+=(FT_Pos) (64.0*draw_info->interword_spacing); else origin.x+=(FT_Pos) grapheme[i].x_advance; metrics->origin.x=(double) origin.x; metrics->origin.y=(double) origin.y; if (metrics->origin.x > metrics->width) metrics->width=metrics->origin.x; if (last_glyph.image != 0) { FT_Done_Glyph(last_glyph.image); last_glyph.image=0; } last_glyph=glyph; code=GetUTFCode(p+grapheme[i].cluster); } if (grapheme != (GraphemeInfo *) NULL) grapheme=(GraphemeInfo *) RelinquishMagickMemory(grapheme); if (utf8 != (unsigned char *) NULL) utf8=(unsigned char *) RelinquishMagickMemory(utf8); if (glyph.image != 0) { FT_Done_Glyph(glyph.image); glyph.image=0; } /* Determine font metrics. */ metrics->bounds.x1/=64.0; metrics->bounds.y1/=64.0; metrics->bounds.x2/=64.0; metrics->bounds.y2/=64.0; metrics->origin.x/=64.0; metrics->origin.y/=64.0; metrics->width/=64.0; /* Relinquish resources. */ annotate_info=DestroyDrawInfo(annotate_info); (void) FT_Done_Face(face); (void) FT_Done_FreeType(library); return(status); } #else static MagickBooleanType RenderFreetype(Image *image,const DrawInfo *draw_info, const char *magick_unused(encoding),const PointInfo *offset, TypeMetric *metrics,ExceptionInfo *exception) { (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","'%s' (Freetype)", draw_info->font != (char *) NULL ? draw_info->font : "none"); return(RenderPostscript(image,draw_info,offset,metrics,exception)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e n d e r P o s t s c r i p t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RenderPostscript() renders text on the image with a Postscript font. It % also returns the bounding box of the text relative to the image. % % The format of the RenderPostscript method is: % % MagickBooleanType RenderPostscript(Image *image,DrawInfo *draw_info, % const PointInfo *offset,TypeMetric *metrics,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o offset: (x,y) location of text relative to image. % % o metrics: bounding box of text. % % o exception: return any errors or warnings in this structure. % */ static char *EscapeParenthesis(const char *source) { char *destination; register char *q; register const char *p; size_t length; assert(source != (const char *) NULL); length=0; for (p=source; *p != '\0'; p++) { if ((*p == '\\') || (*p == '(') || (*p == ')')) { if (~length < 1) ThrowFatalException(ResourceLimitFatalError,"UnableToEscapeString"); length++; } length++; } destination=(char *) NULL; if (~length >= (MagickPathExtent-1)) destination=(char *) AcquireQuantumMemory(length+MagickPathExtent, sizeof(*destination)); if (destination == (char *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToEscapeString"); *destination='\0'; q=destination; for (p=source; *p != '\0'; p++) { if ((*p == '\\') || (*p == '(') || (*p == ')')) *q++='\\'; *q++=(*p); } *q='\0'; return(destination); } static MagickBooleanType RenderPostscript(Image *image, const DrawInfo *draw_info,const PointInfo *offset,TypeMetric *metrics, ExceptionInfo *exception) { char filename[MagickPathExtent], geometry[MagickPathExtent], *text; FILE *file; Image *annotate_image; ImageInfo *annotate_info; int unique_file; MagickBooleanType identity; PointInfo extent, point, resolution; register ssize_t i; size_t length; ssize_t y; /* Render label with a Postscript font. */ if (image->debug != MagickFalse) (void) LogMagickEvent(AnnotateEvent,GetMagickModule(), "Font %s; pointsize %g",draw_info->font != (char *) NULL ? draw_info->font : "none",draw_info->pointsize); file=(FILE *) NULL; unique_file=AcquireUniqueFileResource(filename); if (unique_file != -1) file=fdopen(unique_file,"wb"); if ((unique_file == -1) || (file == (FILE *) NULL)) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile",filename); return(MagickFalse); } (void) FormatLocaleFile(file,"%%!PS-Adobe-3.0\n"); (void) FormatLocaleFile(file,"/ReencodeType\n"); (void) FormatLocaleFile(file,"{\n"); (void) FormatLocaleFile(file," findfont dup length\n"); (void) FormatLocaleFile(file, " dict begin { 1 index /FID ne {def} {pop pop} ifelse } forall\n"); (void) FormatLocaleFile(file, " /Encoding ISOLatin1Encoding def currentdict end definefont pop\n"); (void) FormatLocaleFile(file,"} bind def\n"); /* Sample to compute bounding box. */ identity=(fabs(draw_info->affine.sx-draw_info->affine.sy) < MagickEpsilon) && (fabs(draw_info->affine.rx) < MagickEpsilon) && (fabs(draw_info->affine.ry) < MagickEpsilon) ? MagickTrue : MagickFalse; extent.x=0.0; extent.y=0.0; length=strlen(draw_info->text); for (i=0; i <= (ssize_t) (length+2); i++) { point.x=fabs(draw_info->affine.sx*i*draw_info->pointsize+ draw_info->affine.ry*2.0*draw_info->pointsize); point.y=fabs(draw_info->affine.rx*i*draw_info->pointsize+ draw_info->affine.sy*2.0*draw_info->pointsize); if (point.x > extent.x) extent.x=point.x; if (point.y > extent.y) extent.y=point.y; } (void) FormatLocaleFile(file,"%g %g moveto\n",identity != MagickFalse ? 0.0 : extent.x/2.0,extent.y/2.0); (void) FormatLocaleFile(file,"%g %g scale\n",draw_info->pointsize, draw_info->pointsize); if ((draw_info->font == (char *) NULL) || (*draw_info->font == '\0') || (strchr(draw_info->font,'/') != (char *) NULL)) (void) FormatLocaleFile(file, "/Times-Roman-ISO dup /Times-Roman ReencodeType findfont setfont\n"); else (void) FormatLocaleFile(file, "/%s-ISO dup /%s ReencodeType findfont setfont\n",draw_info->font, draw_info->font); (void) FormatLocaleFile(file,"[%g %g %g %g 0 0] concat\n", draw_info->affine.sx,-draw_info->affine.rx,-draw_info->affine.ry, draw_info->affine.sy); text=EscapeParenthesis(draw_info->text); if (identity == MagickFalse) (void) FormatLocaleFile(file,"(%s) stringwidth pop -0.5 mul -0.5 rmoveto\n", text); (void) FormatLocaleFile(file,"(%s) show\n",text); text=DestroyString(text); (void) FormatLocaleFile(file,"showpage\n"); (void) fclose(file); (void) FormatLocaleString(geometry,MagickPathExtent,"%.20gx%.20g+0+0!", floor(extent.x+0.5),floor(extent.y+0.5)); annotate_info=AcquireImageInfo(); (void) FormatLocaleString(annotate_info->filename,MagickPathExtent,"ps:%s", filename); (void) CloneString(&annotate_info->page,geometry); if (draw_info->density != (char *) NULL) (void) CloneString(&annotate_info->density,draw_info->density); annotate_info->antialias=draw_info->text_antialias; annotate_image=ReadImage(annotate_info,exception); CatchException(exception); annotate_info=DestroyImageInfo(annotate_info); (void) RelinquishUniqueFileResource(filename); if (annotate_image == (Image *) NULL) return(MagickFalse); (void) NegateImage(annotate_image,MagickFalse,exception); resolution.x=DefaultResolution; resolution.y=DefaultResolution; if (draw_info->density != (char *) NULL) { GeometryInfo geometry_info; MagickStatusType flags; flags=ParseGeometry(draw_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (identity == MagickFalse) (void) TransformImage(&annotate_image,"0x0",(char *) NULL,exception); else { RectangleInfo crop_info; crop_info=GetImageBoundingBox(annotate_image,exception); crop_info.height=(size_t) ((resolution.y/DefaultResolution)* ExpandAffine(&draw_info->affine)*draw_info->pointsize+0.5); crop_info.y=(ssize_t) ceil((resolution.y/DefaultResolution)*extent.y/8.0- 0.5); (void) FormatLocaleString(geometry,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) crop_info.width,(double) crop_info.height,(double) crop_info.x,(double) crop_info.y); (void) TransformImage(&annotate_image,geometry,(char *) NULL,exception); } metrics->pixels_per_em.x=(resolution.y/DefaultResolution)* ExpandAffine(&draw_info->affine)*draw_info->pointsize; metrics->pixels_per_em.y=metrics->pixels_per_em.x; metrics->ascent=metrics->pixels_per_em.x; metrics->descent=metrics->pixels_per_em.y/-5.0; metrics->width=(double) annotate_image->columns/ ExpandAffine(&draw_info->affine); metrics->height=1.152*metrics->pixels_per_em.x; metrics->max_advance=metrics->pixels_per_em.x; metrics->bounds.x1=0.0; metrics->bounds.y1=metrics->descent; metrics->bounds.x2=metrics->ascent+metrics->descent; metrics->bounds.y2=metrics->ascent+metrics->descent; metrics->underline_position=(-2.0); metrics->underline_thickness=1.0; if (draw_info->render == MagickFalse) { annotate_image=DestroyImage(annotate_image); return(MagickTrue); } if (draw_info->fill.alpha != TransparentAlpha) { CacheView *annotate_view; MagickBooleanType sync; PixelInfo fill_color; /* Render fill color. */ if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); if (annotate_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(annotate_image,OpaqueAlphaChannel, exception); fill_color=draw_info->fill; annotate_view=AcquireAuthenticCacheView(annotate_image,exception); for (y=0; y < (ssize_t) annotate_image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=GetCacheViewAuthenticPixels(annotate_view,0,y,annotate_image->columns, 1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) annotate_image->columns; x++) { GetFillColor(draw_info,x,y,&fill_color,exception); SetPixelAlpha(annotate_image,ClampToQuantum((((double) QuantumScale* GetPixelIntensity(annotate_image,q)*fill_color.alpha))),q); SetPixelRed(annotate_image,fill_color.red,q); SetPixelGreen(annotate_image,fill_color.green,q); SetPixelBlue(annotate_image,fill_color.blue,q); q+=GetPixelChannels(annotate_image); } sync=SyncCacheViewAuthenticPixels(annotate_view,exception); if (sync == MagickFalse) break; } annotate_view=DestroyCacheView(annotate_view); (void) CompositeImage(image,annotate_image,OverCompositeOp,MagickTrue, (ssize_t) ceil(offset->x-0.5),(ssize_t) ceil(offset->y-(metrics->ascent+ metrics->descent)-0.5),exception); } annotate_image=DestroyImage(annotate_image); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e n d e r X 1 1 % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RenderX11() renders text on the image with an X11 font. It also returns the % bounding box of the text relative to the image. % % The format of the RenderX11 method is: % % MagickBooleanType RenderX11(Image *image,DrawInfo *draw_info, % const PointInfo *offset,TypeMetric *metrics,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o offset: (x,y) location of text relative to image. % % o metrics: bounding box of text. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType RenderX11(Image *image,const DrawInfo *draw_info, const PointInfo *offset,TypeMetric *metrics,ExceptionInfo *exception) { MagickBooleanType status; if (annotate_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&annotate_semaphore); LockSemaphoreInfo(annotate_semaphore); status=XRenderImage(image,draw_info,offset,metrics,exception); UnlockSemaphoreInfo(annotate_semaphore); return(status); }
./CrossVul/dataset_final_sorted/CWE-399/c/bad_931_0
crossvul-cpp_data_bad_905_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % BBBB M M PPPP % % B B MM MM P P % % BBBB M M M PPPP % % B B M M P % % BBBB M M P % % % % % % Read/Write Microsoft Windows Bitmap Image Format % % % % Software Design % % Cristy % % Glenn Randers-Pehrson % % December 2001 % % % % % % Copyright 1999-2019 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://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/colormap-private.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" #include "MagickCore/transform.h" /* Macro definitions (from Windows wingdi.h). */ #undef BI_JPEG #define BI_JPEG 4 #undef BI_PNG #define BI_PNG 5 #if !defined(MAGICKCORE_WINDOWS_SUPPORT) || defined(__MINGW32__) #undef BI_RGB #define BI_RGB 0 #undef BI_RLE8 #define BI_RLE8 1 #undef BI_RLE4 #define BI_RLE4 2 #undef BI_BITFIELDS #define BI_BITFIELDS 3 #undef LCS_CALIBRATED_RBG #define LCS_CALIBRATED_RBG 0 #undef LCS_sRGB #define LCS_sRGB 1 #undef LCS_WINDOWS_COLOR_SPACE #define LCS_WINDOWS_COLOR_SPACE 2 #undef PROFILE_LINKED #define PROFILE_LINKED 3 #undef PROFILE_EMBEDDED #define PROFILE_EMBEDDED 4 #undef LCS_GM_BUSINESS #define LCS_GM_BUSINESS 1 /* Saturation */ #undef LCS_GM_GRAPHICS #define LCS_GM_GRAPHICS 2 /* Relative */ #undef LCS_GM_IMAGES #define LCS_GM_IMAGES 4 /* Perceptual */ #undef LCS_GM_ABS_COLORIMETRIC #define LCS_GM_ABS_COLORIMETRIC 8 /* Absolute */ #endif /* Enumerated declaractions. */ typedef enum { UndefinedSubtype, RGB555, RGB565, ARGB4444, ARGB1555 } BMPSubtype; /* Typedef declarations. */ typedef struct _BMPInfo { unsigned int file_size, ba_offset, offset_bits, size; ssize_t width, height; unsigned short planes, bits_per_pixel; unsigned int compression, image_size, x_pixels, y_pixels, number_colors, red_mask, green_mask, blue_mask, alpha_mask, colors_important; long colorspace; PrimaryInfo red_primary, green_primary, blue_primary, gamma_scale; } BMPInfo; /* Forward declarations. */ static MagickBooleanType WriteBMPImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DecodeImage unpacks the packed image pixels into runlength-encoded % pixel packets. % % The format of the DecodeImage method is: % % MagickBooleanType DecodeImage(Image *image,const size_t compression, % unsigned char *pixels,const size_t number_pixels) % % A description of each parameter follows: % % o image: the address of a structure of type Image. % % o compression: Zero means uncompressed. A value of 1 means the % compressed pixels are runlength encoded for a 256-color bitmap. % A value of 2 means a 16-color bitmap. A value of 3 means bitfields % encoding. % % o pixels: The address of a byte (8 bits) array of pixel data created by % the decoding process. % % o number_pixels: The number of pixels. % */ static MagickBooleanType DecodeImage(Image *image,const size_t compression, unsigned char *pixels,const size_t number_pixels) { int byte, count; register ssize_t i, x; register unsigned char *p, *q; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); (void) memset(pixels,0,number_pixels*sizeof(*pixels)); byte=0; x=0; p=pixels; q=pixels+number_pixels; for (y=0; y < (ssize_t) image->rows; ) { MagickBooleanType status; if ((p < pixels) || (p > q)) break; count=ReadBlobByte(image); if (count == EOF) break; if (count > 0) { /* Encoded mode. */ count=(int) MagickMin((ssize_t) count,(ssize_t) (q-p)); byte=ReadBlobByte(image); if (byte == EOF) break; if (compression == BI_RLE8) { for (i=0; i < (ssize_t) count; i++) *p++=(unsigned char) byte; } else { for (i=0; i < (ssize_t) count; i++) *p++=(unsigned char) ((i & 0x01) != 0 ? (byte & 0x0f) : ((byte >> 4) & 0x0f)); } x+=count; } else { /* Escape mode. */ count=ReadBlobByte(image); if (count == EOF) break; if (count == 0x01) return(MagickTrue); switch (count) { case 0x00: { /* End of line. */ x=0; y++; p=pixels+y*image->columns; break; } case 0x02: { /* Delta mode. */ x+=ReadBlobByte(image); y+=ReadBlobByte(image); p=pixels+y*image->columns+x; break; } default: { /* Absolute mode. */ count=(int) MagickMin((ssize_t) count,(ssize_t) (q-p)); if (compression == BI_RLE8) for (i=0; i < (ssize_t) count; i++) { byte=ReadBlobByte(image); if (byte == EOF) break; *p++=(unsigned char) byte; } else for (i=0; i < (ssize_t) count; i++) { if ((i & 0x01) == 0) { byte=ReadBlobByte(image); if (byte == EOF) break; } *p++=(unsigned char) ((i & 0x01) != 0 ? (byte & 0x0f) : ((byte >> 4) & 0x0f)); } x+=count; /* Read pad byte. */ if (compression == BI_RLE8) { if ((count & 0x01) != 0) if (ReadBlobByte(image) == EOF) break; } else if (((count & 0x03) == 1) || ((count & 0x03) == 2)) if (ReadBlobByte(image) == EOF) break; break; } } } status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } (void) ReadBlobByte(image); /* end of line */ (void) ReadBlobByte(image); return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E n c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EncodeImage compresses pixels using a runlength encoded format. % % The format of the EncodeImage method is: % % static MagickBooleanType EncodeImage(Image *image, % const size_t bytes_per_line,const unsigned char *pixels, % unsigned char *compressed_pixels) % % A description of each parameter follows: % % o image: The image. % % o bytes_per_line: the number of bytes in a scanline of compressed pixels % % o pixels: The address of a byte (8 bits) array of pixel data created by % the compression process. % % o compressed_pixels: The address of a byte (8 bits) array of compressed % pixel data. % */ static size_t EncodeImage(Image *image,const size_t bytes_per_line, const unsigned char *pixels,unsigned char *compressed_pixels) { MagickBooleanType status; register const unsigned char *p; register ssize_t i, x; register unsigned char *q; ssize_t y; /* Runlength encode pixels. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (const unsigned char *) NULL); assert(compressed_pixels != (unsigned char *) NULL); p=pixels; q=compressed_pixels; i=0; for (y=0; y < (ssize_t) image->rows; y++) { for (x=0; x < (ssize_t) bytes_per_line; x+=i) { /* Determine runlength. */ for (i=1; ((x+i) < (ssize_t) bytes_per_line); i++) if ((i == 255) || (*(p+i) != *p)) break; *q++=(unsigned char) i; *q++=(*p); p+=i; } /* End of line. */ *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } /* End of bitmap. */ *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x01; return((size_t) (q-compressed_pixels)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s B M P % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsBMP() returns MagickTrue if the image format type, identified by the % magick string, is BMP. % % The format of the IsBMP method is: % % MagickBooleanType IsBMP(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 IsBMP(const unsigned char *magick,const size_t length) { if (length < 2) return(MagickFalse); if ((LocaleNCompare((char *) magick,"BA",2) == 0) || (LocaleNCompare((char *) magick,"BM",2) == 0) || (LocaleNCompare((char *) magick,"IC",2) == 0) || (LocaleNCompare((char *) magick,"PI",2) == 0) || (LocaleNCompare((char *) magick,"CI",2) == 0) || (LocaleNCompare((char *) magick,"CP",2) == 0)) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d B M P I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadBMPImage() reads a Microsoft Windows bitmap image file, Version % 2, 3 (for Windows or NT), or 4, 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 ReadBMPImage method is: % % image=ReadBMPImage(image_info) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) { BMPInfo bmp_info; Image *image; MagickBooleanType status; MagickOffsetType offset, profile_data, profile_size, start_position; MemoryInfo *pixel_info; Quantum index; register Quantum *q; register ssize_t i, x; register unsigned char *p; size_t bit, bytes_per_line, length; ssize_t count, y; unsigned char magick[12], *pixels; unsigned int blue, green, offset_bits, red; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a BMP file. */ (void) memset(&bmp_info,0,sizeof(bmp_info)); bmp_info.ba_offset=0; start_position=0; offset_bits=0; count=ReadBlob(image,2,magick); if (count != 2) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); do { PixelInfo quantum_bits; PixelPacket shift; /* Verify BMP identifier. */ start_position=TellBlob(image)-2; bmp_info.ba_offset=0; while (LocaleNCompare((char *) magick,"BA",2) == 0) { bmp_info.file_size=ReadBlobLSBLong(image); bmp_info.ba_offset=ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); count=ReadBlob(image,2,magick); if (count != 2) break; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c", magick[0],magick[1]); if ((count != 2) || ((LocaleNCompare((char *) magick,"BM",2) != 0) && (LocaleNCompare((char *) magick,"CI",2) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); bmp_info.file_size=ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); bmp_info.offset_bits=ReadBlobLSBLong(image); bmp_info.size=ReadBlobLSBLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," BMP size: %u", bmp_info.size); profile_data=0; profile_size=0; if (bmp_info.size == 12) { /* OS/2 BMP image file. */ (void) CopyMagickString(image->magick,"BMP2",MagickPathExtent); bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image)); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.x_pixels=0; bmp_info.y_pixels=0; bmp_info.number_colors=0; bmp_info.compression=BI_RGB; bmp_info.image_size=0; bmp_info.alpha_mask=0; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: OS/2 Bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); } } else { /* Microsoft Windows BMP image file. */ if (bmp_info.size < 40) ThrowReaderException(CorruptImageError,"NonOS2HeaderSizeError"); bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image); bmp_info.planes=ReadBlobLSBShort(image); bmp_info.bits_per_pixel=ReadBlobLSBShort(image); bmp_info.compression=ReadBlobLSBLong(image); bmp_info.image_size=ReadBlobLSBLong(image); bmp_info.x_pixels=ReadBlobLSBLong(image); bmp_info.y_pixels=ReadBlobLSBLong(image); bmp_info.number_colors=ReadBlobLSBLong(image); if ((MagickSizeType) bmp_info.number_colors > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); bmp_info.colors_important=ReadBlobLSBLong(image); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format: MS Windows bitmap"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) bmp_info.height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Bits per pixel: %.20g",(double) bmp_info.bits_per_pixel); switch (bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RGB"); break; } case BI_RLE4: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE4"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_RLE8"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_BITFIELDS"); break; } case BI_PNG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_PNG"); break; } case BI_JPEG: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: BI_JPEG"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression: UNKNOWN (%u)",bmp_info.compression); } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number of colors: %u",bmp_info.number_colors); } bmp_info.red_mask=ReadBlobLSBLong(image); bmp_info.green_mask=ReadBlobLSBLong(image); bmp_info.blue_mask=ReadBlobLSBLong(image); if (bmp_info.size > 40) { double gamma; /* Read color management information. */ bmp_info.alpha_mask=ReadBlobLSBLong(image); bmp_info.colorspace=ReadBlobLSBSignedLong(image); /* Decode 2^30 fixed point formatted CIE primaries. */ # define BMP_DENOM ((double) 0x40000000) bmp_info.red_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.red_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.green_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.x=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.y=(double) ReadBlobLSBLong(image)/BMP_DENOM; bmp_info.blue_primary.z=(double) ReadBlobLSBLong(image)/BMP_DENOM; gamma=bmp_info.red_primary.x+bmp_info.red_primary.y+ bmp_info.red_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.red_primary.x*=gamma; bmp_info.red_primary.y*=gamma; image->chromaticity.red_primary.x=bmp_info.red_primary.x; image->chromaticity.red_primary.y=bmp_info.red_primary.y; gamma=bmp_info.green_primary.x+bmp_info.green_primary.y+ bmp_info.green_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.green_primary.x*=gamma; bmp_info.green_primary.y*=gamma; image->chromaticity.green_primary.x=bmp_info.green_primary.x; image->chromaticity.green_primary.y=bmp_info.green_primary.y; gamma=bmp_info.blue_primary.x+bmp_info.blue_primary.y+ bmp_info.blue_primary.z; gamma=PerceptibleReciprocal(gamma); bmp_info.blue_primary.x*=gamma; bmp_info.blue_primary.y*=gamma; image->chromaticity.blue_primary.x=bmp_info.blue_primary.x; image->chromaticity.blue_primary.y=bmp_info.blue_primary.y; /* Decode 16^16 fixed point formatted gamma_scales. */ bmp_info.gamma_scale.x=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.y=(double) ReadBlobLSBLong(image)/0x10000; bmp_info.gamma_scale.z=(double) ReadBlobLSBLong(image)/0x10000; /* Compute a single gamma from the BMP 3-channel gamma. */ image->gamma=(bmp_info.gamma_scale.x+bmp_info.gamma_scale.y+ bmp_info.gamma_scale.z)/3.0; } else (void) CopyMagickString(image->magick,"BMP3",MagickPathExtent); if (bmp_info.size > 108) { size_t intent; /* Read BMP Version 5 color management information. */ intent=ReadBlobLSBLong(image); switch ((int) intent) { case LCS_GM_BUSINESS: { image->rendering_intent=SaturationIntent; break; } case LCS_GM_GRAPHICS: { image->rendering_intent=RelativeIntent; break; } case LCS_GM_IMAGES: { image->rendering_intent=PerceptualIntent; break; } case LCS_GM_ABS_COLORIMETRIC: { image->rendering_intent=AbsoluteIntent; break; } } profile_data=(MagickOffsetType)ReadBlobLSBLong(image); profile_size=(MagickOffsetType)ReadBlobLSBLong(image); (void) ReadBlobLSBLong(image); /* Reserved byte */ } } if ((MagickSizeType) bmp_info.file_size > GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError, "LengthAndFilesizeDoNotMatch","`%s'",image->filename); else if ((MagickSizeType) bmp_info.file_size < GetBlobSize(image)) (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"LengthAndFilesizeDoNotMatch","`%s'", image->filename); if (bmp_info.width <= 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.height == 0) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); if (bmp_info.planes != 1) ThrowReaderException(CorruptImageError,"StaticPlanesValueNotEqualToOne"); if ((bmp_info.bits_per_pixel != 1) && (bmp_info.bits_per_pixel != 4) && (bmp_info.bits_per_pixel != 8) && (bmp_info.bits_per_pixel != 16) && (bmp_info.bits_per_pixel != 24) && (bmp_info.bits_per_pixel != 32)) ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel"); if (bmp_info.bits_per_pixel < 16 && bmp_info.number_colors > (1U << bmp_info.bits_per_pixel)) ThrowReaderException(CorruptImageError,"UnrecognizedNumberOfColors"); if ((bmp_info.compression == 1) && (bmp_info.bits_per_pixel != 8)) ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel"); if ((bmp_info.compression == 2) && (bmp_info.bits_per_pixel != 4)) ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel"); if ((bmp_info.compression == 3) && (bmp_info.bits_per_pixel < 16)) ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel"); switch (bmp_info.compression) { case BI_RGB: image->compression=NoCompression; break; case BI_RLE8: case BI_RLE4: image->compression=RLECompression; break; case BI_BITFIELDS: break; case BI_JPEG: ThrowReaderException(CoderError,"JPEGCompressNotSupported"); case BI_PNG: ThrowReaderException(CoderError,"PNGCompressNotSupported"); default: ThrowReaderException(CorruptImageError,"UnrecognizedImageCompression"); } image->columns=(size_t) MagickAbsoluteValue(bmp_info.width); image->rows=(size_t) MagickAbsoluteValue(bmp_info.height); image->depth=bmp_info.bits_per_pixel <= 8 ? bmp_info.bits_per_pixel : 8; image->alpha_trait=((bmp_info.alpha_mask != 0) && (bmp_info.compression == BI_BITFIELDS)) ? BlendPixelTrait : UndefinedPixelTrait; if (bmp_info.bits_per_pixel < 16) { size_t one; image->storage_class=PseudoClass; image->colors=bmp_info.number_colors; one=1; if (image->colors == 0) image->colors=one << bmp_info.bits_per_pixel; } image->resolution.x=(double) bmp_info.x_pixels/100.0; image->resolution.y=(double) bmp_info.y_pixels/100.0; image->units=PixelsPerCentimeterResolution; if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; size_t packet_size; /* Read BMP raster colormap. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading colormap of %.20g colors",(double) image->colors); if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if ((bmp_info.size == 12) || (bmp_info.size == 64)) packet_size=3; else packet_size=4; offset=SeekBlob(image,start_position+14+bmp_info.size,SEEK_SET); if (offset < 0) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } count=ReadBlob(image,packet_size*image->colors,bmp_colormap); if (count != (ssize_t) (packet_size*image->colors)) { bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=bmp_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum(*p++); image->colormap[i].green=(MagickRealType) ScaleCharToQuantum(*p++); image->colormap[i].red=(MagickRealType) ScaleCharToQuantum(*p++); if (packet_size == 4) p++; } bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } /* Read image data. */ if (bmp_info.offset_bits == offset_bits) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); offset_bits=bmp_info.offset_bits; offset=SeekBlob(image,start_position+bmp_info.offset_bits,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (bmp_info.compression == BI_RLE4) bmp_info.bits_per_pixel<<=1; bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); length=(size_t) bytes_per_line*image->rows; if ((MagickSizeType) (length/256) > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); if ((bmp_info.compression == BI_RGB) || (bmp_info.compression == BI_BITFIELDS)) { pixel_info=AcquireVirtualMemory(image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading pixels (%.20g bytes)",(double) length); count=ReadBlob(image,length,pixels); if (count != (ssize_t) length) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } } else { /* Convert run-length encoded raster pixels. */ pixel_info=AcquireVirtualMemory(image->rows, MagickMax(bytes_per_line,image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); status=DecodeImage(image,bmp_info.compression,pixels, image->columns*image->rows); if (status == MagickFalse) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnableToRunlengthDecodeImage"); } } /* Convert BMP raster image to pixel packets. */ if (bmp_info.compression == BI_RGB) { /* We should ignore the alpha value in BMP3 files but there have been reports about 32 bit files with alpha. We do a quick check to see if the alpha channel contains a value that is not zero (default value). If we find a non zero value we asume the program that wrote the file wants to use the alpha channel. */ if ((image->alpha_trait == UndefinedPixelTrait) && (bmp_info.size == 40) && (bmp_info.bits_per_pixel == 32)) { bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { if (*(p+3) != 0) { image->alpha_trait=BlendPixelTrait; y=-1; break; } p+=4; } } } bmp_info.alpha_mask=image->alpha_trait != UndefinedPixelTrait ? 0xff000000U : 0U; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; if (bmp_info.bits_per_pixel == 16) { /* RGB555. */ bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; } } (void) memset(&shift,0,sizeof(shift)); (void) memset(&quantum_bits,0,sizeof(quantum_bits)); if ((bmp_info.bits_per_pixel == 16) || (bmp_info.bits_per_pixel == 32)) { register unsigned int sample; /* Get shift and quantum bits info from bitfield masks. */ if (bmp_info.red_mask != 0) while (((bmp_info.red_mask << shift.red) & 0x80000000UL) == 0) { shift.red++; if (shift.red >= 32U) break; } if (bmp_info.green_mask != 0) while (((bmp_info.green_mask << shift.green) & 0x80000000UL) == 0) { shift.green++; if (shift.green >= 32U) break; } if (bmp_info.blue_mask != 0) while (((bmp_info.blue_mask << shift.blue) & 0x80000000UL) == 0) { shift.blue++; if (shift.blue >= 32U) break; } if (bmp_info.alpha_mask != 0) while (((bmp_info.alpha_mask << shift.alpha) & 0x80000000UL) == 0) { shift.alpha++; if (shift.alpha >= 32U) break; } sample=shift.red; while (((bmp_info.red_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.red=(MagickRealType) (sample-shift.red); sample=shift.green; while (((bmp_info.green_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.green=(MagickRealType) (sample-shift.green); sample=shift.blue; while (((bmp_info.blue_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.blue=(MagickRealType) (sample-shift.blue); sample=shift.alpha; while (((bmp_info.alpha_mask << sample) & 0x80000000UL) != 0) { sample++; if (sample >= 32U) break; } quantum_bits.alpha=(MagickRealType) (sample-shift.alpha); } switch (bmp_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { for (bit=0; bit < 8; bit++) { index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if ((image->columns % 8) != 0) { for (bit=0; bit < (image->columns % 8); bit++) { index=(Quantum) (((*p) & (0x80 >> bit)) != 0 ? 0x01 : 0x00); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 4: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0x0f),&index, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); ValidateColormapValue(image,(ssize_t) (*p & 0x0f),&index,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; } if ((image->columns % 2) != 0) { ValidateColormapValue(image,(ssize_t) ((*p >> 4) & 0xf),&index, exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); p++; x++; } if (x < (ssize_t) image->columns) break; if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 8: { /* Convert PseudoColor scanline. */ if ((bmp_info.compression == BI_RLE8) || (bmp_info.compression == BI_RLE4)) bytes_per_line=image->columns; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=(ssize_t) image->columns; x != 0; --x) { ValidateColormapValue(image,(ssize_t) *p++,&index,exception); SetPixelIndex(image,index,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } (void) SyncImage(image,exception); break; } case 16: { unsigned int alpha, pixel; /* Convert bitfield encoded 16-bit PseudoColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=2*(image->columns+image->columns % 2); image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=(*p++) << 8; red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 5) red|=((red & 0xe000) >> 5); if (quantum_bits.red <= 8) red|=((red & 0xff00) >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 5) green|=((green & 0xe000) >> 5); if (quantum_bits.green == 6) green|=((green & 0xc000) >> 6); if (quantum_bits.green <= 8) green|=((green & 0xff00) >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 5) blue|=((blue & 0xe000) >> 5); if (quantum_bits.blue <= 8) blue|=((blue & 0xff00) >> 8); SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16; if (quantum_bits.alpha <= 8) alpha|=((alpha & 0xff00) >> 8); SetPixelAlpha(image,ScaleShortToQuantum( (unsigned short) alpha),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectColor scanline. */ bytes_per_line=4*((image->columns*24+31)/32); for (y=(ssize_t) image->rows-1; y >= 0; y--) { p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,OpaqueAlpha,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert bitfield encoded DirectColor scanline. */ if ((bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError, "UnrecognizedImageCompression"); } bytes_per_line=4*(image->columns); for (y=(ssize_t) image->rows-1; y >= 0; y--) { unsigned int alpha, pixel; p=pixels+(image->rows-y-1)*bytes_per_line; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=(unsigned int) (*p++); pixel|=((unsigned int) *p++ << 8); pixel|=((unsigned int) *p++ << 16); pixel|=((unsigned int) *p++ << 24); red=((pixel & bmp_info.red_mask) << shift.red) >> 16; if (quantum_bits.red == 8) red|=(red >> 8); green=((pixel & bmp_info.green_mask) << shift.green) >> 16; if (quantum_bits.green == 8) green|=(green >> 8); blue=((pixel & bmp_info.blue_mask) << shift.blue) >> 16; if (quantum_bits.blue == 8) blue|=(blue >> 8); SetPixelRed(image,ScaleShortToQuantum((unsigned short) red),q); SetPixelGreen(image,ScaleShortToQuantum((unsigned short) green),q); SetPixelBlue(image,ScaleShortToQuantum((unsigned short) blue),q); SetPixelAlpha(image,OpaqueAlpha,q); if (image->alpha_trait != UndefinedPixelTrait) { alpha=((pixel & bmp_info.alpha_mask) << shift.alpha) >> 16; if (quantum_bits.alpha == 8) alpha|=(alpha >> 8); SetPixelAlpha(image,ScaleShortToQuantum( (unsigned short) alpha),q); } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; offset=(MagickOffsetType) (image->rows-y-1); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) (image->rows-y),image->rows); if (status == MagickFalse) break; } } break; } default: { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } } pixel_info=RelinquishVirtualMemory(pixel_info); if (y > 0) break; if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if (bmp_info.height < 0) { Image *flipped_image; /* Correct image orientation. */ flipped_image=FlipImage(image,exception); if (flipped_image != (Image *) NULL) { DuplicateBlob(flipped_image,image); ReplaceImageInList(&image, flipped_image); image=flipped_image; } } /* Read embeded ICC profile */ if ((bmp_info.colorspace == 0x4D424544L) && (profile_data > 0) && (profile_size > 0)) { StringInfo *profile; unsigned char *datum; offset=start_position+14+profile_data; if ((offset < TellBlob(image)) || (SeekBlob(image,offset,SEEK_SET) != offset) || (GetBlobSize(image) < (MagickSizeType) (offset+profile_size))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); profile=AcquireStringInfo((size_t) profile_size); if (profile == (StringInfo *) NULL) ThrowReaderException(CorruptImageError,"MemoryAllocationFailed"); datum=GetStringInfoDatum(profile); if (ReadBlob(image,(size_t) profile_size,datum) == (ssize_t) profile_size) { MagickOffsetType profile_size_orig; /* Trimming padded bytes. */ profile_size_orig=(MagickOffsetType) datum[0] << 24; profile_size_orig|=(MagickOffsetType) datum[1] << 16; profile_size_orig|=(MagickOffsetType) datum[2] << 8; profile_size_orig|=(MagickOffsetType) datum[3]; if (profile_size_orig < profile_size) SetStringInfoLength(profile,(size_t) profile_size_orig); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Profile: ICC, %u bytes",(unsigned int) profile_size_orig); (void) SetImageProfile(image,"icc",profile,exception); } profile=DestroyStringInfo(profile); } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; offset=(MagickOffsetType) bmp_info.ba_offset; if (offset != 0) if ((offset < TellBlob(image)) || (SeekBlob(image,offset,SEEK_SET) != offset)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); *magick='\0'; count=ReadBlob(image,2,magick); if ((count == 2) && (IsBMP(magick,2) != MagickFalse)) { /* Acquire next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { status=MagickFalse; return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } while (IsBMP(magick,2) != MagickFalse); (void) CloseBlob(image); if (status == MagickFalse) return(DestroyImageList(image)); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r B M P I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterBMPImage() adds attributes for the BMP 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 RegisterBMPImage method is: % % size_t RegisterBMPImage(void) % */ ModuleExport size_t RegisterBMPImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("BMP","BMP","Microsoft Windows bitmap image"); entry->decoder=(DecodeImageHandler *) ReadBMPImage; entry->encoder=(EncodeImageHandler *) WriteBMPImage; entry->magick=(IsImageFormatHandler *) IsBMP; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("BMP","BMP2","Microsoft Windows bitmap image (V2)"); entry->decoder=(DecodeImageHandler *) ReadBMPImage; entry->encoder=(EncodeImageHandler *) WriteBMPImage; entry->magick=(IsImageFormatHandler *) IsBMP; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("BMP","BMP3","Microsoft Windows bitmap image (V3)"); entry->decoder=(DecodeImageHandler *) ReadBMPImage; entry->encoder=(EncodeImageHandler *) WriteBMPImage; entry->magick=(IsImageFormatHandler *) IsBMP; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderDecoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r B M P I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterBMPImage() removes format registrations made by the % BMP module from the list of supported formats. % % The format of the UnregisterBMPImage method is: % % UnregisterBMPImage(void) % */ ModuleExport void UnregisterBMPImage(void) { (void) UnregisterMagickInfo("BMP"); (void) UnregisterMagickInfo("BMP2"); (void) UnregisterMagickInfo("BMP3"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e B M P I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteBMPImage() writes an image in Microsoft Windows bitmap encoded % image format, version 3 for Windows or (if the image has a matte channel) % version 4. % % The format of the WriteBMPImage method is: % % MagickBooleanType WriteBMPImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteBMPImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { BMPInfo bmp_info; BMPSubtype bmp_subtype; const char *option; const StringInfo *profile; MagickBooleanType have_color_info, status; MagickOffsetType scene; MemoryInfo *pixel_info; register const Quantum *p; register ssize_t i, x; register unsigned char *q; size_t bytes_per_line, imageListLength, type; ssize_t y; unsigned char *bmp_data, *pixels; MagickOffsetType profile_data, profile_size, profile_size_pad; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); if (((image->columns << 3) != (int) (image->columns << 3)) || ((image->rows << 3) != (int) (image->rows << 3))) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); type=4; if (LocaleCompare(image_info->magick,"BMP2") == 0) type=2; else if (LocaleCompare(image_info->magick,"BMP3") == 0) type=3; option=GetImageOption(image_info,"bmp:format"); if (option != (char *) NULL) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Format=%s",option); if (LocaleCompare(option,"bmp2") == 0) type=2; if (LocaleCompare(option,"bmp3") == 0) type=3; if (LocaleCompare(option,"bmp4") == 0) type=4; } scene=0; imageListLength=GetImageListLength(image); do { /* Initialize BMP raster file header. */ if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) memset(&bmp_info,0,sizeof(bmp_info)); bmp_info.file_size=14+12; if (type > 2) bmp_info.file_size+=28; bmp_info.offset_bits=bmp_info.file_size; bmp_info.compression=BI_RGB; bmp_info.red_mask=0x00ff0000U; bmp_info.green_mask=0x0000ff00U; bmp_info.blue_mask=0x000000ffU; bmp_info.alpha_mask=0xff000000U; bmp_subtype=UndefinedSubtype; if ((image->storage_class == PseudoClass) && (image->colors > 256)) (void) SetImageStorageClass(image,DirectClass,exception); if (image->storage_class != DirectClass) { /* Colormapped BMP raster. */ bmp_info.bits_per_pixel=8; if (image->colors <= 2) bmp_info.bits_per_pixel=1; else if (image->colors <= 16) bmp_info.bits_per_pixel=4; else if (image->colors <= 256) bmp_info.bits_per_pixel=8; if (image_info->compression == RLECompression) bmp_info.bits_per_pixel=8; bmp_info.number_colors=1U << bmp_info.bits_per_pixel; if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageStorageClass(image,DirectClass,exception); else if ((size_t) bmp_info.number_colors < image->colors) (void) SetImageStorageClass(image,DirectClass,exception); else { bmp_info.file_size+=3*(1UL << bmp_info.bits_per_pixel); bmp_info.offset_bits+=3*(1UL << bmp_info.bits_per_pixel); if (type > 2) { bmp_info.file_size+=(1UL << bmp_info.bits_per_pixel); bmp_info.offset_bits+=(1UL << bmp_info.bits_per_pixel); } } } if (image->storage_class == DirectClass) { /* Full color BMP raster. */ bmp_info.number_colors=0; option=GetImageOption(image_info,"bmp:subtype"); if (option != (const char *) NULL) { if (image->alpha_trait != UndefinedPixelTrait) { if (LocaleNCompare(option,"ARGB4444",8) == 0) { bmp_subtype=ARGB4444; bmp_info.red_mask=0x00000f00U; bmp_info.green_mask=0x000000f0U; bmp_info.blue_mask=0x0000000fU; bmp_info.alpha_mask=0x0000f000U; } else if (LocaleNCompare(option,"ARGB1555",8) == 0) { bmp_subtype=ARGB1555; bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; bmp_info.alpha_mask=0x00008000U; } } else { if (LocaleNCompare(option,"RGB555",6) == 0) { bmp_subtype=RGB555; bmp_info.red_mask=0x00007c00U; bmp_info.green_mask=0x000003e0U; bmp_info.blue_mask=0x0000001fU; bmp_info.alpha_mask=0U; } else if (LocaleNCompare(option,"RGB565",6) == 0) { bmp_subtype=RGB565; bmp_info.red_mask=0x0000f800U; bmp_info.green_mask=0x000007e0U; bmp_info.blue_mask=0x0000001fU; bmp_info.alpha_mask=0U; } } } if (bmp_subtype != UndefinedSubtype) { bmp_info.bits_per_pixel=16; bmp_info.compression=BI_BITFIELDS; } else { bmp_info.bits_per_pixel=(unsigned short) ((type > 3) && (image->alpha_trait != UndefinedPixelTrait) ? 32 : 24); bmp_info.compression=(unsigned int) ((type > 3) && (image->alpha_trait != UndefinedPixelTrait) ? BI_BITFIELDS : BI_RGB); if ((type == 3) && (image->alpha_trait != UndefinedPixelTrait)) { option=GetImageOption(image_info,"bmp3:alpha"); if (IsStringTrue(option)) bmp_info.bits_per_pixel=32; } } } bytes_per_line=4*((image->columns*bmp_info.bits_per_pixel+31)/32); bmp_info.ba_offset=0; profile=GetImageProfile(image,"icc"); have_color_info=(image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL) || (image->gamma != 0.0) ? MagickTrue : MagickFalse; if (type == 2) bmp_info.size=12; else if ((type == 3) || ((image->alpha_trait == UndefinedPixelTrait) && (have_color_info == MagickFalse))) { type=3; bmp_info.size=40; } else { int extra_size; bmp_info.size=108; extra_size=68; if ((image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL)) { bmp_info.size=124; extra_size+=16; } bmp_info.file_size+=extra_size; bmp_info.offset_bits+=extra_size; } if (((ssize_t) image->columns != (ssize_t) ((signed int) image->columns)) || ((ssize_t) image->rows != (ssize_t) ((signed int) image->rows))) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); bmp_info.width=(ssize_t) image->columns; bmp_info.height=(ssize_t) image->rows; bmp_info.planes=1; bmp_info.image_size=(unsigned int) (bytes_per_line*image->rows); bmp_info.file_size+=bmp_info.image_size; bmp_info.x_pixels=75*39; bmp_info.y_pixels=75*39; switch (image->units) { case UndefinedResolution: case PixelsPerInchResolution: { bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x/2.54); bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y/2.54); break; } case PixelsPerCentimeterResolution: { bmp_info.x_pixels=(unsigned int) (100.0*image->resolution.x); bmp_info.y_pixels=(unsigned int) (100.0*image->resolution.y); break; } } bmp_info.colors_important=bmp_info.number_colors; /* Convert MIFF to BMP raster pixels. */ pixel_info=AcquireVirtualMemory(image->rows,MagickMax(bytes_per_line, image->columns+256UL)*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); (void) memset(pixels,0,(size_t) bmp_info.image_size); switch (bmp_info.bits_per_pixel) { case 1: { size_t bit, byte; /* Convert PseudoClass image to a BMP monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { ssize_t offset; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; byte|=GetPixelIndex(image,p) != 0 ? 0x01 : 0x00; bit++; if (bit == 8) { *q++=(unsigned char) byte; bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) { *q++=(unsigned char) (byte << (8-bit)); x++; } offset=(ssize_t) (image->columns+7)/8; for (x=offset; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 4: { unsigned int byte, nibble; ssize_t offset; /* Convert PseudoClass image to a BMP monochrome image. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; nibble=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=4; byte|=((unsigned int) GetPixelIndex(image,p) & 0x0f); nibble++; if (nibble == 2) { *q++=(unsigned char) byte; nibble=0; byte=0; } p+=GetPixelChannels(image); } if (nibble != 0) { *q++=(unsigned char) (byte << 4); x++; } offset=(ssize_t) (image->columns+1)/2; for (x=offset; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoClass packet to BMP pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) GetPixelIndex(image,p); p+=GetPixelChannels(image); } for ( ; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 16: { /* Convert DirectClass packet to BMP BGR888. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { unsigned short pixel; pixel=0; if (bmp_subtype == ARGB4444) { pixel=(unsigned short) (ScaleQuantumToAny( GetPixelAlpha(image,p),15) << 12); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelRed(image,p),15) << 8); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelGreen(image,p),15) << 4); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelBlue(image,p),15)); } else if (bmp_subtype == RGB565) { pixel=(unsigned short) (ScaleQuantumToAny( GetPixelRed(image,p),31) << 11); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelGreen(image,p),63) << 5); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelBlue(image,p),31)); } else { if (bmp_subtype == ARGB1555) pixel=(unsigned short) (ScaleQuantumToAny( GetPixelAlpha(image,p),1) << 15); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelRed(image,p),31) << 10); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelGreen(image,p),31) << 5); pixel|=(unsigned short) (ScaleQuantumToAny( GetPixelBlue(image,p),31)); } *((unsigned short *) q)=pixel; q+=2; p+=GetPixelChannels(image); } for (x=2L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 24: { /* Convert DirectClass packet to BMP BGR888. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelRed(image,p)); p+=GetPixelChannels(image); } for (x=3L*(ssize_t) image->columns; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } case 32: { /* Convert DirectClass packet to ARGB8888 pixel. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(image->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) image->columns; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } break; } } if ((type > 2) && (bmp_info.bits_per_pixel == 8)) if (image_info->compression != NoCompression) { MemoryInfo *rle_info; /* Convert run-length encoded raster pixels. */ rle_info=AcquireVirtualMemory((size_t) (2*(bytes_per_line+2)+2), (image->rows+2)*sizeof(*pixels)); if (rle_info == (MemoryInfo *) NULL) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } bmp_data=(unsigned char *) GetVirtualMemoryBlob(rle_info); bmp_info.file_size-=bmp_info.image_size; bmp_info.image_size=(unsigned int) EncodeImage(image,bytes_per_line, pixels,bmp_data); bmp_info.file_size+=bmp_info.image_size; pixel_info=RelinquishVirtualMemory(pixel_info); pixel_info=rle_info; pixels=bmp_data; bmp_info.compression=BI_RLE8; } /* Write BMP for Windows, all versions, 14-byte header. */ if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing BMP version %.20g datastream",(double) type); if (image->storage_class == DirectClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class=DirectClass"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Storage class=PseudoClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image depth=%.20g",(double) image->depth); if (image->alpha_trait != UndefinedPixelTrait) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte=True"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Matte=MagickFalse"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " BMP bits_per_pixel=%.20g",(double) bmp_info.bits_per_pixel); switch ((int) bmp_info.compression) { case BI_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression=BI_RGB"); break; } case BI_RLE8: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression=BI_RLE8"); break; } case BI_BITFIELDS: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression=BI_BITFIELDS"); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Compression=UNKNOWN (%u)",bmp_info.compression); break; } } if (bmp_info.number_colors == 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number_colors=unspecified"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Number_colors=%u",bmp_info.number_colors); } profile_data=0; profile_size=0; profile_size_pad=0; if (profile != (StringInfo *) NULL) { profile_data=(MagickOffsetType) bmp_info.file_size-14; /* from head of BMP info header */ profile_size=(MagickOffsetType) GetStringInfoLength(profile); if ((profile_size % 4) > 0) profile_size_pad=4-(profile_size%4); bmp_info.file_size+=profile_size+profile_size_pad; } (void) WriteBlob(image,2,(unsigned char *) "BM"); (void) WriteBlobLSBLong(image,bmp_info.file_size); (void) WriteBlobLSBLong(image,bmp_info.ba_offset); /* always 0 */ (void) WriteBlobLSBLong(image,bmp_info.offset_bits); if (type == 2) { /* Write 12-byte version 2 bitmap header. */ (void) WriteBlobLSBLong(image,bmp_info.size); (void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.width); (void) WriteBlobLSBSignedShort(image,(signed short) bmp_info.height); (void) WriteBlobLSBShort(image,bmp_info.planes); (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel); } else { /* Write 40-byte version 3+ bitmap header. */ (void) WriteBlobLSBLong(image,bmp_info.size); (void) WriteBlobLSBSignedLong(image,(signed int) bmp_info.width); (void) WriteBlobLSBSignedLong(image,(signed int) bmp_info.height); (void) WriteBlobLSBShort(image,bmp_info.planes); (void) WriteBlobLSBShort(image,bmp_info.bits_per_pixel); (void) WriteBlobLSBLong(image,bmp_info.compression); (void) WriteBlobLSBLong(image,bmp_info.image_size); (void) WriteBlobLSBLong(image,bmp_info.x_pixels); (void) WriteBlobLSBLong(image,bmp_info.y_pixels); (void) WriteBlobLSBLong(image,bmp_info.number_colors); (void) WriteBlobLSBLong(image,bmp_info.colors_important); } if ((type > 3) && ((image->alpha_trait != UndefinedPixelTrait) || (have_color_info != MagickFalse))) { /* Write the rest of the 108-byte BMP Version 4 header. */ (void) WriteBlobLSBLong(image,bmp_info.red_mask); (void) WriteBlobLSBLong(image,bmp_info.green_mask); (void) WriteBlobLSBLong(image,bmp_info.blue_mask); (void) WriteBlobLSBLong(image,bmp_info.alpha_mask); if (profile != (StringInfo *) NULL) (void) WriteBlobLSBLong(image,0x4D424544U); /* PROFILE_EMBEDDED */ else (void) WriteBlobLSBLong(image,0x73524742U); /* sRGB */ (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.red_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.red_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.red_primary.x+ image->chromaticity.red_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.green_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.green_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.green_primary.x+ image->chromaticity.green_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.blue_primary.x*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (image->chromaticity.blue_primary.y*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) ((1.000f-(image->chromaticity.blue_primary.x+ image->chromaticity.blue_primary.y))*0x40000000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.x*0x10000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.y*0x10000)); (void) WriteBlobLSBLong(image,(unsigned int) (bmp_info.gamma_scale.z*0x10000)); if ((image->rendering_intent != UndefinedIntent) || (profile != (StringInfo *) NULL)) { ssize_t intent; switch ((int) image->rendering_intent) { case SaturationIntent: { intent=LCS_GM_BUSINESS; break; } case RelativeIntent: { intent=LCS_GM_GRAPHICS; break; } case PerceptualIntent: { intent=LCS_GM_IMAGES; break; } case AbsoluteIntent: { intent=LCS_GM_ABS_COLORIMETRIC; break; } default: { intent=0; break; } } (void) WriteBlobLSBLong(image,(unsigned int) intent); (void) WriteBlobLSBLong(image,(unsigned int) profile_data); (void) WriteBlobLSBLong(image,(unsigned int) (profile_size+profile_size_pad)); (void) WriteBlobLSBLong(image,0x00); /* reserved */ } } if (image->storage_class == PseudoClass) { unsigned char *bmp_colormap; /* Dump colormap to file. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Colormap: %.20g entries",(double) image->colors); bmp_colormap=(unsigned char *) AcquireQuantumMemory((size_t) (1UL << bmp_info.bits_per_pixel),4*sizeof(*bmp_colormap)); if (bmp_colormap == (unsigned char *) NULL) { pixel_info=RelinquishVirtualMemory(pixel_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } q=bmp_colormap; for (i=0; i < (ssize_t) MagickMin((ssize_t) image->colors,(ssize_t) bmp_info.number_colors); i++) { *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue)); *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green)); *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red)); if (type > 2) *q++=(unsigned char) 0x0; } for ( ; i < (ssize_t) (1UL << bmp_info.bits_per_pixel); i++) { *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; if (type > 2) *q++=(unsigned char) 0x00; } if (type <= 2) (void) WriteBlob(image,(size_t) (3*(1L << bmp_info.bits_per_pixel)), bmp_colormap); else (void) WriteBlob(image,(size_t) (4*(1L << bmp_info.bits_per_pixel)), bmp_colormap); bmp_colormap=(unsigned char *) RelinquishMagickMemory(bmp_colormap); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Pixels: %u bytes",bmp_info.image_size); (void) WriteBlob(image,(size_t) bmp_info.image_size,pixels); if (profile != (StringInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Profile: %g bytes",(double) profile_size+profile_size_pad); (void) WriteBlob(image,(size_t) profile_size,GetStringInfoDatum(profile)); if (profile_size_pad > 0) /* padding for 4 bytes multiple */ (void) WriteBlob(image,(size_t) profile_size_pad,"\0\0\0"); } pixel_info=RelinquishVirtualMemory(pixel_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-399/c/bad_905_0
crossvul-cpp_data_bad_3574_0
/* * Linux NET3: Internet Group Management Protocol [IGMP] * * This code implements the IGMP protocol as defined in RFC1112. There has * been a further revision of this protocol since which is now supported. * * If you have trouble with this module be careful what gcc you have used, * the older version didn't come out right using gcc 2.5.8, the newer one * seems to fall out with gcc 2.6.2. * * Authors: * Alan Cox <alan@lxorguk.ukuu.org.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. * * Fixes: * * Alan Cox : Added lots of __inline__ to optimise * the memory usage of all the tiny little * functions. * Alan Cox : Dumped the header building experiment. * Alan Cox : Minor tweaks ready for multicast routing * and extended IGMP protocol. * Alan Cox : Removed a load of inline directives. Gcc 2.5.8 * writes utterly bogus code otherwise (sigh) * fixed IGMP loopback to behave in the manner * desired by mrouted, fixed the fact it has been * broken since 1.3.6 and cleaned up a few minor * points. * * Chih-Jen Chang : Tried to revise IGMP to Version 2 * Tsu-Sheng Tsao E-mail: chihjenc@scf.usc.edu and tsusheng@scf.usc.edu * The enhancements are mainly based on Steve Deering's * ipmulti-3.5 source code. * Chih-Jen Chang : Added the igmp_get_mrouter_info and * Tsu-Sheng Tsao igmp_set_mrouter_info to keep track of * the mrouted version on that device. * Chih-Jen Chang : Added the max_resp_time parameter to * Tsu-Sheng Tsao igmp_heard_query(). Using this parameter * to identify the multicast router version * and do what the IGMP version 2 specified. * Chih-Jen Chang : Added a timer to revert to IGMP V2 router * Tsu-Sheng Tsao if the specified time expired. * Alan Cox : Stop IGMP from 0.0.0.0 being accepted. * Alan Cox : Use GFP_ATOMIC in the right places. * Christian Daudt : igmp timer wasn't set for local group * memberships but was being deleted, * which caused a "del_timer() called * from %p with timer not initialized\n" * message (960131). * Christian Daudt : removed del_timer from * igmp_timer_expire function (960205). * Christian Daudt : igmp_heard_report now only calls * igmp_timer_expire if tm->running is * true (960216). * Malcolm Beattie : ttl comparison wrong in igmp_rcv made * igmp_heard_query never trigger. Expiry * miscalculation fixed in igmp_heard_query * and random() made to return unsigned to * prevent negative expiry times. * Alexey Kuznetsov: Wrong group leaving behaviour, backport * fix from pending 2.1.x patches. * Alan Cox: Forget to enable FDDI support earlier. * Alexey Kuznetsov: Fixed leaving groups on device down. * Alexey Kuznetsov: Accordance to igmp-v2-06 draft. * David L Stevens: IGMPv3 support, with help from * Vinay Kulkarni */ #include <linux/module.h> #include <linux/slab.h> #include <asm/uaccess.h> #include <asm/system.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/jiffies.h> #include <linux/string.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/in.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <linux/skbuff.h> #include <linux/inetdevice.h> #include <linux/igmp.h> #include <linux/if_arp.h> #include <linux/rtnetlink.h> #include <linux/times.h> #include <net/net_namespace.h> #include <net/arp.h> #include <net/ip.h> #include <net/protocol.h> #include <net/route.h> #include <net/sock.h> #include <net/checksum.h> #include <linux/netfilter_ipv4.h> #ifdef CONFIG_IP_MROUTE #include <linux/mroute.h> #endif #ifdef CONFIG_PROC_FS #include <linux/proc_fs.h> #include <linux/seq_file.h> #endif #define IP_MAX_MEMBERSHIPS 20 #define IP_MAX_MSF 10 #ifdef CONFIG_IP_MULTICAST /* Parameter names and values are taken from igmp-v2-06 draft */ #define IGMP_V1_Router_Present_Timeout (400*HZ) #define IGMP_V2_Router_Present_Timeout (400*HZ) #define IGMP_Unsolicited_Report_Interval (10*HZ) #define IGMP_Query_Response_Interval (10*HZ) #define IGMP_Unsolicited_Report_Count 2 #define IGMP_Initial_Report_Delay (1) /* IGMP_Initial_Report_Delay is not from IGMP specs! * IGMP specs require to report membership immediately after * joining a group, but we delay the first report by a * small interval. It seems more natural and still does not * contradict to specs provided this delay is small enough. */ #define IGMP_V1_SEEN(in_dev) \ (IPV4_DEVCONF_ALL(dev_net(in_dev->dev), FORCE_IGMP_VERSION) == 1 || \ IN_DEV_CONF_GET((in_dev), FORCE_IGMP_VERSION) == 1 || \ ((in_dev)->mr_v1_seen && \ time_before(jiffies, (in_dev)->mr_v1_seen))) #define IGMP_V2_SEEN(in_dev) \ (IPV4_DEVCONF_ALL(dev_net(in_dev->dev), FORCE_IGMP_VERSION) == 2 || \ IN_DEV_CONF_GET((in_dev), FORCE_IGMP_VERSION) == 2 || \ ((in_dev)->mr_v2_seen && \ time_before(jiffies, (in_dev)->mr_v2_seen))) static void igmpv3_add_delrec(struct in_device *in_dev, struct ip_mc_list *im); static void igmpv3_del_delrec(struct in_device *in_dev, __be32 multiaddr); static void igmpv3_clear_delrec(struct in_device *in_dev); static int sf_setstate(struct ip_mc_list *pmc); static void sf_markstate(struct ip_mc_list *pmc); #endif static void ip_mc_clear_src(struct ip_mc_list *pmc); static int ip_mc_add_src(struct in_device *in_dev, __be32 *pmca, int sfmode, int sfcount, __be32 *psfsrc, int delta); static void ip_ma_put(struct ip_mc_list *im) { if (atomic_dec_and_test(&im->refcnt)) { in_dev_put(im->interface); kfree_rcu(im, rcu); } } #define for_each_pmc_rcu(in_dev, pmc) \ for (pmc = rcu_dereference(in_dev->mc_list); \ pmc != NULL; \ pmc = rcu_dereference(pmc->next_rcu)) #define for_each_pmc_rtnl(in_dev, pmc) \ for (pmc = rtnl_dereference(in_dev->mc_list); \ pmc != NULL; \ pmc = rtnl_dereference(pmc->next_rcu)) #ifdef CONFIG_IP_MULTICAST /* * Timer management */ static void igmp_stop_timer(struct ip_mc_list *im) { spin_lock_bh(&im->lock); if (del_timer(&im->timer)) atomic_dec(&im->refcnt); im->tm_running = 0; im->reporter = 0; im->unsolicit_count = 0; spin_unlock_bh(&im->lock); } /* It must be called with locked im->lock */ static void igmp_start_timer(struct ip_mc_list *im, int max_delay) { int tv = net_random() % max_delay; im->tm_running = 1; if (!mod_timer(&im->timer, jiffies+tv+2)) atomic_inc(&im->refcnt); } static void igmp_gq_start_timer(struct in_device *in_dev) { int tv = net_random() % in_dev->mr_maxdelay; in_dev->mr_gq_running = 1; if (!mod_timer(&in_dev->mr_gq_timer, jiffies+tv+2)) in_dev_hold(in_dev); } static void igmp_ifc_start_timer(struct in_device *in_dev, int delay) { int tv = net_random() % delay; if (!mod_timer(&in_dev->mr_ifc_timer, jiffies+tv+2)) in_dev_hold(in_dev); } static void igmp_mod_timer(struct ip_mc_list *im, int max_delay) { spin_lock_bh(&im->lock); im->unsolicit_count = 0; if (del_timer(&im->timer)) { if ((long)(im->timer.expires-jiffies) < max_delay) { add_timer(&im->timer); im->tm_running = 1; spin_unlock_bh(&im->lock); return; } atomic_dec(&im->refcnt); } igmp_start_timer(im, max_delay); spin_unlock_bh(&im->lock); } /* * Send an IGMP report. */ #define IGMP_SIZE (sizeof(struct igmphdr)+sizeof(struct iphdr)+4) static int is_in(struct ip_mc_list *pmc, struct ip_sf_list *psf, int type, int gdeleted, int sdeleted) { switch (type) { case IGMPV3_MODE_IS_INCLUDE: case IGMPV3_MODE_IS_EXCLUDE: if (gdeleted || sdeleted) return 0; if (!(pmc->gsquery && !psf->sf_gsresp)) { if (pmc->sfmode == MCAST_INCLUDE) return 1; /* don't include if this source is excluded * in all filters */ if (psf->sf_count[MCAST_INCLUDE]) return type == IGMPV3_MODE_IS_INCLUDE; return pmc->sfcount[MCAST_EXCLUDE] == psf->sf_count[MCAST_EXCLUDE]; } return 0; case IGMPV3_CHANGE_TO_INCLUDE: if (gdeleted || sdeleted) return 0; return psf->sf_count[MCAST_INCLUDE] != 0; case IGMPV3_CHANGE_TO_EXCLUDE: if (gdeleted || sdeleted) return 0; if (pmc->sfcount[MCAST_EXCLUDE] == 0 || psf->sf_count[MCAST_INCLUDE]) return 0; return pmc->sfcount[MCAST_EXCLUDE] == psf->sf_count[MCAST_EXCLUDE]; case IGMPV3_ALLOW_NEW_SOURCES: if (gdeleted || !psf->sf_crcount) return 0; return (pmc->sfmode == MCAST_INCLUDE) ^ sdeleted; case IGMPV3_BLOCK_OLD_SOURCES: if (pmc->sfmode == MCAST_INCLUDE) return gdeleted || (psf->sf_crcount && sdeleted); return psf->sf_crcount && !gdeleted && !sdeleted; } return 0; } static int igmp_scount(struct ip_mc_list *pmc, int type, int gdeleted, int sdeleted) { struct ip_sf_list *psf; int scount = 0; for (psf=pmc->sources; psf; psf=psf->sf_next) { if (!is_in(pmc, psf, type, gdeleted, sdeleted)) continue; scount++; } return scount; } #define igmp_skb_size(skb) (*(unsigned int *)((skb)->cb)) static struct sk_buff *igmpv3_newpack(struct net_device *dev, int size) { struct sk_buff *skb; struct rtable *rt; struct iphdr *pip; struct igmpv3_report *pig; struct net *net = dev_net(dev); struct flowi4 fl4; while (1) { skb = alloc_skb(size + LL_ALLOCATED_SPACE(dev), GFP_ATOMIC | __GFP_NOWARN); if (skb) break; size >>= 1; if (size < 256) return NULL; } igmp_skb_size(skb) = size; rt = ip_route_output_ports(net, &fl4, NULL, IGMPV3_ALL_MCR, 0, 0, 0, IPPROTO_IGMP, 0, dev->ifindex); if (IS_ERR(rt)) { kfree_skb(skb); return NULL; } skb_dst_set(skb, &rt->dst); skb->dev = dev; skb_reserve(skb, LL_RESERVED_SPACE(dev)); skb_reset_network_header(skb); pip = ip_hdr(skb); skb_put(skb, sizeof(struct iphdr) + 4); pip->version = 4; pip->ihl = (sizeof(struct iphdr)+4)>>2; pip->tos = 0xc0; pip->frag_off = htons(IP_DF); pip->ttl = 1; pip->daddr = fl4.daddr; pip->saddr = fl4.saddr; pip->protocol = IPPROTO_IGMP; pip->tot_len = 0; /* filled in later */ ip_select_ident(pip, &rt->dst, NULL); ((u8*)&pip[1])[0] = IPOPT_RA; ((u8*)&pip[1])[1] = 4; ((u8*)&pip[1])[2] = 0; ((u8*)&pip[1])[3] = 0; skb->transport_header = skb->network_header + sizeof(struct iphdr) + 4; skb_put(skb, sizeof(*pig)); pig = igmpv3_report_hdr(skb); pig->type = IGMPV3_HOST_MEMBERSHIP_REPORT; pig->resv1 = 0; pig->csum = 0; pig->resv2 = 0; pig->ngrec = 0; return skb; } static int igmpv3_sendpack(struct sk_buff *skb) { struct igmphdr *pig = igmp_hdr(skb); const int igmplen = skb->tail - skb->transport_header; pig->csum = ip_compute_csum(igmp_hdr(skb), igmplen); return ip_local_out(skb); } static int grec_size(struct ip_mc_list *pmc, int type, int gdel, int sdel) { return sizeof(struct igmpv3_grec) + 4*igmp_scount(pmc, type, gdel, sdel); } static struct sk_buff *add_grhead(struct sk_buff *skb, struct ip_mc_list *pmc, int type, struct igmpv3_grec **ppgr) { struct net_device *dev = pmc->interface->dev; struct igmpv3_report *pih; struct igmpv3_grec *pgr; if (!skb) skb = igmpv3_newpack(dev, dev->mtu); if (!skb) return NULL; pgr = (struct igmpv3_grec *)skb_put(skb, sizeof(struct igmpv3_grec)); pgr->grec_type = type; pgr->grec_auxwords = 0; pgr->grec_nsrcs = 0; pgr->grec_mca = pmc->multiaddr; pih = igmpv3_report_hdr(skb); pih->ngrec = htons(ntohs(pih->ngrec)+1); *ppgr = pgr; return skb; } #define AVAILABLE(skb) ((skb) ? ((skb)->dev ? igmp_skb_size(skb) - (skb)->len : \ skb_tailroom(skb)) : 0) static struct sk_buff *add_grec(struct sk_buff *skb, struct ip_mc_list *pmc, int type, int gdeleted, int sdeleted) { struct net_device *dev = pmc->interface->dev; struct igmpv3_report *pih; struct igmpv3_grec *pgr = NULL; struct ip_sf_list *psf, *psf_next, *psf_prev, **psf_list; int scount, stotal, first, isquery, truncate; if (pmc->multiaddr == IGMP_ALL_HOSTS) return skb; isquery = type == IGMPV3_MODE_IS_INCLUDE || type == IGMPV3_MODE_IS_EXCLUDE; truncate = type == IGMPV3_MODE_IS_EXCLUDE || type == IGMPV3_CHANGE_TO_EXCLUDE; stotal = scount = 0; psf_list = sdeleted ? &pmc->tomb : &pmc->sources; if (!*psf_list) goto empty_source; pih = skb ? igmpv3_report_hdr(skb) : NULL; /* EX and TO_EX get a fresh packet, if needed */ if (truncate) { if (pih && pih->ngrec && AVAILABLE(skb) < grec_size(pmc, type, gdeleted, sdeleted)) { if (skb) igmpv3_sendpack(skb); skb = igmpv3_newpack(dev, dev->mtu); } } first = 1; psf_prev = NULL; for (psf=*psf_list; psf; psf=psf_next) { __be32 *psrc; psf_next = psf->sf_next; if (!is_in(pmc, psf, type, gdeleted, sdeleted)) { psf_prev = psf; continue; } /* clear marks on query responses */ if (isquery) psf->sf_gsresp = 0; if (AVAILABLE(skb) < sizeof(__be32) + first*sizeof(struct igmpv3_grec)) { if (truncate && !first) break; /* truncate these */ if (pgr) pgr->grec_nsrcs = htons(scount); if (skb) igmpv3_sendpack(skb); skb = igmpv3_newpack(dev, dev->mtu); first = 1; scount = 0; } if (first) { skb = add_grhead(skb, pmc, type, &pgr); first = 0; } if (!skb) return NULL; psrc = (__be32 *)skb_put(skb, sizeof(__be32)); *psrc = psf->sf_inaddr; scount++; stotal++; if ((type == IGMPV3_ALLOW_NEW_SOURCES || type == IGMPV3_BLOCK_OLD_SOURCES) && psf->sf_crcount) { psf->sf_crcount--; if ((sdeleted || gdeleted) && psf->sf_crcount == 0) { if (psf_prev) psf_prev->sf_next = psf->sf_next; else *psf_list = psf->sf_next; kfree(psf); continue; } } psf_prev = psf; } empty_source: if (!stotal) { if (type == IGMPV3_ALLOW_NEW_SOURCES || type == IGMPV3_BLOCK_OLD_SOURCES) return skb; if (pmc->crcount || isquery) { /* make sure we have room for group header */ if (skb && AVAILABLE(skb)<sizeof(struct igmpv3_grec)) { igmpv3_sendpack(skb); skb = NULL; /* add_grhead will get a new one */ } skb = add_grhead(skb, pmc, type, &pgr); } } if (pgr) pgr->grec_nsrcs = htons(scount); if (isquery) pmc->gsquery = 0; /* clear query state on report */ return skb; } static int igmpv3_send_report(struct in_device *in_dev, struct ip_mc_list *pmc) { struct sk_buff *skb = NULL; int type; if (!pmc) { rcu_read_lock(); for_each_pmc_rcu(in_dev, pmc) { if (pmc->multiaddr == IGMP_ALL_HOSTS) continue; spin_lock_bh(&pmc->lock); if (pmc->sfcount[MCAST_EXCLUDE]) type = IGMPV3_MODE_IS_EXCLUDE; else type = IGMPV3_MODE_IS_INCLUDE; skb = add_grec(skb, pmc, type, 0, 0); spin_unlock_bh(&pmc->lock); } rcu_read_unlock(); } else { spin_lock_bh(&pmc->lock); if (pmc->sfcount[MCAST_EXCLUDE]) type = IGMPV3_MODE_IS_EXCLUDE; else type = IGMPV3_MODE_IS_INCLUDE; skb = add_grec(skb, pmc, type, 0, 0); spin_unlock_bh(&pmc->lock); } if (!skb) return 0; return igmpv3_sendpack(skb); } /* * remove zero-count source records from a source filter list */ static void igmpv3_clear_zeros(struct ip_sf_list **ppsf) { struct ip_sf_list *psf_prev, *psf_next, *psf; psf_prev = NULL; for (psf=*ppsf; psf; psf = psf_next) { psf_next = psf->sf_next; if (psf->sf_crcount == 0) { if (psf_prev) psf_prev->sf_next = psf->sf_next; else *ppsf = psf->sf_next; kfree(psf); } else psf_prev = psf; } } static void igmpv3_send_cr(struct in_device *in_dev) { struct ip_mc_list *pmc, *pmc_prev, *pmc_next; struct sk_buff *skb = NULL; int type, dtype; rcu_read_lock(); spin_lock_bh(&in_dev->mc_tomb_lock); /* deleted MCA's */ pmc_prev = NULL; for (pmc=in_dev->mc_tomb; pmc; pmc=pmc_next) { pmc_next = pmc->next; if (pmc->sfmode == MCAST_INCLUDE) { type = IGMPV3_BLOCK_OLD_SOURCES; dtype = IGMPV3_BLOCK_OLD_SOURCES; skb = add_grec(skb, pmc, type, 1, 0); skb = add_grec(skb, pmc, dtype, 1, 1); } if (pmc->crcount) { if (pmc->sfmode == MCAST_EXCLUDE) { type = IGMPV3_CHANGE_TO_INCLUDE; skb = add_grec(skb, pmc, type, 1, 0); } pmc->crcount--; if (pmc->crcount == 0) { igmpv3_clear_zeros(&pmc->tomb); igmpv3_clear_zeros(&pmc->sources); } } if (pmc->crcount == 0 && !pmc->tomb && !pmc->sources) { if (pmc_prev) pmc_prev->next = pmc_next; else in_dev->mc_tomb = pmc_next; in_dev_put(pmc->interface); kfree(pmc); } else pmc_prev = pmc; } spin_unlock_bh(&in_dev->mc_tomb_lock); /* change recs */ for_each_pmc_rcu(in_dev, pmc) { spin_lock_bh(&pmc->lock); if (pmc->sfcount[MCAST_EXCLUDE]) { type = IGMPV3_BLOCK_OLD_SOURCES; dtype = IGMPV3_ALLOW_NEW_SOURCES; } else { type = IGMPV3_ALLOW_NEW_SOURCES; dtype = IGMPV3_BLOCK_OLD_SOURCES; } skb = add_grec(skb, pmc, type, 0, 0); skb = add_grec(skb, pmc, dtype, 0, 1); /* deleted sources */ /* filter mode changes */ if (pmc->crcount) { if (pmc->sfmode == MCAST_EXCLUDE) type = IGMPV3_CHANGE_TO_EXCLUDE; else type = IGMPV3_CHANGE_TO_INCLUDE; skb = add_grec(skb, pmc, type, 0, 0); pmc->crcount--; } spin_unlock_bh(&pmc->lock); } rcu_read_unlock(); if (!skb) return; (void) igmpv3_sendpack(skb); } static int igmp_send_report(struct in_device *in_dev, struct ip_mc_list *pmc, int type) { struct sk_buff *skb; struct iphdr *iph; struct igmphdr *ih; struct rtable *rt; struct net_device *dev = in_dev->dev; struct net *net = dev_net(dev); __be32 group = pmc ? pmc->multiaddr : 0; struct flowi4 fl4; __be32 dst; if (type == IGMPV3_HOST_MEMBERSHIP_REPORT) return igmpv3_send_report(in_dev, pmc); else if (type == IGMP_HOST_LEAVE_MESSAGE) dst = IGMP_ALL_ROUTER; else dst = group; rt = ip_route_output_ports(net, &fl4, NULL, dst, 0, 0, 0, IPPROTO_IGMP, 0, dev->ifindex); if (IS_ERR(rt)) return -1; skb = alloc_skb(IGMP_SIZE+LL_ALLOCATED_SPACE(dev), GFP_ATOMIC); if (skb == NULL) { ip_rt_put(rt); return -1; } skb_dst_set(skb, &rt->dst); skb_reserve(skb, LL_RESERVED_SPACE(dev)); skb_reset_network_header(skb); iph = ip_hdr(skb); skb_put(skb, sizeof(struct iphdr) + 4); iph->version = 4; iph->ihl = (sizeof(struct iphdr)+4)>>2; iph->tos = 0xc0; iph->frag_off = htons(IP_DF); iph->ttl = 1; iph->daddr = dst; iph->saddr = fl4.saddr; iph->protocol = IPPROTO_IGMP; ip_select_ident(iph, &rt->dst, NULL); ((u8*)&iph[1])[0] = IPOPT_RA; ((u8*)&iph[1])[1] = 4; ((u8*)&iph[1])[2] = 0; ((u8*)&iph[1])[3] = 0; ih = (struct igmphdr *)skb_put(skb, sizeof(struct igmphdr)); ih->type = type; ih->code = 0; ih->csum = 0; ih->group = group; ih->csum = ip_compute_csum((void *)ih, sizeof(struct igmphdr)); return ip_local_out(skb); } static void igmp_gq_timer_expire(unsigned long data) { struct in_device *in_dev = (struct in_device *)data; in_dev->mr_gq_running = 0; igmpv3_send_report(in_dev, NULL); __in_dev_put(in_dev); } static void igmp_ifc_timer_expire(unsigned long data) { struct in_device *in_dev = (struct in_device *)data; igmpv3_send_cr(in_dev); if (in_dev->mr_ifc_count) { in_dev->mr_ifc_count--; igmp_ifc_start_timer(in_dev, IGMP_Unsolicited_Report_Interval); } __in_dev_put(in_dev); } static void igmp_ifc_event(struct in_device *in_dev) { if (IGMP_V1_SEEN(in_dev) || IGMP_V2_SEEN(in_dev)) return; in_dev->mr_ifc_count = in_dev->mr_qrv ? in_dev->mr_qrv : IGMP_Unsolicited_Report_Count; igmp_ifc_start_timer(in_dev, 1); } static void igmp_timer_expire(unsigned long data) { struct ip_mc_list *im=(struct ip_mc_list *)data; struct in_device *in_dev = im->interface; spin_lock(&im->lock); im->tm_running = 0; if (im->unsolicit_count) { im->unsolicit_count--; igmp_start_timer(im, IGMP_Unsolicited_Report_Interval); } im->reporter = 1; spin_unlock(&im->lock); if (IGMP_V1_SEEN(in_dev)) igmp_send_report(in_dev, im, IGMP_HOST_MEMBERSHIP_REPORT); else if (IGMP_V2_SEEN(in_dev)) igmp_send_report(in_dev, im, IGMPV2_HOST_MEMBERSHIP_REPORT); else igmp_send_report(in_dev, im, IGMPV3_HOST_MEMBERSHIP_REPORT); ip_ma_put(im); } /* mark EXCLUDE-mode sources */ static int igmp_xmarksources(struct ip_mc_list *pmc, int nsrcs, __be32 *srcs) { struct ip_sf_list *psf; int i, scount; scount = 0; for (psf=pmc->sources; psf; psf=psf->sf_next) { if (scount == nsrcs) break; for (i=0; i<nsrcs; i++) { /* skip inactive filters */ if (psf->sf_count[MCAST_INCLUDE] || pmc->sfcount[MCAST_EXCLUDE] != psf->sf_count[MCAST_EXCLUDE]) continue; if (srcs[i] == psf->sf_inaddr) { scount++; break; } } } pmc->gsquery = 0; if (scount == nsrcs) /* all sources excluded */ return 0; return 1; } static int igmp_marksources(struct ip_mc_list *pmc, int nsrcs, __be32 *srcs) { struct ip_sf_list *psf; int i, scount; if (pmc->sfmode == MCAST_EXCLUDE) return igmp_xmarksources(pmc, nsrcs, srcs); /* mark INCLUDE-mode sources */ scount = 0; for (psf=pmc->sources; psf; psf=psf->sf_next) { if (scount == nsrcs) break; for (i=0; i<nsrcs; i++) if (srcs[i] == psf->sf_inaddr) { psf->sf_gsresp = 1; scount++; break; } } if (!scount) { pmc->gsquery = 0; return 0; } pmc->gsquery = 1; return 1; } static void igmp_heard_report(struct in_device *in_dev, __be32 group) { struct ip_mc_list *im; /* Timers are only set for non-local groups */ if (group == IGMP_ALL_HOSTS) return; rcu_read_lock(); for_each_pmc_rcu(in_dev, im) { if (im->multiaddr == group) { igmp_stop_timer(im); break; } } rcu_read_unlock(); } static void igmp_heard_query(struct in_device *in_dev, struct sk_buff *skb, int len) { struct igmphdr *ih = igmp_hdr(skb); struct igmpv3_query *ih3 = igmpv3_query_hdr(skb); struct ip_mc_list *im; __be32 group = ih->group; int max_delay; int mark = 0; if (len == 8) { if (ih->code == 0) { /* Alas, old v1 router presents here. */ max_delay = IGMP_Query_Response_Interval; in_dev->mr_v1_seen = jiffies + IGMP_V1_Router_Present_Timeout; group = 0; } else { /* v2 router present */ max_delay = ih->code*(HZ/IGMP_TIMER_SCALE); in_dev->mr_v2_seen = jiffies + IGMP_V2_Router_Present_Timeout; } /* cancel the interface change timer */ in_dev->mr_ifc_count = 0; if (del_timer(&in_dev->mr_ifc_timer)) __in_dev_put(in_dev); /* clear deleted report items */ igmpv3_clear_delrec(in_dev); } else if (len < 12) { return; /* ignore bogus packet; freed by caller */ } else if (IGMP_V1_SEEN(in_dev)) { /* This is a v3 query with v1 queriers present */ max_delay = IGMP_Query_Response_Interval; group = 0; } else if (IGMP_V2_SEEN(in_dev)) { /* this is a v3 query with v2 queriers present; * Interpretation of the max_delay code is problematic here. * A real v2 host would use ih_code directly, while v3 has a * different encoding. We use the v3 encoding as more likely * to be intended in a v3 query. */ max_delay = IGMPV3_MRC(ih3->code)*(HZ/IGMP_TIMER_SCALE); } else { /* v3 */ if (!pskb_may_pull(skb, sizeof(struct igmpv3_query))) return; ih3 = igmpv3_query_hdr(skb); if (ih3->nsrcs) { if (!pskb_may_pull(skb, sizeof(struct igmpv3_query) + ntohs(ih3->nsrcs)*sizeof(__be32))) return; ih3 = igmpv3_query_hdr(skb); } max_delay = IGMPV3_MRC(ih3->code)*(HZ/IGMP_TIMER_SCALE); if (!max_delay) max_delay = 1; /* can't mod w/ 0 */ in_dev->mr_maxdelay = max_delay; if (ih3->qrv) in_dev->mr_qrv = ih3->qrv; if (!group) { /* general query */ if (ih3->nsrcs) return; /* no sources allowed */ igmp_gq_start_timer(in_dev); return; } /* mark sources to include, if group & source-specific */ mark = ih3->nsrcs != 0; } /* * - Start the timers in all of our membership records * that the query applies to for the interface on * which the query arrived excl. those that belong * to a "local" group (224.0.0.X) * - For timers already running check if they need to * be reset. * - Use the igmp->igmp_code field as the maximum * delay possible */ rcu_read_lock(); for_each_pmc_rcu(in_dev, im) { int changed; if (group && group != im->multiaddr) continue; if (im->multiaddr == IGMP_ALL_HOSTS) continue; spin_lock_bh(&im->lock); if (im->tm_running) im->gsquery = im->gsquery && mark; else im->gsquery = mark; changed = !im->gsquery || igmp_marksources(im, ntohs(ih3->nsrcs), ih3->srcs); spin_unlock_bh(&im->lock); if (changed) igmp_mod_timer(im, max_delay); } rcu_read_unlock(); } /* called in rcu_read_lock() section */ int igmp_rcv(struct sk_buff *skb) { /* This basically follows the spec line by line -- see RFC1112 */ struct igmphdr *ih; struct in_device *in_dev = __in_dev_get_rcu(skb->dev); int len = skb->len; if (in_dev == NULL) goto drop; if (!pskb_may_pull(skb, sizeof(struct igmphdr))) goto drop; switch (skb->ip_summed) { case CHECKSUM_COMPLETE: if (!csum_fold(skb->csum)) break; /* fall through */ case CHECKSUM_NONE: skb->csum = 0; if (__skb_checksum_complete(skb)) goto drop; } ih = igmp_hdr(skb); switch (ih->type) { case IGMP_HOST_MEMBERSHIP_QUERY: igmp_heard_query(in_dev, skb, len); break; case IGMP_HOST_MEMBERSHIP_REPORT: case IGMPV2_HOST_MEMBERSHIP_REPORT: /* Is it our report looped back? */ if (rt_is_output_route(skb_rtable(skb))) break; /* don't rely on MC router hearing unicast reports */ if (skb->pkt_type == PACKET_MULTICAST || skb->pkt_type == PACKET_BROADCAST) igmp_heard_report(in_dev, ih->group); break; case IGMP_PIM: #ifdef CONFIG_IP_PIMSM_V1 return pim_rcv_v1(skb); #endif case IGMPV3_HOST_MEMBERSHIP_REPORT: case IGMP_DVMRP: case IGMP_TRACE: case IGMP_HOST_LEAVE_MESSAGE: case IGMP_MTRACE: case IGMP_MTRACE_RESP: break; default: break; } drop: kfree_skb(skb); return 0; } #endif /* * Add a filter to a device */ static void ip_mc_filter_add(struct in_device *in_dev, __be32 addr) { char buf[MAX_ADDR_LEN]; struct net_device *dev = in_dev->dev; /* Checking for IFF_MULTICAST here is WRONG-WRONG-WRONG. We will get multicast token leakage, when IFF_MULTICAST is changed. This check should be done in ndo_set_rx_mode routine. Something sort of: if (dev->mc_list && dev->flags&IFF_MULTICAST) { do it; } --ANK */ if (arp_mc_map(addr, buf, dev, 0) == 0) dev_mc_add(dev, buf); } /* * Remove a filter from a device */ static void ip_mc_filter_del(struct in_device *in_dev, __be32 addr) { char buf[MAX_ADDR_LEN]; struct net_device *dev = in_dev->dev; if (arp_mc_map(addr, buf, dev, 0) == 0) dev_mc_del(dev, buf); } #ifdef CONFIG_IP_MULTICAST /* * deleted ip_mc_list manipulation */ static void igmpv3_add_delrec(struct in_device *in_dev, struct ip_mc_list *im) { struct ip_mc_list *pmc; /* this is an "ip_mc_list" for convenience; only the fields below * are actually used. In particular, the refcnt and users are not * used for management of the delete list. Using the same structure * for deleted items allows change reports to use common code with * non-deleted or query-response MCA's. */ pmc = kzalloc(sizeof(*pmc), GFP_KERNEL); if (!pmc) return; spin_lock_bh(&im->lock); pmc->interface = im->interface; in_dev_hold(in_dev); pmc->multiaddr = im->multiaddr; pmc->crcount = in_dev->mr_qrv ? in_dev->mr_qrv : IGMP_Unsolicited_Report_Count; pmc->sfmode = im->sfmode; if (pmc->sfmode == MCAST_INCLUDE) { struct ip_sf_list *psf; pmc->tomb = im->tomb; pmc->sources = im->sources; im->tomb = im->sources = NULL; for (psf=pmc->sources; psf; psf=psf->sf_next) psf->sf_crcount = pmc->crcount; } spin_unlock_bh(&im->lock); spin_lock_bh(&in_dev->mc_tomb_lock); pmc->next = in_dev->mc_tomb; in_dev->mc_tomb = pmc; spin_unlock_bh(&in_dev->mc_tomb_lock); } static void igmpv3_del_delrec(struct in_device *in_dev, __be32 multiaddr) { struct ip_mc_list *pmc, *pmc_prev; struct ip_sf_list *psf, *psf_next; spin_lock_bh(&in_dev->mc_tomb_lock); pmc_prev = NULL; for (pmc=in_dev->mc_tomb; pmc; pmc=pmc->next) { if (pmc->multiaddr == multiaddr) break; pmc_prev = pmc; } if (pmc) { if (pmc_prev) pmc_prev->next = pmc->next; else in_dev->mc_tomb = pmc->next; } spin_unlock_bh(&in_dev->mc_tomb_lock); if (pmc) { for (psf=pmc->tomb; psf; psf=psf_next) { psf_next = psf->sf_next; kfree(psf); } in_dev_put(pmc->interface); kfree(pmc); } } static void igmpv3_clear_delrec(struct in_device *in_dev) { struct ip_mc_list *pmc, *nextpmc; spin_lock_bh(&in_dev->mc_tomb_lock); pmc = in_dev->mc_tomb; in_dev->mc_tomb = NULL; spin_unlock_bh(&in_dev->mc_tomb_lock); for (; pmc; pmc = nextpmc) { nextpmc = pmc->next; ip_mc_clear_src(pmc); in_dev_put(pmc->interface); kfree(pmc); } /* clear dead sources, too */ rcu_read_lock(); for_each_pmc_rcu(in_dev, pmc) { struct ip_sf_list *psf, *psf_next; spin_lock_bh(&pmc->lock); psf = pmc->tomb; pmc->tomb = NULL; spin_unlock_bh(&pmc->lock); for (; psf; psf=psf_next) { psf_next = psf->sf_next; kfree(psf); } } rcu_read_unlock(); } #endif static void igmp_group_dropped(struct ip_mc_list *im) { struct in_device *in_dev = im->interface; #ifdef CONFIG_IP_MULTICAST int reporter; #endif if (im->loaded) { im->loaded = 0; ip_mc_filter_del(in_dev, im->multiaddr); } #ifdef CONFIG_IP_MULTICAST if (im->multiaddr == IGMP_ALL_HOSTS) return; reporter = im->reporter; igmp_stop_timer(im); if (!in_dev->dead) { if (IGMP_V1_SEEN(in_dev)) return; if (IGMP_V2_SEEN(in_dev)) { if (reporter) igmp_send_report(in_dev, im, IGMP_HOST_LEAVE_MESSAGE); return; } /* IGMPv3 */ igmpv3_add_delrec(in_dev, im); igmp_ifc_event(in_dev); } #endif } static void igmp_group_added(struct ip_mc_list *im) { struct in_device *in_dev = im->interface; if (im->loaded == 0) { im->loaded = 1; ip_mc_filter_add(in_dev, im->multiaddr); } #ifdef CONFIG_IP_MULTICAST if (im->multiaddr == IGMP_ALL_HOSTS) return; if (in_dev->dead) return; if (IGMP_V1_SEEN(in_dev) || IGMP_V2_SEEN(in_dev)) { spin_lock_bh(&im->lock); igmp_start_timer(im, IGMP_Initial_Report_Delay); spin_unlock_bh(&im->lock); return; } /* else, v3 */ im->crcount = in_dev->mr_qrv ? in_dev->mr_qrv : IGMP_Unsolicited_Report_Count; igmp_ifc_event(in_dev); #endif } /* * Multicast list managers */ /* * A socket has joined a multicast group on device dev. */ void ip_mc_inc_group(struct in_device *in_dev, __be32 addr) { struct ip_mc_list *im; ASSERT_RTNL(); for_each_pmc_rtnl(in_dev, im) { if (im->multiaddr == addr) { im->users++; ip_mc_add_src(in_dev, &addr, MCAST_EXCLUDE, 0, NULL, 0); goto out; } } im = kzalloc(sizeof(*im), GFP_KERNEL); if (!im) goto out; im->users = 1; im->interface = in_dev; in_dev_hold(in_dev); im->multiaddr = addr; /* initial mode is (EX, empty) */ im->sfmode = MCAST_EXCLUDE; im->sfcount[MCAST_EXCLUDE] = 1; atomic_set(&im->refcnt, 1); spin_lock_init(&im->lock); #ifdef CONFIG_IP_MULTICAST setup_timer(&im->timer, &igmp_timer_expire, (unsigned long)im); im->unsolicit_count = IGMP_Unsolicited_Report_Count; #endif im->next_rcu = in_dev->mc_list; in_dev->mc_count++; RCU_INIT_POINTER(in_dev->mc_list, im); #ifdef CONFIG_IP_MULTICAST igmpv3_del_delrec(in_dev, im->multiaddr); #endif igmp_group_added(im); if (!in_dev->dead) ip_rt_multicast_event(in_dev); out: return; } EXPORT_SYMBOL(ip_mc_inc_group); /* * Resend IGMP JOIN report; used for bonding. * Called with rcu_read_lock() */ void ip_mc_rejoin_groups(struct in_device *in_dev) { #ifdef CONFIG_IP_MULTICAST struct ip_mc_list *im; int type; for_each_pmc_rcu(in_dev, im) { if (im->multiaddr == IGMP_ALL_HOSTS) continue; /* a failover is happening and switches * must be notified immediately */ if (IGMP_V1_SEEN(in_dev)) type = IGMP_HOST_MEMBERSHIP_REPORT; else if (IGMP_V2_SEEN(in_dev)) type = IGMPV2_HOST_MEMBERSHIP_REPORT; else type = IGMPV3_HOST_MEMBERSHIP_REPORT; igmp_send_report(in_dev, im, type); } #endif } EXPORT_SYMBOL(ip_mc_rejoin_groups); /* * A socket has left a multicast group on device dev */ void ip_mc_dec_group(struct in_device *in_dev, __be32 addr) { struct ip_mc_list *i; struct ip_mc_list __rcu **ip; ASSERT_RTNL(); for (ip = &in_dev->mc_list; (i = rtnl_dereference(*ip)) != NULL; ip = &i->next_rcu) { if (i->multiaddr == addr) { if (--i->users == 0) { *ip = i->next_rcu; in_dev->mc_count--; igmp_group_dropped(i); ip_mc_clear_src(i); if (!in_dev->dead) ip_rt_multicast_event(in_dev); ip_ma_put(i); return; } break; } } } EXPORT_SYMBOL(ip_mc_dec_group); /* Device changing type */ void ip_mc_unmap(struct in_device *in_dev) { struct ip_mc_list *pmc; ASSERT_RTNL(); for_each_pmc_rtnl(in_dev, pmc) igmp_group_dropped(pmc); } void ip_mc_remap(struct in_device *in_dev) { struct ip_mc_list *pmc; ASSERT_RTNL(); for_each_pmc_rtnl(in_dev, pmc) igmp_group_added(pmc); } /* Device going down */ void ip_mc_down(struct in_device *in_dev) { struct ip_mc_list *pmc; ASSERT_RTNL(); for_each_pmc_rtnl(in_dev, pmc) igmp_group_dropped(pmc); #ifdef CONFIG_IP_MULTICAST in_dev->mr_ifc_count = 0; if (del_timer(&in_dev->mr_ifc_timer)) __in_dev_put(in_dev); in_dev->mr_gq_running = 0; if (del_timer(&in_dev->mr_gq_timer)) __in_dev_put(in_dev); igmpv3_clear_delrec(in_dev); #endif ip_mc_dec_group(in_dev, IGMP_ALL_HOSTS); } void ip_mc_init_dev(struct in_device *in_dev) { ASSERT_RTNL(); in_dev->mc_tomb = NULL; #ifdef CONFIG_IP_MULTICAST in_dev->mr_gq_running = 0; setup_timer(&in_dev->mr_gq_timer, igmp_gq_timer_expire, (unsigned long)in_dev); in_dev->mr_ifc_count = 0; in_dev->mc_count = 0; setup_timer(&in_dev->mr_ifc_timer, igmp_ifc_timer_expire, (unsigned long)in_dev); in_dev->mr_qrv = IGMP_Unsolicited_Report_Count; #endif spin_lock_init(&in_dev->mc_tomb_lock); } /* Device going up */ void ip_mc_up(struct in_device *in_dev) { struct ip_mc_list *pmc; ASSERT_RTNL(); ip_mc_inc_group(in_dev, IGMP_ALL_HOSTS); for_each_pmc_rtnl(in_dev, pmc) igmp_group_added(pmc); } /* * Device is about to be destroyed: clean up. */ void ip_mc_destroy_dev(struct in_device *in_dev) { struct ip_mc_list *i; ASSERT_RTNL(); /* Deactivate timers */ ip_mc_down(in_dev); while ((i = rtnl_dereference(in_dev->mc_list)) != NULL) { in_dev->mc_list = i->next_rcu; in_dev->mc_count--; /* We've dropped the groups in ip_mc_down already */ ip_mc_clear_src(i); ip_ma_put(i); } } /* RTNL is locked */ static struct in_device *ip_mc_find_dev(struct net *net, struct ip_mreqn *imr) { struct net_device *dev = NULL; struct in_device *idev = NULL; if (imr->imr_ifindex) { idev = inetdev_by_index(net, imr->imr_ifindex); return idev; } if (imr->imr_address.s_addr) { dev = __ip_dev_find(net, imr->imr_address.s_addr, false); if (!dev) return NULL; } if (!dev) { struct rtable *rt = ip_route_output(net, imr->imr_multiaddr.s_addr, 0, 0, 0); if (!IS_ERR(rt)) { dev = rt->dst.dev; ip_rt_put(rt); } } if (dev) { imr->imr_ifindex = dev->ifindex; idev = __in_dev_get_rtnl(dev); } return idev; } /* * Join a socket to a group */ int sysctl_igmp_max_memberships __read_mostly = IP_MAX_MEMBERSHIPS; int sysctl_igmp_max_msf __read_mostly = IP_MAX_MSF; static int ip_mc_del1_src(struct ip_mc_list *pmc, int sfmode, __be32 *psfsrc) { struct ip_sf_list *psf, *psf_prev; int rv = 0; psf_prev = NULL; for (psf=pmc->sources; psf; psf=psf->sf_next) { if (psf->sf_inaddr == *psfsrc) break; psf_prev = psf; } if (!psf || psf->sf_count[sfmode] == 0) { /* source filter not found, or count wrong => bug */ return -ESRCH; } psf->sf_count[sfmode]--; if (psf->sf_count[sfmode] == 0) { ip_rt_multicast_event(pmc->interface); } if (!psf->sf_count[MCAST_INCLUDE] && !psf->sf_count[MCAST_EXCLUDE]) { #ifdef CONFIG_IP_MULTICAST struct in_device *in_dev = pmc->interface; #endif /* no more filters for this source */ if (psf_prev) psf_prev->sf_next = psf->sf_next; else pmc->sources = psf->sf_next; #ifdef CONFIG_IP_MULTICAST if (psf->sf_oldin && !IGMP_V1_SEEN(in_dev) && !IGMP_V2_SEEN(in_dev)) { psf->sf_crcount = in_dev->mr_qrv ? in_dev->mr_qrv : IGMP_Unsolicited_Report_Count; psf->sf_next = pmc->tomb; pmc->tomb = psf; rv = 1; } else #endif kfree(psf); } return rv; } #ifndef CONFIG_IP_MULTICAST #define igmp_ifc_event(x) do { } while (0) #endif static int ip_mc_del_src(struct in_device *in_dev, __be32 *pmca, int sfmode, int sfcount, __be32 *psfsrc, int delta) { struct ip_mc_list *pmc; int changerec = 0; int i, err; if (!in_dev) return -ENODEV; rcu_read_lock(); for_each_pmc_rcu(in_dev, pmc) { if (*pmca == pmc->multiaddr) break; } if (!pmc) { /* MCA not found?? bug */ rcu_read_unlock(); return -ESRCH; } spin_lock_bh(&pmc->lock); rcu_read_unlock(); #ifdef CONFIG_IP_MULTICAST sf_markstate(pmc); #endif if (!delta) { err = -EINVAL; if (!pmc->sfcount[sfmode]) goto out_unlock; pmc->sfcount[sfmode]--; } err = 0; for (i=0; i<sfcount; i++) { int rv = ip_mc_del1_src(pmc, sfmode, &psfsrc[i]); changerec |= rv > 0; if (!err && rv < 0) err = rv; } if (pmc->sfmode == MCAST_EXCLUDE && pmc->sfcount[MCAST_EXCLUDE] == 0 && pmc->sfcount[MCAST_INCLUDE]) { #ifdef CONFIG_IP_MULTICAST struct ip_sf_list *psf; #endif /* filter mode change */ pmc->sfmode = MCAST_INCLUDE; #ifdef CONFIG_IP_MULTICAST pmc->crcount = in_dev->mr_qrv ? in_dev->mr_qrv : IGMP_Unsolicited_Report_Count; in_dev->mr_ifc_count = pmc->crcount; for (psf=pmc->sources; psf; psf = psf->sf_next) psf->sf_crcount = 0; igmp_ifc_event(pmc->interface); } else if (sf_setstate(pmc) || changerec) { igmp_ifc_event(pmc->interface); #endif } out_unlock: spin_unlock_bh(&pmc->lock); return err; } /* * Add multicast single-source filter to the interface list */ static int ip_mc_add1_src(struct ip_mc_list *pmc, int sfmode, __be32 *psfsrc, int delta) { struct ip_sf_list *psf, *psf_prev; psf_prev = NULL; for (psf=pmc->sources; psf; psf=psf->sf_next) { if (psf->sf_inaddr == *psfsrc) break; psf_prev = psf; } if (!psf) { psf = kzalloc(sizeof(*psf), GFP_ATOMIC); if (!psf) return -ENOBUFS; psf->sf_inaddr = *psfsrc; if (psf_prev) { psf_prev->sf_next = psf; } else pmc->sources = psf; } psf->sf_count[sfmode]++; if (psf->sf_count[sfmode] == 1) { ip_rt_multicast_event(pmc->interface); } return 0; } #ifdef CONFIG_IP_MULTICAST static void sf_markstate(struct ip_mc_list *pmc) { struct ip_sf_list *psf; int mca_xcount = pmc->sfcount[MCAST_EXCLUDE]; for (psf=pmc->sources; psf; psf=psf->sf_next) if (pmc->sfcount[MCAST_EXCLUDE]) { psf->sf_oldin = mca_xcount == psf->sf_count[MCAST_EXCLUDE] && !psf->sf_count[MCAST_INCLUDE]; } else psf->sf_oldin = psf->sf_count[MCAST_INCLUDE] != 0; } static int sf_setstate(struct ip_mc_list *pmc) { struct ip_sf_list *psf, *dpsf; int mca_xcount = pmc->sfcount[MCAST_EXCLUDE]; int qrv = pmc->interface->mr_qrv; int new_in, rv; rv = 0; for (psf=pmc->sources; psf; psf=psf->sf_next) { if (pmc->sfcount[MCAST_EXCLUDE]) { new_in = mca_xcount == psf->sf_count[MCAST_EXCLUDE] && !psf->sf_count[MCAST_INCLUDE]; } else new_in = psf->sf_count[MCAST_INCLUDE] != 0; if (new_in) { if (!psf->sf_oldin) { struct ip_sf_list *prev = NULL; for (dpsf=pmc->tomb; dpsf; dpsf=dpsf->sf_next) { if (dpsf->sf_inaddr == psf->sf_inaddr) break; prev = dpsf; } if (dpsf) { if (prev) prev->sf_next = dpsf->sf_next; else pmc->tomb = dpsf->sf_next; kfree(dpsf); } psf->sf_crcount = qrv; rv++; } } else if (psf->sf_oldin) { psf->sf_crcount = 0; /* * add or update "delete" records if an active filter * is now inactive */ for (dpsf=pmc->tomb; dpsf; dpsf=dpsf->sf_next) if (dpsf->sf_inaddr == psf->sf_inaddr) break; if (!dpsf) { dpsf = kmalloc(sizeof(*dpsf), GFP_ATOMIC); if (!dpsf) continue; *dpsf = *psf; /* pmc->lock held by callers */ dpsf->sf_next = pmc->tomb; pmc->tomb = dpsf; } dpsf->sf_crcount = qrv; rv++; } } return rv; } #endif /* * Add multicast source filter list to the interface list */ static int ip_mc_add_src(struct in_device *in_dev, __be32 *pmca, int sfmode, int sfcount, __be32 *psfsrc, int delta) { struct ip_mc_list *pmc; int isexclude; int i, err; if (!in_dev) return -ENODEV; rcu_read_lock(); for_each_pmc_rcu(in_dev, pmc) { if (*pmca == pmc->multiaddr) break; } if (!pmc) { /* MCA not found?? bug */ rcu_read_unlock(); return -ESRCH; } spin_lock_bh(&pmc->lock); rcu_read_unlock(); #ifdef CONFIG_IP_MULTICAST sf_markstate(pmc); #endif isexclude = pmc->sfmode == MCAST_EXCLUDE; if (!delta) pmc->sfcount[sfmode]++; err = 0; for (i=0; i<sfcount; i++) { err = ip_mc_add1_src(pmc, sfmode, &psfsrc[i], delta); if (err) break; } if (err) { int j; if (!delta) pmc->sfcount[sfmode]--; for (j=0; j<i; j++) (void) ip_mc_del1_src(pmc, sfmode, &psfsrc[j]); } else if (isexclude != (pmc->sfcount[MCAST_EXCLUDE] != 0)) { #ifdef CONFIG_IP_MULTICAST struct ip_sf_list *psf; in_dev = pmc->interface; #endif /* filter mode change */ if (pmc->sfcount[MCAST_EXCLUDE]) pmc->sfmode = MCAST_EXCLUDE; else if (pmc->sfcount[MCAST_INCLUDE]) pmc->sfmode = MCAST_INCLUDE; #ifdef CONFIG_IP_MULTICAST /* else no filters; keep old mode for reports */ pmc->crcount = in_dev->mr_qrv ? in_dev->mr_qrv : IGMP_Unsolicited_Report_Count; in_dev->mr_ifc_count = pmc->crcount; for (psf=pmc->sources; psf; psf = psf->sf_next) psf->sf_crcount = 0; igmp_ifc_event(in_dev); } else if (sf_setstate(pmc)) { igmp_ifc_event(in_dev); #endif } spin_unlock_bh(&pmc->lock); return err; } static void ip_mc_clear_src(struct ip_mc_list *pmc) { struct ip_sf_list *psf, *nextpsf; for (psf=pmc->tomb; psf; psf=nextpsf) { nextpsf = psf->sf_next; kfree(psf); } pmc->tomb = NULL; for (psf=pmc->sources; psf; psf=nextpsf) { nextpsf = psf->sf_next; kfree(psf); } pmc->sources = NULL; pmc->sfmode = MCAST_EXCLUDE; pmc->sfcount[MCAST_INCLUDE] = 0; pmc->sfcount[MCAST_EXCLUDE] = 1; } /* * Join a multicast group */ int ip_mc_join_group(struct sock *sk , struct ip_mreqn *imr) { int err; __be32 addr = imr->imr_multiaddr.s_addr; struct ip_mc_socklist *iml = NULL, *i; struct in_device *in_dev; struct inet_sock *inet = inet_sk(sk); struct net *net = sock_net(sk); int ifindex; int count = 0; if (!ipv4_is_multicast(addr)) return -EINVAL; rtnl_lock(); in_dev = ip_mc_find_dev(net, imr); if (!in_dev) { iml = NULL; err = -ENODEV; goto done; } err = -EADDRINUSE; ifindex = imr->imr_ifindex; for_each_pmc_rtnl(inet, i) { if (i->multi.imr_multiaddr.s_addr == addr && i->multi.imr_ifindex == ifindex) goto done; count++; } err = -ENOBUFS; if (count >= sysctl_igmp_max_memberships) goto done; iml = sock_kmalloc(sk, sizeof(*iml), GFP_KERNEL); if (iml == NULL) goto done; memcpy(&iml->multi, imr, sizeof(*imr)); iml->next_rcu = inet->mc_list; iml->sflist = NULL; iml->sfmode = MCAST_EXCLUDE; RCU_INIT_POINTER(inet->mc_list, iml); ip_mc_inc_group(in_dev, addr); err = 0; done: rtnl_unlock(); return err; } EXPORT_SYMBOL(ip_mc_join_group); static int ip_mc_leave_src(struct sock *sk, struct ip_mc_socklist *iml, struct in_device *in_dev) { struct ip_sf_socklist *psf = rtnl_dereference(iml->sflist); int err; if (psf == NULL) { /* any-source empty exclude case */ return ip_mc_del_src(in_dev, &iml->multi.imr_multiaddr.s_addr, iml->sfmode, 0, NULL, 0); } err = ip_mc_del_src(in_dev, &iml->multi.imr_multiaddr.s_addr, iml->sfmode, psf->sl_count, psf->sl_addr, 0); RCU_INIT_POINTER(iml->sflist, NULL); /* decrease mem now to avoid the memleak warning */ atomic_sub(IP_SFLSIZE(psf->sl_max), &sk->sk_omem_alloc); kfree_rcu(psf, rcu); return err; } /* * Ask a socket to leave a group. */ int ip_mc_leave_group(struct sock *sk, struct ip_mreqn *imr) { struct inet_sock *inet = inet_sk(sk); struct ip_mc_socklist *iml; struct ip_mc_socklist __rcu **imlp; struct in_device *in_dev; struct net *net = sock_net(sk); __be32 group = imr->imr_multiaddr.s_addr; u32 ifindex; int ret = -EADDRNOTAVAIL; rtnl_lock(); in_dev = ip_mc_find_dev(net, imr); ifindex = imr->imr_ifindex; for (imlp = &inet->mc_list; (iml = rtnl_dereference(*imlp)) != NULL; imlp = &iml->next_rcu) { if (iml->multi.imr_multiaddr.s_addr != group) continue; if (ifindex) { if (iml->multi.imr_ifindex != ifindex) continue; } else if (imr->imr_address.s_addr && imr->imr_address.s_addr != iml->multi.imr_address.s_addr) continue; (void) ip_mc_leave_src(sk, iml, in_dev); *imlp = iml->next_rcu; if (in_dev) ip_mc_dec_group(in_dev, group); rtnl_unlock(); /* decrease mem now to avoid the memleak warning */ atomic_sub(sizeof(*iml), &sk->sk_omem_alloc); kfree_rcu(iml, rcu); return 0; } if (!in_dev) ret = -ENODEV; rtnl_unlock(); return ret; } int ip_mc_source(int add, int omode, struct sock *sk, struct ip_mreq_source *mreqs, int ifindex) { int err; struct ip_mreqn imr; __be32 addr = mreqs->imr_multiaddr; struct ip_mc_socklist *pmc; struct in_device *in_dev = NULL; struct inet_sock *inet = inet_sk(sk); struct ip_sf_socklist *psl; struct net *net = sock_net(sk); int leavegroup = 0; int i, j, rv; if (!ipv4_is_multicast(addr)) return -EINVAL; rtnl_lock(); imr.imr_multiaddr.s_addr = mreqs->imr_multiaddr; imr.imr_address.s_addr = mreqs->imr_interface; imr.imr_ifindex = ifindex; in_dev = ip_mc_find_dev(net, &imr); if (!in_dev) { err = -ENODEV; goto done; } err = -EADDRNOTAVAIL; for_each_pmc_rtnl(inet, pmc) { if ((pmc->multi.imr_multiaddr.s_addr == imr.imr_multiaddr.s_addr) && (pmc->multi.imr_ifindex == imr.imr_ifindex)) break; } if (!pmc) { /* must have a prior join */ err = -EINVAL; goto done; } /* if a source filter was set, must be the same mode as before */ if (pmc->sflist) { if (pmc->sfmode != omode) { err = -EINVAL; goto done; } } else if (pmc->sfmode != omode) { /* allow mode switches for empty-set filters */ ip_mc_add_src(in_dev, &mreqs->imr_multiaddr, omode, 0, NULL, 0); ip_mc_del_src(in_dev, &mreqs->imr_multiaddr, pmc->sfmode, 0, NULL, 0); pmc->sfmode = omode; } psl = rtnl_dereference(pmc->sflist); if (!add) { if (!psl) goto done; /* err = -EADDRNOTAVAIL */ rv = !0; for (i=0; i<psl->sl_count; i++) { rv = memcmp(&psl->sl_addr[i], &mreqs->imr_sourceaddr, sizeof(__be32)); if (rv == 0) break; } if (rv) /* source not found */ goto done; /* err = -EADDRNOTAVAIL */ /* special case - (INCLUDE, empty) == LEAVE_GROUP */ if (psl->sl_count == 1 && omode == MCAST_INCLUDE) { leavegroup = 1; goto done; } /* update the interface filter */ ip_mc_del_src(in_dev, &mreqs->imr_multiaddr, omode, 1, &mreqs->imr_sourceaddr, 1); for (j=i+1; j<psl->sl_count; j++) psl->sl_addr[j-1] = psl->sl_addr[j]; psl->sl_count--; err = 0; goto done; } /* else, add a new source to the filter */ if (psl && psl->sl_count >= sysctl_igmp_max_msf) { err = -ENOBUFS; goto done; } if (!psl || psl->sl_count == psl->sl_max) { struct ip_sf_socklist *newpsl; int count = IP_SFBLOCK; if (psl) count += psl->sl_max; newpsl = sock_kmalloc(sk, IP_SFLSIZE(count), GFP_KERNEL); if (!newpsl) { err = -ENOBUFS; goto done; } newpsl->sl_max = count; newpsl->sl_count = count - IP_SFBLOCK; if (psl) { for (i=0; i<psl->sl_count; i++) newpsl->sl_addr[i] = psl->sl_addr[i]; /* decrease mem now to avoid the memleak warning */ atomic_sub(IP_SFLSIZE(psl->sl_max), &sk->sk_omem_alloc); kfree_rcu(psl, rcu); } RCU_INIT_POINTER(pmc->sflist, newpsl); psl = newpsl; } rv = 1; /* > 0 for insert logic below if sl_count is 0 */ for (i=0; i<psl->sl_count; i++) { rv = memcmp(&psl->sl_addr[i], &mreqs->imr_sourceaddr, sizeof(__be32)); if (rv == 0) break; } if (rv == 0) /* address already there is an error */ goto done; for (j=psl->sl_count-1; j>=i; j--) psl->sl_addr[j+1] = psl->sl_addr[j]; psl->sl_addr[i] = mreqs->imr_sourceaddr; psl->sl_count++; err = 0; /* update the interface list */ ip_mc_add_src(in_dev, &mreqs->imr_multiaddr, omode, 1, &mreqs->imr_sourceaddr, 1); done: rtnl_unlock(); if (leavegroup) return ip_mc_leave_group(sk, &imr); return err; } int ip_mc_msfilter(struct sock *sk, struct ip_msfilter *msf, int ifindex) { int err = 0; struct ip_mreqn imr; __be32 addr = msf->imsf_multiaddr; struct ip_mc_socklist *pmc; struct in_device *in_dev; struct inet_sock *inet = inet_sk(sk); struct ip_sf_socklist *newpsl, *psl; struct net *net = sock_net(sk); int leavegroup = 0; if (!ipv4_is_multicast(addr)) return -EINVAL; if (msf->imsf_fmode != MCAST_INCLUDE && msf->imsf_fmode != MCAST_EXCLUDE) return -EINVAL; rtnl_lock(); imr.imr_multiaddr.s_addr = msf->imsf_multiaddr; imr.imr_address.s_addr = msf->imsf_interface; imr.imr_ifindex = ifindex; in_dev = ip_mc_find_dev(net, &imr); if (!in_dev) { err = -ENODEV; goto done; } /* special case - (INCLUDE, empty) == LEAVE_GROUP */ if (msf->imsf_fmode == MCAST_INCLUDE && msf->imsf_numsrc == 0) { leavegroup = 1; goto done; } for_each_pmc_rtnl(inet, pmc) { if (pmc->multi.imr_multiaddr.s_addr == msf->imsf_multiaddr && pmc->multi.imr_ifindex == imr.imr_ifindex) break; } if (!pmc) { /* must have a prior join */ err = -EINVAL; goto done; } if (msf->imsf_numsrc) { newpsl = sock_kmalloc(sk, IP_SFLSIZE(msf->imsf_numsrc), GFP_KERNEL); if (!newpsl) { err = -ENOBUFS; goto done; } newpsl->sl_max = newpsl->sl_count = msf->imsf_numsrc; memcpy(newpsl->sl_addr, msf->imsf_slist, msf->imsf_numsrc * sizeof(msf->imsf_slist[0])); err = ip_mc_add_src(in_dev, &msf->imsf_multiaddr, msf->imsf_fmode, newpsl->sl_count, newpsl->sl_addr, 0); if (err) { sock_kfree_s(sk, newpsl, IP_SFLSIZE(newpsl->sl_max)); goto done; } } else { newpsl = NULL; (void) ip_mc_add_src(in_dev, &msf->imsf_multiaddr, msf->imsf_fmode, 0, NULL, 0); } psl = rtnl_dereference(pmc->sflist); if (psl) { (void) ip_mc_del_src(in_dev, &msf->imsf_multiaddr, pmc->sfmode, psl->sl_count, psl->sl_addr, 0); /* decrease mem now to avoid the memleak warning */ atomic_sub(IP_SFLSIZE(psl->sl_max), &sk->sk_omem_alloc); kfree_rcu(psl, rcu); } else (void) ip_mc_del_src(in_dev, &msf->imsf_multiaddr, pmc->sfmode, 0, NULL, 0); RCU_INIT_POINTER(pmc->sflist, newpsl); pmc->sfmode = msf->imsf_fmode; err = 0; done: rtnl_unlock(); if (leavegroup) err = ip_mc_leave_group(sk, &imr); return err; } int ip_mc_msfget(struct sock *sk, struct ip_msfilter *msf, struct ip_msfilter __user *optval, int __user *optlen) { int err, len, count, copycount; struct ip_mreqn imr; __be32 addr = msf->imsf_multiaddr; struct ip_mc_socklist *pmc; struct in_device *in_dev; struct inet_sock *inet = inet_sk(sk); struct ip_sf_socklist *psl; struct net *net = sock_net(sk); if (!ipv4_is_multicast(addr)) return -EINVAL; rtnl_lock(); imr.imr_multiaddr.s_addr = msf->imsf_multiaddr; imr.imr_address.s_addr = msf->imsf_interface; imr.imr_ifindex = 0; in_dev = ip_mc_find_dev(net, &imr); if (!in_dev) { err = -ENODEV; goto done; } err = -EADDRNOTAVAIL; for_each_pmc_rtnl(inet, pmc) { if (pmc->multi.imr_multiaddr.s_addr == msf->imsf_multiaddr && pmc->multi.imr_ifindex == imr.imr_ifindex) break; } if (!pmc) /* must have a prior join */ goto done; msf->imsf_fmode = pmc->sfmode; psl = rtnl_dereference(pmc->sflist); rtnl_unlock(); if (!psl) { len = 0; count = 0; } else { count = psl->sl_count; } copycount = count < msf->imsf_numsrc ? count : msf->imsf_numsrc; len = copycount * sizeof(psl->sl_addr[0]); msf->imsf_numsrc = count; if (put_user(IP_MSFILTER_SIZE(copycount), optlen) || copy_to_user(optval, msf, IP_MSFILTER_SIZE(0))) { return -EFAULT; } if (len && copy_to_user(&optval->imsf_slist[0], psl->sl_addr, len)) return -EFAULT; return 0; done: rtnl_unlock(); return err; } int ip_mc_gsfget(struct sock *sk, struct group_filter *gsf, struct group_filter __user *optval, int __user *optlen) { int err, i, count, copycount; struct sockaddr_in *psin; __be32 addr; struct ip_mc_socklist *pmc; struct inet_sock *inet = inet_sk(sk); struct ip_sf_socklist *psl; psin = (struct sockaddr_in *)&gsf->gf_group; if (psin->sin_family != AF_INET) return -EINVAL; addr = psin->sin_addr.s_addr; if (!ipv4_is_multicast(addr)) return -EINVAL; rtnl_lock(); err = -EADDRNOTAVAIL; for_each_pmc_rtnl(inet, pmc) { if (pmc->multi.imr_multiaddr.s_addr == addr && pmc->multi.imr_ifindex == gsf->gf_interface) break; } if (!pmc) /* must have a prior join */ goto done; gsf->gf_fmode = pmc->sfmode; psl = rtnl_dereference(pmc->sflist); rtnl_unlock(); count = psl ? psl->sl_count : 0; copycount = count < gsf->gf_numsrc ? count : gsf->gf_numsrc; gsf->gf_numsrc = count; if (put_user(GROUP_FILTER_SIZE(copycount), optlen) || copy_to_user(optval, gsf, GROUP_FILTER_SIZE(0))) { return -EFAULT; } for (i=0; i<copycount; i++) { struct sockaddr_storage ss; psin = (struct sockaddr_in *)&ss; memset(&ss, 0, sizeof(ss)); psin->sin_family = AF_INET; psin->sin_addr.s_addr = psl->sl_addr[i]; if (copy_to_user(&optval->gf_slist[i], &ss, sizeof(ss))) return -EFAULT; } return 0; done: rtnl_unlock(); return err; } /* * check if a multicast source filter allows delivery for a given <src,dst,intf> */ int ip_mc_sf_allow(struct sock *sk, __be32 loc_addr, __be32 rmt_addr, int dif) { struct inet_sock *inet = inet_sk(sk); struct ip_mc_socklist *pmc; struct ip_sf_socklist *psl; int i; int ret; ret = 1; if (!ipv4_is_multicast(loc_addr)) goto out; rcu_read_lock(); for_each_pmc_rcu(inet, pmc) { if (pmc->multi.imr_multiaddr.s_addr == loc_addr && pmc->multi.imr_ifindex == dif) break; } ret = inet->mc_all; if (!pmc) goto unlock; psl = rcu_dereference(pmc->sflist); ret = (pmc->sfmode == MCAST_EXCLUDE); if (!psl) goto unlock; for (i=0; i<psl->sl_count; i++) { if (psl->sl_addr[i] == rmt_addr) break; } ret = 0; if (pmc->sfmode == MCAST_INCLUDE && i >= psl->sl_count) goto unlock; if (pmc->sfmode == MCAST_EXCLUDE && i < psl->sl_count) goto unlock; ret = 1; unlock: rcu_read_unlock(); out: return ret; } /* * A socket is closing. */ void ip_mc_drop_socket(struct sock *sk) { struct inet_sock *inet = inet_sk(sk); struct ip_mc_socklist *iml; struct net *net = sock_net(sk); if (inet->mc_list == NULL) return; rtnl_lock(); while ((iml = rtnl_dereference(inet->mc_list)) != NULL) { struct in_device *in_dev; inet->mc_list = iml->next_rcu; in_dev = inetdev_by_index(net, iml->multi.imr_ifindex); (void) ip_mc_leave_src(sk, iml, in_dev); if (in_dev != NULL) ip_mc_dec_group(in_dev, iml->multi.imr_multiaddr.s_addr); /* decrease mem now to avoid the memleak warning */ atomic_sub(sizeof(*iml), &sk->sk_omem_alloc); kfree_rcu(iml, rcu); } rtnl_unlock(); } /* called with rcu_read_lock() */ int ip_check_mc_rcu(struct in_device *in_dev, __be32 mc_addr, __be32 src_addr, u16 proto) { struct ip_mc_list *im; struct ip_sf_list *psf; int rv = 0; for_each_pmc_rcu(in_dev, im) { if (im->multiaddr == mc_addr) break; } if (im && proto == IPPROTO_IGMP) { rv = 1; } else if (im) { if (src_addr) { for (psf=im->sources; psf; psf=psf->sf_next) { if (psf->sf_inaddr == src_addr) break; } if (psf) rv = psf->sf_count[MCAST_INCLUDE] || psf->sf_count[MCAST_EXCLUDE] != im->sfcount[MCAST_EXCLUDE]; else rv = im->sfcount[MCAST_EXCLUDE] != 0; } else rv = 1; /* unspecified source; tentatively allow */ } return rv; } #if defined(CONFIG_PROC_FS) struct igmp_mc_iter_state { struct seq_net_private p; struct net_device *dev; struct in_device *in_dev; }; #define igmp_mc_seq_private(seq) ((struct igmp_mc_iter_state *)(seq)->private) static inline struct ip_mc_list *igmp_mc_get_first(struct seq_file *seq) { struct net *net = seq_file_net(seq); struct ip_mc_list *im = NULL; struct igmp_mc_iter_state *state = igmp_mc_seq_private(seq); state->in_dev = NULL; for_each_netdev_rcu(net, state->dev) { struct in_device *in_dev; in_dev = __in_dev_get_rcu(state->dev); if (!in_dev) continue; im = rcu_dereference(in_dev->mc_list); if (im) { state->in_dev = in_dev; break; } } return im; } static struct ip_mc_list *igmp_mc_get_next(struct seq_file *seq, struct ip_mc_list *im) { struct igmp_mc_iter_state *state = igmp_mc_seq_private(seq); im = rcu_dereference(im->next_rcu); while (!im) { state->dev = next_net_device_rcu(state->dev); if (!state->dev) { state->in_dev = NULL; break; } state->in_dev = __in_dev_get_rcu(state->dev); if (!state->in_dev) continue; im = rcu_dereference(state->in_dev->mc_list); } return im; } static struct ip_mc_list *igmp_mc_get_idx(struct seq_file *seq, loff_t pos) { struct ip_mc_list *im = igmp_mc_get_first(seq); if (im) while (pos && (im = igmp_mc_get_next(seq, im)) != NULL) --pos; return pos ? NULL : im; } static void *igmp_mc_seq_start(struct seq_file *seq, loff_t *pos) __acquires(rcu) { rcu_read_lock(); return *pos ? igmp_mc_get_idx(seq, *pos - 1) : SEQ_START_TOKEN; } static void *igmp_mc_seq_next(struct seq_file *seq, void *v, loff_t *pos) { struct ip_mc_list *im; if (v == SEQ_START_TOKEN) im = igmp_mc_get_first(seq); else im = igmp_mc_get_next(seq, v); ++*pos; return im; } static void igmp_mc_seq_stop(struct seq_file *seq, void *v) __releases(rcu) { struct igmp_mc_iter_state *state = igmp_mc_seq_private(seq); state->in_dev = NULL; state->dev = NULL; rcu_read_unlock(); } static int igmp_mc_seq_show(struct seq_file *seq, void *v) { if (v == SEQ_START_TOKEN) seq_puts(seq, "Idx\tDevice : Count Querier\tGroup Users Timer\tReporter\n"); else { struct ip_mc_list *im = (struct ip_mc_list *)v; struct igmp_mc_iter_state *state = igmp_mc_seq_private(seq); char *querier; #ifdef CONFIG_IP_MULTICAST querier = IGMP_V1_SEEN(state->in_dev) ? "V1" : IGMP_V2_SEEN(state->in_dev) ? "V2" : "V3"; #else querier = "NONE"; #endif if (rcu_dereference(state->in_dev->mc_list) == im) { seq_printf(seq, "%d\t%-10s: %5d %7s\n", state->dev->ifindex, state->dev->name, state->in_dev->mc_count, querier); } seq_printf(seq, "\t\t\t\t%08X %5d %d:%08lX\t\t%d\n", im->multiaddr, im->users, im->tm_running, im->tm_running ? jiffies_to_clock_t(im->timer.expires-jiffies) : 0, im->reporter); } return 0; } static const struct seq_operations igmp_mc_seq_ops = { .start = igmp_mc_seq_start, .next = igmp_mc_seq_next, .stop = igmp_mc_seq_stop, .show = igmp_mc_seq_show, }; static int igmp_mc_seq_open(struct inode *inode, struct file *file) { return seq_open_net(inode, file, &igmp_mc_seq_ops, sizeof(struct igmp_mc_iter_state)); } static const struct file_operations igmp_mc_seq_fops = { .owner = THIS_MODULE, .open = igmp_mc_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net, }; struct igmp_mcf_iter_state { struct seq_net_private p; struct net_device *dev; struct in_device *idev; struct ip_mc_list *im; }; #define igmp_mcf_seq_private(seq) ((struct igmp_mcf_iter_state *)(seq)->private) static inline struct ip_sf_list *igmp_mcf_get_first(struct seq_file *seq) { struct net *net = seq_file_net(seq); struct ip_sf_list *psf = NULL; struct ip_mc_list *im = NULL; struct igmp_mcf_iter_state *state = igmp_mcf_seq_private(seq); state->idev = NULL; state->im = NULL; for_each_netdev_rcu(net, state->dev) { struct in_device *idev; idev = __in_dev_get_rcu(state->dev); if (unlikely(idev == NULL)) continue; im = rcu_dereference(idev->mc_list); if (likely(im != NULL)) { spin_lock_bh(&im->lock); psf = im->sources; if (likely(psf != NULL)) { state->im = im; state->idev = idev; break; } spin_unlock_bh(&im->lock); } } return psf; } static struct ip_sf_list *igmp_mcf_get_next(struct seq_file *seq, struct ip_sf_list *psf) { struct igmp_mcf_iter_state *state = igmp_mcf_seq_private(seq); psf = psf->sf_next; while (!psf) { spin_unlock_bh(&state->im->lock); state->im = state->im->next; while (!state->im) { state->dev = next_net_device_rcu(state->dev); if (!state->dev) { state->idev = NULL; goto out; } state->idev = __in_dev_get_rcu(state->dev); if (!state->idev) continue; state->im = rcu_dereference(state->idev->mc_list); } if (!state->im) break; spin_lock_bh(&state->im->lock); psf = state->im->sources; } out: return psf; } static struct ip_sf_list *igmp_mcf_get_idx(struct seq_file *seq, loff_t pos) { struct ip_sf_list *psf = igmp_mcf_get_first(seq); if (psf) while (pos && (psf = igmp_mcf_get_next(seq, psf)) != NULL) --pos; return pos ? NULL : psf; } static void *igmp_mcf_seq_start(struct seq_file *seq, loff_t *pos) __acquires(rcu) { rcu_read_lock(); return *pos ? igmp_mcf_get_idx(seq, *pos - 1) : SEQ_START_TOKEN; } static void *igmp_mcf_seq_next(struct seq_file *seq, void *v, loff_t *pos) { struct ip_sf_list *psf; if (v == SEQ_START_TOKEN) psf = igmp_mcf_get_first(seq); else psf = igmp_mcf_get_next(seq, v); ++*pos; return psf; } static void igmp_mcf_seq_stop(struct seq_file *seq, void *v) __releases(rcu) { struct igmp_mcf_iter_state *state = igmp_mcf_seq_private(seq); if (likely(state->im != NULL)) { spin_unlock_bh(&state->im->lock); state->im = NULL; } state->idev = NULL; state->dev = NULL; rcu_read_unlock(); } static int igmp_mcf_seq_show(struct seq_file *seq, void *v) { struct ip_sf_list *psf = (struct ip_sf_list *)v; struct igmp_mcf_iter_state *state = igmp_mcf_seq_private(seq); if (v == SEQ_START_TOKEN) { seq_printf(seq, "%3s %6s " "%10s %10s %6s %6s\n", "Idx", "Device", "MCA", "SRC", "INC", "EXC"); } else { seq_printf(seq, "%3d %6.6s 0x%08x " "0x%08x %6lu %6lu\n", state->dev->ifindex, state->dev->name, ntohl(state->im->multiaddr), ntohl(psf->sf_inaddr), psf->sf_count[MCAST_INCLUDE], psf->sf_count[MCAST_EXCLUDE]); } return 0; } static const struct seq_operations igmp_mcf_seq_ops = { .start = igmp_mcf_seq_start, .next = igmp_mcf_seq_next, .stop = igmp_mcf_seq_stop, .show = igmp_mcf_seq_show, }; static int igmp_mcf_seq_open(struct inode *inode, struct file *file) { return seq_open_net(inode, file, &igmp_mcf_seq_ops, sizeof(struct igmp_mcf_iter_state)); } static const struct file_operations igmp_mcf_seq_fops = { .owner = THIS_MODULE, .open = igmp_mcf_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net, }; static int __net_init igmp_net_init(struct net *net) { struct proc_dir_entry *pde; pde = proc_net_fops_create(net, "igmp", S_IRUGO, &igmp_mc_seq_fops); if (!pde) goto out_igmp; pde = proc_net_fops_create(net, "mcfilter", S_IRUGO, &igmp_mcf_seq_fops); if (!pde) goto out_mcfilter; return 0; out_mcfilter: proc_net_remove(net, "igmp"); out_igmp: return -ENOMEM; } static void __net_exit igmp_net_exit(struct net *net) { proc_net_remove(net, "mcfilter"); proc_net_remove(net, "igmp"); } static struct pernet_operations igmp_net_ops = { .init = igmp_net_init, .exit = igmp_net_exit, }; int __init igmp_mc_proc_init(void) { return register_pernet_subsys(&igmp_net_ops); } #endif
./CrossVul/dataset_final_sorted/CWE-399/c/bad_3574_0
crossvul-cpp_data_good_2393_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.116 2014/12/16 23:18:40 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 *, uint16_t *); #endif private int dophn_exec(struct magic_set *, int, int, int, off_t, int, size_t, off_t, int, int *, uint16_t *); private int doshn(struct magic_set *, int, int, int, off_t, int, size_t, off_t, int, int, int *, uint16_t *); private size_t donote(struct magic_set *, void *, size_t, size_t, int, int, size_t, int *, uint16_t *); #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 (%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 0x001 #define FLAGS_DID_OS_NOTE 0x002 #define FLAGS_DID_BUILD_ID 0x004 #define FLAGS_DID_CORE_STYLE 0x008 #define FLAGS_DID_NETBSD_PAX 0x010 #define FLAGS_DID_NETBSD_MARCH 0x020 #define FLAGS_DID_NETBSD_CMODEL 0x040 #define FLAGS_DID_NETBSD_UNKNOWN 0x080 #define FLAGS_IS_CORE 0x100 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, uint16_t *notecount) { 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, notecount); 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 int do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags) { if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 && type == NT_GNU_BUILD_ID && (descsz == 16 || descsz == 20)) { uint8_t desc[20]; uint32_t i; *flags |= FLAGS_DID_BUILD_ID; if (file_printf(ms, ", BuildID[%s]=", descsz == 16 ? "md5/uuid" : "sha1") == -1) return 1; (void)memcpy(desc, &nbuf[doff], descsz); for (i = 0; i < descsz; i++) if (file_printf(ms, "%02x", desc[i]) == -1) return 1; return 1; } return 0; } private int do_os_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap, uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags) { if (namesz == 5 && strcmp((char *)&nbuf[noff], "SuSE") == 0 && type == NT_GNU_VERSION && descsz == 2) { *flags |= FLAGS_DID_OS_NOTE; file_printf(ms, ", for SuSE %d.%d", nbuf[doff], nbuf[doff + 1]); return 1; } if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 && type == NT_GNU_VERSION && descsz == 16) { uint32_t desc[4]; (void)memcpy(desc, &nbuf[doff], sizeof(desc)); *flags |= FLAGS_DID_OS_NOTE; if (file_printf(ms, ", for GNU/") == -1) return 1; switch (elf_getu32(swap, desc[0])) { case GNU_OS_LINUX: if (file_printf(ms, "Linux") == -1) return 1; break; case GNU_OS_HURD: if (file_printf(ms, "Hurd") == -1) return 1; break; case GNU_OS_SOLARIS: if (file_printf(ms, "Solaris") == -1) return 1; break; case GNU_OS_KFREEBSD: if (file_printf(ms, "kFreeBSD") == -1) return 1; break; case GNU_OS_KNETBSD: if (file_printf(ms, "kNetBSD") == -1) return 1; break; default: if (file_printf(ms, "<unknown>") == -1) return 1; } if (file_printf(ms, " %d.%d.%d", elf_getu32(swap, desc[1]), elf_getu32(swap, desc[2]), elf_getu32(swap, desc[3])) == -1) return 1; return 1; } if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) { if (type == NT_NETBSD_VERSION && descsz == 4) { *flags |= FLAGS_DID_OS_NOTE; do_note_netbsd_version(ms, swap, &nbuf[doff]); return 1; } } if (namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0) { if (type == NT_FREEBSD_VERSION && descsz == 4) { *flags |= FLAGS_DID_OS_NOTE; do_note_freebsd_version(ms, swap, &nbuf[doff]); return 1; } } if (namesz == 8 && strcmp((char *)&nbuf[noff], "OpenBSD") == 0 && type == NT_OPENBSD_VERSION && descsz == 4) { *flags |= FLAGS_DID_OS_NOTE; if (file_printf(ms, ", for OpenBSD") == -1) return 1; /* Content of note is always 0 */ return 1; } if (namesz == 10 && strcmp((char *)&nbuf[noff], "DragonFly") == 0 && type == NT_DRAGONFLY_VERSION && descsz == 4) { uint32_t desc; *flags |= FLAGS_DID_OS_NOTE; if (file_printf(ms, ", for DragonFly") == -1) return 1; (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 1; return 1; } return 0; } private int do_pax_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap, uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags) { if (namesz == 4 && strcmp((char *)&nbuf[noff], "PaX") == 0 && 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; *flags |= FLAGS_DID_NETBSD_PAX; (void)memcpy(&desc, &nbuf[doff], sizeof(desc)); desc = elf_getu32(swap, desc); if (desc && file_printf(ms, ", PaX: ") == -1) return 1; for (i = 0; i < __arraycount(pax); i++) { if (((1 << i) & desc) == 0) continue; if (file_printf(ms, "%s%s", did++ ? "," : "", pax[i]) == -1) return 1; } return 1; } return 0; } private int do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, int swap, uint32_t namesz, uint32_t descsz, size_t noff, size_t doff, int *flags, size_t size, int clazz) { #ifdef ELFCORE int os_style = -1; /* * 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; } if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) { if (file_printf(ms, ", %s-style", os_style_names[os_style]) == -1) return 1; *flags |= FLAGS_DID_CORE_STYLE; } switch (os_style) { case OS_STYLE_NETBSD: if (type == NT_NETBSD_CORE_PROCINFO) { char sbuf[512]; 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 1; /* * 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 1; *flags |= FLAGS_DID_CORE; return 1; } break; default: if (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 1; *flags |= FLAGS_DID_CORE; return 1; tryanother: ; } } break; } #endif return 0; } 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, uint16_t *notecount) { Elf32_Nhdr nh32; Elf64_Nhdr nh64; size_t noff, doff; uint32_t namesz, descsz; unsigned char *nbuf = CAST(unsigned char *, vbuf); if (*notecount == 0) return 0; --*notecount; 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_OS_NOTE) == 0) { if (do_os_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags)) return size; } if ((*flags & FLAGS_DID_BUILD_ID) == 0) { if (do_bid_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags)) return size; } if ((*flags & FLAGS_DID_NETBSD_PAX) == 0) { if (do_pax_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags)) return size; } if ((*flags & FLAGS_DID_CORE) == 0) { if (do_core_note(ms, nbuf, xnh_type, swap, namesz, descsz, noff, doff, flags, size, clazz)) return size; } if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) { if (descsz > 100) descsz = 100; switch (xnh_type) { case NT_NETBSD_VERSION: return size; case NT_NETBSD_MARCH: if (*flags & FLAGS_DID_NETBSD_MARCH) return size; *flags |= FLAGS_DID_NETBSD_MARCH; if (file_printf(ms, ", compiled for: %.*s", (int)descsz, (const char *)&nbuf[doff]) == -1) return size; break; case NT_NETBSD_CMODEL: if (*flags & FLAGS_DID_NETBSD_CMODEL) return size; *flags |= FLAGS_DID_NETBSD_CMODEL; if (file_printf(ms, ", compiler model: %.*s", (int)descsz, (const char *)&nbuf[doff]) == -1) return size; break; default: if (*flags & FLAGS_DID_NETBSD_UNKNOWN) return size; *flags |= FLAGS_DID_NETBSD_UNKNOWN; if (file_printf(ms, ", note=%u", xnh_type) == -1) return size; break; } return size; } 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 mach, int strtab, int *flags, uint16_t *notecount) { 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, notecount); 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 sh_num, int *flags, uint16_t *notecount) { 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, notecount); 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, notecount; 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-399/c/good_2393_0
crossvul-cpp_data_good_3486_9
/* * Handle unaligned accesses by emulation. * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. * * Copyright (C) 1996, 1998, 1999, 2002 by Ralf Baechle * Copyright (C) 1999 Silicon Graphics, Inc. * * This file contains exception handler for address error exception with the * special capability to execute faulting instructions in software. The * handler does not try to handle the case when the program counter points * to an address not aligned to a word boundary. * * Putting data to unaligned addresses is a bad practice even on Intel where * only the performance is affected. Much worse is that such code is non- * portable. Due to several programs that die on MIPS due to alignment * problems I decided to implement this handler anyway though I originally * didn't intend to do this at all for user code. * * For now I enable fixing of address errors by default to make life easier. * I however intend to disable this somewhen in the future when the alignment * problems with user programs have been fixed. For programmers this is the * right way to go. * * Fixing address errors is a per process option. The option is inherited * across fork(2) and execve(2) calls. If you really want to use the * option in your user programs - I discourage the use of the software * emulation strongly - use the following code in your userland stuff: * * #include <sys/sysmips.h> * * ... * sysmips(MIPS_FIXADE, x); * ... * * The argument x is 0 for disabling software emulation, enabled otherwise. * * Below a little program to play around with this feature. * * #include <stdio.h> * #include <sys/sysmips.h> * * struct foo { * unsigned char bar[8]; * }; * * main(int argc, char *argv[]) * { * struct foo x = {0, 1, 2, 3, 4, 5, 6, 7}; * unsigned int *p = (unsigned int *) (x.bar + 3); * int i; * * if (argc > 1) * sysmips(MIPS_FIXADE, atoi(argv[1])); * * printf("*p = %08lx\n", *p); * * *p = 0xdeadface; * * for(i = 0; i <= 7; i++) * printf("%02x ", x.bar[i]); * printf("\n"); * } * * Coprocessor loads are not supported; I think this case is unimportant * in the practice. * * TODO: Handle ndc (attempted store to doubleword in uncached memory) * exception for the R6000. * A store crossing a page boundary might be executed only partially. * Undo the partial store in this case. */ #include <linux/mm.h> #include <linux/module.h> #include <linux/signal.h> #include <linux/smp.h> #include <linux/sched.h> #include <linux/debugfs.h> #include <linux/perf_event.h> #include <asm/asm.h> #include <asm/branch.h> #include <asm/byteorder.h> #include <asm/cop2.h> #include <asm/inst.h> #include <asm/uaccess.h> #include <asm/system.h> #define STR(x) __STR(x) #define __STR(x) #x enum { UNALIGNED_ACTION_QUIET, UNALIGNED_ACTION_SIGNAL, UNALIGNED_ACTION_SHOW, }; #ifdef CONFIG_DEBUG_FS static u32 unaligned_instructions; static u32 unaligned_action; #else #define unaligned_action UNALIGNED_ACTION_QUIET #endif extern void show_registers(struct pt_regs *regs); static void emulate_load_store_insn(struct pt_regs *regs, void __user *addr, unsigned int __user *pc) { union mips_instruction insn; unsigned long value; unsigned int res; perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, regs, 0); /* * This load never faults. */ __get_user(insn.word, pc); switch (insn.i_format.opcode) { /* * These are instructions that a compiler doesn't generate. We * can assume therefore that the code is MIPS-aware and * really buggy. Emulating these instructions would break the * semantics anyway. */ case ll_op: case lld_op: case sc_op: case scd_op: /* * For these instructions the only way to create an address * error is an attempted access to kernel/supervisor address * space. */ case ldl_op: case ldr_op: case lwl_op: case lwr_op: case sdl_op: case sdr_op: case swl_op: case swr_op: case lb_op: case lbu_op: case sb_op: goto sigbus; /* * The remaining opcodes are the ones that are really of interest. */ case lh_op: if (!access_ok(VERIFY_READ, addr, 2)) goto sigbus; __asm__ __volatile__ (".set\tnoat\n" #ifdef __BIG_ENDIAN "1:\tlb\t%0, 0(%2)\n" "2:\tlbu\t$1, 1(%2)\n\t" #endif #ifdef __LITTLE_ENDIAN "1:\tlb\t%0, 1(%2)\n" "2:\tlbu\t$1, 0(%2)\n\t" #endif "sll\t%0, 0x8\n\t" "or\t%0, $1\n\t" "li\t%1, 0\n" "3:\t.set\tat\n\t" ".section\t.fixup,\"ax\"\n\t" "4:\tli\t%1, %3\n\t" "j\t3b\n\t" ".previous\n\t" ".section\t__ex_table,\"a\"\n\t" STR(PTR)"\t1b, 4b\n\t" STR(PTR)"\t2b, 4b\n\t" ".previous" : "=&r" (value), "=r" (res) : "r" (addr), "i" (-EFAULT)); if (res) goto fault; compute_return_epc(regs); regs->regs[insn.i_format.rt] = value; break; case lw_op: if (!access_ok(VERIFY_READ, addr, 4)) goto sigbus; __asm__ __volatile__ ( #ifdef __BIG_ENDIAN "1:\tlwl\t%0, (%2)\n" "2:\tlwr\t%0, 3(%2)\n\t" #endif #ifdef __LITTLE_ENDIAN "1:\tlwl\t%0, 3(%2)\n" "2:\tlwr\t%0, (%2)\n\t" #endif "li\t%1, 0\n" "3:\t.section\t.fixup,\"ax\"\n\t" "4:\tli\t%1, %3\n\t" "j\t3b\n\t" ".previous\n\t" ".section\t__ex_table,\"a\"\n\t" STR(PTR)"\t1b, 4b\n\t" STR(PTR)"\t2b, 4b\n\t" ".previous" : "=&r" (value), "=r" (res) : "r" (addr), "i" (-EFAULT)); if (res) goto fault; compute_return_epc(regs); regs->regs[insn.i_format.rt] = value; break; case lhu_op: if (!access_ok(VERIFY_READ, addr, 2)) goto sigbus; __asm__ __volatile__ ( ".set\tnoat\n" #ifdef __BIG_ENDIAN "1:\tlbu\t%0, 0(%2)\n" "2:\tlbu\t$1, 1(%2)\n\t" #endif #ifdef __LITTLE_ENDIAN "1:\tlbu\t%0, 1(%2)\n" "2:\tlbu\t$1, 0(%2)\n\t" #endif "sll\t%0, 0x8\n\t" "or\t%0, $1\n\t" "li\t%1, 0\n" "3:\t.set\tat\n\t" ".section\t.fixup,\"ax\"\n\t" "4:\tli\t%1, %3\n\t" "j\t3b\n\t" ".previous\n\t" ".section\t__ex_table,\"a\"\n\t" STR(PTR)"\t1b, 4b\n\t" STR(PTR)"\t2b, 4b\n\t" ".previous" : "=&r" (value), "=r" (res) : "r" (addr), "i" (-EFAULT)); if (res) goto fault; compute_return_epc(regs); regs->regs[insn.i_format.rt] = value; break; case lwu_op: #ifdef CONFIG_64BIT /* * A 32-bit kernel might be running on a 64-bit processor. But * if we're on a 32-bit processor and an i-cache incoherency * or race makes us see a 64-bit instruction here the sdl/sdr * would blow up, so for now we don't handle unaligned 64-bit * instructions on 32-bit kernels. */ if (!access_ok(VERIFY_READ, addr, 4)) goto sigbus; __asm__ __volatile__ ( #ifdef __BIG_ENDIAN "1:\tlwl\t%0, (%2)\n" "2:\tlwr\t%0, 3(%2)\n\t" #endif #ifdef __LITTLE_ENDIAN "1:\tlwl\t%0, 3(%2)\n" "2:\tlwr\t%0, (%2)\n\t" #endif "dsll\t%0, %0, 32\n\t" "dsrl\t%0, %0, 32\n\t" "li\t%1, 0\n" "3:\t.section\t.fixup,\"ax\"\n\t" "4:\tli\t%1, %3\n\t" "j\t3b\n\t" ".previous\n\t" ".section\t__ex_table,\"a\"\n\t" STR(PTR)"\t1b, 4b\n\t" STR(PTR)"\t2b, 4b\n\t" ".previous" : "=&r" (value), "=r" (res) : "r" (addr), "i" (-EFAULT)); if (res) goto fault; compute_return_epc(regs); regs->regs[insn.i_format.rt] = value; break; #endif /* CONFIG_64BIT */ /* Cannot handle 64-bit instructions in 32-bit kernel */ goto sigill; case ld_op: #ifdef CONFIG_64BIT /* * A 32-bit kernel might be running on a 64-bit processor. But * if we're on a 32-bit processor and an i-cache incoherency * or race makes us see a 64-bit instruction here the sdl/sdr * would blow up, so for now we don't handle unaligned 64-bit * instructions on 32-bit kernels. */ if (!access_ok(VERIFY_READ, addr, 8)) goto sigbus; __asm__ __volatile__ ( #ifdef __BIG_ENDIAN "1:\tldl\t%0, (%2)\n" "2:\tldr\t%0, 7(%2)\n\t" #endif #ifdef __LITTLE_ENDIAN "1:\tldl\t%0, 7(%2)\n" "2:\tldr\t%0, (%2)\n\t" #endif "li\t%1, 0\n" "3:\t.section\t.fixup,\"ax\"\n\t" "4:\tli\t%1, %3\n\t" "j\t3b\n\t" ".previous\n\t" ".section\t__ex_table,\"a\"\n\t" STR(PTR)"\t1b, 4b\n\t" STR(PTR)"\t2b, 4b\n\t" ".previous" : "=&r" (value), "=r" (res) : "r" (addr), "i" (-EFAULT)); if (res) goto fault; compute_return_epc(regs); regs->regs[insn.i_format.rt] = value; break; #endif /* CONFIG_64BIT */ /* Cannot handle 64-bit instructions in 32-bit kernel */ goto sigill; case sh_op: if (!access_ok(VERIFY_WRITE, addr, 2)) goto sigbus; value = regs->regs[insn.i_format.rt]; __asm__ __volatile__ ( #ifdef __BIG_ENDIAN ".set\tnoat\n" "1:\tsb\t%1, 1(%2)\n\t" "srl\t$1, %1, 0x8\n" "2:\tsb\t$1, 0(%2)\n\t" ".set\tat\n\t" #endif #ifdef __LITTLE_ENDIAN ".set\tnoat\n" "1:\tsb\t%1, 0(%2)\n\t" "srl\t$1,%1, 0x8\n" "2:\tsb\t$1, 1(%2)\n\t" ".set\tat\n\t" #endif "li\t%0, 0\n" "3:\n\t" ".section\t.fixup,\"ax\"\n\t" "4:\tli\t%0, %3\n\t" "j\t3b\n\t" ".previous\n\t" ".section\t__ex_table,\"a\"\n\t" STR(PTR)"\t1b, 4b\n\t" STR(PTR)"\t2b, 4b\n\t" ".previous" : "=r" (res) : "r" (value), "r" (addr), "i" (-EFAULT)); if (res) goto fault; compute_return_epc(regs); break; case sw_op: if (!access_ok(VERIFY_WRITE, addr, 4)) goto sigbus; value = regs->regs[insn.i_format.rt]; __asm__ __volatile__ ( #ifdef __BIG_ENDIAN "1:\tswl\t%1,(%2)\n" "2:\tswr\t%1, 3(%2)\n\t" #endif #ifdef __LITTLE_ENDIAN "1:\tswl\t%1, 3(%2)\n" "2:\tswr\t%1, (%2)\n\t" #endif "li\t%0, 0\n" "3:\n\t" ".section\t.fixup,\"ax\"\n\t" "4:\tli\t%0, %3\n\t" "j\t3b\n\t" ".previous\n\t" ".section\t__ex_table,\"a\"\n\t" STR(PTR)"\t1b, 4b\n\t" STR(PTR)"\t2b, 4b\n\t" ".previous" : "=r" (res) : "r" (value), "r" (addr), "i" (-EFAULT)); if (res) goto fault; compute_return_epc(regs); break; case sd_op: #ifdef CONFIG_64BIT /* * A 32-bit kernel might be running on a 64-bit processor. But * if we're on a 32-bit processor and an i-cache incoherency * or race makes us see a 64-bit instruction here the sdl/sdr * would blow up, so for now we don't handle unaligned 64-bit * instructions on 32-bit kernels. */ if (!access_ok(VERIFY_WRITE, addr, 8)) goto sigbus; value = regs->regs[insn.i_format.rt]; __asm__ __volatile__ ( #ifdef __BIG_ENDIAN "1:\tsdl\t%1,(%2)\n" "2:\tsdr\t%1, 7(%2)\n\t" #endif #ifdef __LITTLE_ENDIAN "1:\tsdl\t%1, 7(%2)\n" "2:\tsdr\t%1, (%2)\n\t" #endif "li\t%0, 0\n" "3:\n\t" ".section\t.fixup,\"ax\"\n\t" "4:\tli\t%0, %3\n\t" "j\t3b\n\t" ".previous\n\t" ".section\t__ex_table,\"a\"\n\t" STR(PTR)"\t1b, 4b\n\t" STR(PTR)"\t2b, 4b\n\t" ".previous" : "=r" (res) : "r" (value), "r" (addr), "i" (-EFAULT)); if (res) goto fault; compute_return_epc(regs); break; #endif /* CONFIG_64BIT */ /* Cannot handle 64-bit instructions in 32-bit kernel */ goto sigill; case lwc1_op: case ldc1_op: case swc1_op: case sdc1_op: /* * I herewith declare: this does not happen. So send SIGBUS. */ goto sigbus; /* * COP2 is available to implementor for application specific use. * It's up to applications to register a notifier chain and do * whatever they have to do, including possible sending of signals. */ case lwc2_op: cu2_notifier_call_chain(CU2_LWC2_OP, regs); break; case ldc2_op: cu2_notifier_call_chain(CU2_LDC2_OP, regs); break; case swc2_op: cu2_notifier_call_chain(CU2_SWC2_OP, regs); break; case sdc2_op: cu2_notifier_call_chain(CU2_SDC2_OP, regs); break; default: /* * Pheeee... We encountered an yet unknown instruction or * cache coherence problem. Die sucker, die ... */ goto sigill; } #ifdef CONFIG_DEBUG_FS unaligned_instructions++; #endif return; fault: /* Did we have an exception handler installed? */ if (fixup_exception(regs)) return; die_if_kernel("Unhandled kernel unaligned access", regs); force_sig(SIGSEGV, current); return; sigbus: die_if_kernel("Unhandled kernel unaligned access", regs); force_sig(SIGBUS, current); return; sigill: die_if_kernel("Unhandled kernel unaligned access or invalid instruction", regs); force_sig(SIGILL, current); } asmlinkage void do_ade(struct pt_regs *regs) { unsigned int __user *pc; mm_segment_t seg; perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, regs, regs->cp0_badvaddr); /* * Did we catch a fault trying to load an instruction? * Or are we running in MIPS16 mode? */ if ((regs->cp0_badvaddr == regs->cp0_epc) || (regs->cp0_epc & 0x1)) goto sigbus; pc = (unsigned int __user *) exception_epc(regs); if (user_mode(regs) && !test_thread_flag(TIF_FIXADE)) goto sigbus; if (unaligned_action == UNALIGNED_ACTION_SIGNAL) goto sigbus; else if (unaligned_action == UNALIGNED_ACTION_SHOW) show_registers(regs); /* * Do branch emulation only if we didn't forward the exception. * This is all so but ugly ... */ seg = get_fs(); if (!user_mode(regs)) set_fs(KERNEL_DS); emulate_load_store_insn(regs, (void __user *)regs->cp0_badvaddr, pc); set_fs(seg); return; sigbus: die_if_kernel("Kernel unaligned instruction access", regs); force_sig(SIGBUS, current); /* * XXX On return from the signal handler we should advance the epc */ } #ifdef CONFIG_DEBUG_FS extern struct dentry *mips_debugfs_dir; static int __init debugfs_unaligned(void) { struct dentry *d; if (!mips_debugfs_dir) return -ENODEV; d = debugfs_create_u32("unaligned_instructions", S_IRUGO, mips_debugfs_dir, &unaligned_instructions); if (!d) return -ENOMEM; d = debugfs_create_u32("unaligned_action", S_IRUGO | S_IWUSR, mips_debugfs_dir, &unaligned_action); if (!d) return -ENOMEM; return 0; } __initcall(debugfs_unaligned); #endif
./CrossVul/dataset_final_sorted/CWE-399/c/good_3486_9
crossvul-cpp_data_bad_2322_0
/****************************************************************************** * emulate.c * * Generic x86 (32-bit and 64-bit) instruction decoder and emulator. * * Copyright (c) 2005 Keir Fraser * * Linux coding style, mod r/m decoder, segment base fixes, real-mode * privileged instructions: * * Copyright (C) 2006 Qumranet * Copyright 2010 Red Hat, Inc. and/or its affiliates. * * Avi Kivity <avi@qumranet.com> * Yaniv Kamay <yaniv@qumranet.com> * * This work is licensed under the terms of the GNU GPL, version 2. See * the COPYING file in the top-level directory. * * From: xen-unstable 10676:af9809f51f81a3c43f276f00c81a52ef558afda4 */ #include <linux/kvm_host.h> #include "kvm_cache_regs.h" #include <linux/module.h> #include <asm/kvm_emulate.h> #include <linux/stringify.h> #include "x86.h" #include "tss.h" /* * Operand types */ #define OpNone 0ull #define OpImplicit 1ull /* No generic decode */ #define OpReg 2ull /* Register */ #define OpMem 3ull /* Memory */ #define OpAcc 4ull /* Accumulator: AL/AX/EAX/RAX */ #define OpDI 5ull /* ES:DI/EDI/RDI */ #define OpMem64 6ull /* Memory, 64-bit */ #define OpImmUByte 7ull /* Zero-extended 8-bit immediate */ #define OpDX 8ull /* DX register */ #define OpCL 9ull /* CL register (for shifts) */ #define OpImmByte 10ull /* 8-bit sign extended immediate */ #define OpOne 11ull /* Implied 1 */ #define OpImm 12ull /* Sign extended up to 32-bit immediate */ #define OpMem16 13ull /* Memory operand (16-bit). */ #define OpMem32 14ull /* Memory operand (32-bit). */ #define OpImmU 15ull /* Immediate operand, zero extended */ #define OpSI 16ull /* SI/ESI/RSI */ #define OpImmFAddr 17ull /* Immediate far address */ #define OpMemFAddr 18ull /* Far address in memory */ #define OpImmU16 19ull /* Immediate operand, 16 bits, zero extended */ #define OpES 20ull /* ES */ #define OpCS 21ull /* CS */ #define OpSS 22ull /* SS */ #define OpDS 23ull /* DS */ #define OpFS 24ull /* FS */ #define OpGS 25ull /* GS */ #define OpMem8 26ull /* 8-bit zero extended memory operand */ #define OpImm64 27ull /* Sign extended 16/32/64-bit immediate */ #define OpXLat 28ull /* memory at BX/EBX/RBX + zero-extended AL */ #define OpAccLo 29ull /* Low part of extended acc (AX/AX/EAX/RAX) */ #define OpAccHi 30ull /* High part of extended acc (-/DX/EDX/RDX) */ #define OpBits 5 /* Width of operand field */ #define OpMask ((1ull << OpBits) - 1) /* * Opcode effective-address decode tables. * Note that we only emulate instructions that have at least one memory * operand (excluding implicit stack references). We assume that stack * references and instruction fetches will never occur in special memory * areas that require emulation. So, for example, 'mov <imm>,<reg>' need * not be handled. */ /* Operand sizes: 8-bit operands or specified/overridden size. */ #define ByteOp (1<<0) /* 8-bit operands. */ /* Destination operand type. */ #define DstShift 1 #define ImplicitOps (OpImplicit << DstShift) #define DstReg (OpReg << DstShift) #define DstMem (OpMem << DstShift) #define DstAcc (OpAcc << DstShift) #define DstDI (OpDI << DstShift) #define DstMem64 (OpMem64 << DstShift) #define DstImmUByte (OpImmUByte << DstShift) #define DstDX (OpDX << DstShift) #define DstAccLo (OpAccLo << DstShift) #define DstMask (OpMask << DstShift) /* Source operand type. */ #define SrcShift 6 #define SrcNone (OpNone << SrcShift) #define SrcReg (OpReg << SrcShift) #define SrcMem (OpMem << SrcShift) #define SrcMem16 (OpMem16 << SrcShift) #define SrcMem32 (OpMem32 << SrcShift) #define SrcImm (OpImm << SrcShift) #define SrcImmByte (OpImmByte << SrcShift) #define SrcOne (OpOne << SrcShift) #define SrcImmUByte (OpImmUByte << SrcShift) #define SrcImmU (OpImmU << SrcShift) #define SrcSI (OpSI << SrcShift) #define SrcXLat (OpXLat << SrcShift) #define SrcImmFAddr (OpImmFAddr << SrcShift) #define SrcMemFAddr (OpMemFAddr << SrcShift) #define SrcAcc (OpAcc << SrcShift) #define SrcImmU16 (OpImmU16 << SrcShift) #define SrcImm64 (OpImm64 << SrcShift) #define SrcDX (OpDX << SrcShift) #define SrcMem8 (OpMem8 << SrcShift) #define SrcAccHi (OpAccHi << SrcShift) #define SrcMask (OpMask << SrcShift) #define BitOp (1<<11) #define MemAbs (1<<12) /* Memory operand is absolute displacement */ #define String (1<<13) /* String instruction (rep capable) */ #define Stack (1<<14) /* Stack instruction (push/pop) */ #define GroupMask (7<<15) /* Opcode uses one of the group mechanisms */ #define Group (1<<15) /* Bits 3:5 of modrm byte extend opcode */ #define GroupDual (2<<15) /* Alternate decoding of mod == 3 */ #define Prefix (3<<15) /* Instruction varies with 66/f2/f3 prefix */ #define RMExt (4<<15) /* Opcode extension in ModRM r/m if mod == 3 */ #define Escape (5<<15) /* Escape to coprocessor instruction */ #define Sse (1<<18) /* SSE Vector instruction */ /* Generic ModRM decode. */ #define ModRM (1<<19) /* Destination is only written; never read. */ #define Mov (1<<20) /* Misc flags */ #define Prot (1<<21) /* instruction generates #UD if not in prot-mode */ #define EmulateOnUD (1<<22) /* Emulate if unsupported by the host */ #define NoAccess (1<<23) /* Don't access memory (lea/invlpg/verr etc) */ #define Op3264 (1<<24) /* Operand is 64b in long mode, 32b otherwise */ #define Undefined (1<<25) /* No Such Instruction */ #define Lock (1<<26) /* lock prefix is allowed for the instruction */ #define Priv (1<<27) /* instruction generates #GP if current CPL != 0 */ #define No64 (1<<28) #define PageTable (1 << 29) /* instruction used to write page table */ #define NotImpl (1 << 30) /* instruction is not implemented */ /* Source 2 operand type */ #define Src2Shift (31) #define Src2None (OpNone << Src2Shift) #define Src2Mem (OpMem << Src2Shift) #define Src2CL (OpCL << Src2Shift) #define Src2ImmByte (OpImmByte << Src2Shift) #define Src2One (OpOne << Src2Shift) #define Src2Imm (OpImm << Src2Shift) #define Src2ES (OpES << Src2Shift) #define Src2CS (OpCS << Src2Shift) #define Src2SS (OpSS << Src2Shift) #define Src2DS (OpDS << Src2Shift) #define Src2FS (OpFS << Src2Shift) #define Src2GS (OpGS << Src2Shift) #define Src2Mask (OpMask << Src2Shift) #define Mmx ((u64)1 << 40) /* MMX Vector instruction */ #define Aligned ((u64)1 << 41) /* Explicitly aligned (e.g. MOVDQA) */ #define Unaligned ((u64)1 << 42) /* Explicitly unaligned (e.g. MOVDQU) */ #define Avx ((u64)1 << 43) /* Advanced Vector Extensions */ #define Fastop ((u64)1 << 44) /* Use opcode::u.fastop */ #define NoWrite ((u64)1 << 45) /* No writeback */ #define SrcWrite ((u64)1 << 46) /* Write back src operand */ #define NoMod ((u64)1 << 47) /* Mod field is ignored */ #define Intercept ((u64)1 << 48) /* Has valid intercept field */ #define CheckPerm ((u64)1 << 49) /* Has valid check_perm field */ #define NoBigReal ((u64)1 << 50) /* No big real mode */ #define PrivUD ((u64)1 << 51) /* #UD instead of #GP on CPL > 0 */ #define DstXacc (DstAccLo | SrcAccHi | SrcWrite) #define X2(x...) x, x #define X3(x...) X2(x), x #define X4(x...) X2(x), X2(x) #define X5(x...) X4(x), x #define X6(x...) X4(x), X2(x) #define X7(x...) X4(x), X3(x) #define X8(x...) X4(x), X4(x) #define X16(x...) X8(x), X8(x) #define NR_FASTOP (ilog2(sizeof(ulong)) + 1) #define FASTOP_SIZE 8 /* * fastop functions have a special calling convention: * * dst: rax (in/out) * src: rdx (in/out) * src2: rcx (in) * flags: rflags (in/out) * ex: rsi (in:fastop pointer, out:zero if exception) * * Moreover, they are all exactly FASTOP_SIZE bytes long, so functions for * different operand sizes can be reached by calculation, rather than a jump * table (which would be bigger than the code). * * fastop functions are declared as taking a never-defined fastop parameter, * so they can't be called from C directly. */ struct fastop; struct opcode { u64 flags : 56; u64 intercept : 8; union { int (*execute)(struct x86_emulate_ctxt *ctxt); const struct opcode *group; const struct group_dual *gdual; const struct gprefix *gprefix; const struct escape *esc; void (*fastop)(struct fastop *fake); } u; int (*check_perm)(struct x86_emulate_ctxt *ctxt); }; struct group_dual { struct opcode mod012[8]; struct opcode mod3[8]; }; struct gprefix { struct opcode pfx_no; struct opcode pfx_66; struct opcode pfx_f2; struct opcode pfx_f3; }; struct escape { struct opcode op[8]; struct opcode high[64]; }; /* EFLAGS bit definitions. */ #define EFLG_ID (1<<21) #define EFLG_VIP (1<<20) #define EFLG_VIF (1<<19) #define EFLG_AC (1<<18) #define EFLG_VM (1<<17) #define EFLG_RF (1<<16) #define EFLG_IOPL (3<<12) #define EFLG_NT (1<<14) #define EFLG_OF (1<<11) #define EFLG_DF (1<<10) #define EFLG_IF (1<<9) #define EFLG_TF (1<<8) #define EFLG_SF (1<<7) #define EFLG_ZF (1<<6) #define EFLG_AF (1<<4) #define EFLG_PF (1<<2) #define EFLG_CF (1<<0) #define EFLG_RESERVED_ZEROS_MASK 0xffc0802a #define EFLG_RESERVED_ONE_MASK 2 static ulong reg_read(struct x86_emulate_ctxt *ctxt, unsigned nr) { if (!(ctxt->regs_valid & (1 << nr))) { ctxt->regs_valid |= 1 << nr; ctxt->_regs[nr] = ctxt->ops->read_gpr(ctxt, nr); } return ctxt->_regs[nr]; } static ulong *reg_write(struct x86_emulate_ctxt *ctxt, unsigned nr) { ctxt->regs_valid |= 1 << nr; ctxt->regs_dirty |= 1 << nr; return &ctxt->_regs[nr]; } static ulong *reg_rmw(struct x86_emulate_ctxt *ctxt, unsigned nr) { reg_read(ctxt, nr); return reg_write(ctxt, nr); } static void writeback_registers(struct x86_emulate_ctxt *ctxt) { unsigned reg; for_each_set_bit(reg, (ulong *)&ctxt->regs_dirty, 16) ctxt->ops->write_gpr(ctxt, reg, ctxt->_regs[reg]); } static void invalidate_registers(struct x86_emulate_ctxt *ctxt) { ctxt->regs_dirty = 0; ctxt->regs_valid = 0; } /* * These EFLAGS bits are restored from saved value during emulation, and * any changes are written back to the saved value after emulation. */ #define EFLAGS_MASK (EFLG_OF|EFLG_SF|EFLG_ZF|EFLG_AF|EFLG_PF|EFLG_CF) #ifdef CONFIG_X86_64 #define ON64(x) x #else #define ON64(x) #endif static int fastop(struct x86_emulate_ctxt *ctxt, void (*fop)(struct fastop *)); #define FOP_ALIGN ".align " __stringify(FASTOP_SIZE) " \n\t" #define FOP_RET "ret \n\t" #define FOP_START(op) \ extern void em_##op(struct fastop *fake); \ asm(".pushsection .text, \"ax\" \n\t" \ ".global em_" #op " \n\t" \ FOP_ALIGN \ "em_" #op ": \n\t" #define FOP_END \ ".popsection") #define FOPNOP() FOP_ALIGN FOP_RET #define FOP1E(op, dst) \ FOP_ALIGN "10: " #op " %" #dst " \n\t" FOP_RET #define FOP1EEX(op, dst) \ FOP1E(op, dst) _ASM_EXTABLE(10b, kvm_fastop_exception) #define FASTOP1(op) \ FOP_START(op) \ FOP1E(op##b, al) \ FOP1E(op##w, ax) \ FOP1E(op##l, eax) \ ON64(FOP1E(op##q, rax)) \ FOP_END /* 1-operand, using src2 (for MUL/DIV r/m) */ #define FASTOP1SRC2(op, name) \ FOP_START(name) \ FOP1E(op, cl) \ FOP1E(op, cx) \ FOP1E(op, ecx) \ ON64(FOP1E(op, rcx)) \ FOP_END /* 1-operand, using src2 (for MUL/DIV r/m), with exceptions */ #define FASTOP1SRC2EX(op, name) \ FOP_START(name) \ FOP1EEX(op, cl) \ FOP1EEX(op, cx) \ FOP1EEX(op, ecx) \ ON64(FOP1EEX(op, rcx)) \ FOP_END #define FOP2E(op, dst, src) \ FOP_ALIGN #op " %" #src ", %" #dst " \n\t" FOP_RET #define FASTOP2(op) \ FOP_START(op) \ FOP2E(op##b, al, dl) \ FOP2E(op##w, ax, dx) \ FOP2E(op##l, eax, edx) \ ON64(FOP2E(op##q, rax, rdx)) \ FOP_END /* 2 operand, word only */ #define FASTOP2W(op) \ FOP_START(op) \ FOPNOP() \ FOP2E(op##w, ax, dx) \ FOP2E(op##l, eax, edx) \ ON64(FOP2E(op##q, rax, rdx)) \ FOP_END /* 2 operand, src is CL */ #define FASTOP2CL(op) \ FOP_START(op) \ FOP2E(op##b, al, cl) \ FOP2E(op##w, ax, cl) \ FOP2E(op##l, eax, cl) \ ON64(FOP2E(op##q, rax, cl)) \ FOP_END #define FOP3E(op, dst, src, src2) \ FOP_ALIGN #op " %" #src2 ", %" #src ", %" #dst " \n\t" FOP_RET /* 3-operand, word-only, src2=cl */ #define FASTOP3WCL(op) \ FOP_START(op) \ FOPNOP() \ FOP3E(op##w, ax, dx, cl) \ FOP3E(op##l, eax, edx, cl) \ ON64(FOP3E(op##q, rax, rdx, cl)) \ FOP_END /* Special case for SETcc - 1 instruction per cc */ #define FOP_SETCC(op) ".align 4; " #op " %al; ret \n\t" asm(".global kvm_fastop_exception \n" "kvm_fastop_exception: xor %esi, %esi; ret"); FOP_START(setcc) FOP_SETCC(seto) FOP_SETCC(setno) FOP_SETCC(setc) FOP_SETCC(setnc) FOP_SETCC(setz) FOP_SETCC(setnz) FOP_SETCC(setbe) FOP_SETCC(setnbe) FOP_SETCC(sets) FOP_SETCC(setns) FOP_SETCC(setp) FOP_SETCC(setnp) FOP_SETCC(setl) FOP_SETCC(setnl) FOP_SETCC(setle) FOP_SETCC(setnle) FOP_END; FOP_START(salc) "pushf; sbb %al, %al; popf \n\t" FOP_RET FOP_END; static int emulator_check_intercept(struct x86_emulate_ctxt *ctxt, enum x86_intercept intercept, enum x86_intercept_stage stage) { struct x86_instruction_info info = { .intercept = intercept, .rep_prefix = ctxt->rep_prefix, .modrm_mod = ctxt->modrm_mod, .modrm_reg = ctxt->modrm_reg, .modrm_rm = ctxt->modrm_rm, .src_val = ctxt->src.val64, .dst_val = ctxt->dst.val64, .src_bytes = ctxt->src.bytes, .dst_bytes = ctxt->dst.bytes, .ad_bytes = ctxt->ad_bytes, .next_rip = ctxt->eip, }; return ctxt->ops->intercept(ctxt, &info, stage); } static void assign_masked(ulong *dest, ulong src, ulong mask) { *dest = (*dest & ~mask) | (src & mask); } static inline unsigned long ad_mask(struct x86_emulate_ctxt *ctxt) { return (1UL << (ctxt->ad_bytes << 3)) - 1; } static ulong stack_mask(struct x86_emulate_ctxt *ctxt) { u16 sel; struct desc_struct ss; if (ctxt->mode == X86EMUL_MODE_PROT64) return ~0UL; ctxt->ops->get_segment(ctxt, &sel, &ss, NULL, VCPU_SREG_SS); return ~0U >> ((ss.d ^ 1) * 16); /* d=0: 0xffff; d=1: 0xffffffff */ } static int stack_size(struct x86_emulate_ctxt *ctxt) { return (__fls(stack_mask(ctxt)) + 1) >> 3; } /* Access/update address held in a register, based on addressing mode. */ static inline unsigned long address_mask(struct x86_emulate_ctxt *ctxt, unsigned long reg) { if (ctxt->ad_bytes == sizeof(unsigned long)) return reg; else return reg & ad_mask(ctxt); } static inline unsigned long register_address(struct x86_emulate_ctxt *ctxt, unsigned long reg) { return address_mask(ctxt, reg); } static void masked_increment(ulong *reg, ulong mask, int inc) { assign_masked(reg, *reg + inc, mask); } static inline void register_address_increment(struct x86_emulate_ctxt *ctxt, unsigned long *reg, int inc) { ulong mask; if (ctxt->ad_bytes == sizeof(unsigned long)) mask = ~0UL; else mask = ad_mask(ctxt); masked_increment(reg, mask, inc); } static void rsp_increment(struct x86_emulate_ctxt *ctxt, int inc) { masked_increment(reg_rmw(ctxt, VCPU_REGS_RSP), stack_mask(ctxt), inc); } static u32 desc_limit_scaled(struct desc_struct *desc) { u32 limit = get_desc_limit(desc); return desc->g ? (limit << 12) | 0xfff : limit; } static unsigned long seg_base(struct x86_emulate_ctxt *ctxt, int seg) { if (ctxt->mode == X86EMUL_MODE_PROT64 && seg < VCPU_SREG_FS) return 0; return ctxt->ops->get_cached_segment_base(ctxt, seg); } static int emulate_exception(struct x86_emulate_ctxt *ctxt, int vec, u32 error, bool valid) { WARN_ON(vec > 0x1f); ctxt->exception.vector = vec; ctxt->exception.error_code = error; ctxt->exception.error_code_valid = valid; return X86EMUL_PROPAGATE_FAULT; } static int emulate_db(struct x86_emulate_ctxt *ctxt) { return emulate_exception(ctxt, DB_VECTOR, 0, false); } static int emulate_gp(struct x86_emulate_ctxt *ctxt, int err) { return emulate_exception(ctxt, GP_VECTOR, err, true); } static int emulate_ss(struct x86_emulate_ctxt *ctxt, int err) { return emulate_exception(ctxt, SS_VECTOR, err, true); } static int emulate_ud(struct x86_emulate_ctxt *ctxt) { return emulate_exception(ctxt, UD_VECTOR, 0, false); } static int emulate_ts(struct x86_emulate_ctxt *ctxt, int err) { return emulate_exception(ctxt, TS_VECTOR, err, true); } static int emulate_de(struct x86_emulate_ctxt *ctxt) { return emulate_exception(ctxt, DE_VECTOR, 0, false); } static int emulate_nm(struct x86_emulate_ctxt *ctxt) { return emulate_exception(ctxt, NM_VECTOR, 0, false); } static inline int assign_eip_far(struct x86_emulate_ctxt *ctxt, ulong dst, int cs_l) { switch (ctxt->op_bytes) { case 2: ctxt->_eip = (u16)dst; break; case 4: ctxt->_eip = (u32)dst; break; case 8: if ((cs_l && is_noncanonical_address(dst)) || (!cs_l && (dst & ~(u32)-1))) return emulate_gp(ctxt, 0); ctxt->_eip = dst; break; default: WARN(1, "unsupported eip assignment size\n"); } return X86EMUL_CONTINUE; } static inline int assign_eip_near(struct x86_emulate_ctxt *ctxt, ulong dst) { return assign_eip_far(ctxt, dst, ctxt->mode == X86EMUL_MODE_PROT64); } static inline int jmp_rel(struct x86_emulate_ctxt *ctxt, int rel) { return assign_eip_near(ctxt, ctxt->_eip + rel); } static u16 get_segment_selector(struct x86_emulate_ctxt *ctxt, unsigned seg) { u16 selector; struct desc_struct desc; ctxt->ops->get_segment(ctxt, &selector, &desc, NULL, seg); return selector; } static void set_segment_selector(struct x86_emulate_ctxt *ctxt, u16 selector, unsigned seg) { u16 dummy; u32 base3; struct desc_struct desc; ctxt->ops->get_segment(ctxt, &dummy, &desc, &base3, seg); ctxt->ops->set_segment(ctxt, selector, &desc, base3, seg); } /* * x86 defines three classes of vector instructions: explicitly * aligned, explicitly unaligned, and the rest, which change behaviour * depending on whether they're AVX encoded or not. * * Also included is CMPXCHG16B which is not a vector instruction, yet it is * subject to the same check. */ static bool insn_aligned(struct x86_emulate_ctxt *ctxt, unsigned size) { if (likely(size < 16)) return false; if (ctxt->d & Aligned) return true; else if (ctxt->d & Unaligned) return false; else if (ctxt->d & Avx) return false; else return true; } static int __linearize(struct x86_emulate_ctxt *ctxt, struct segmented_address addr, unsigned size, bool write, bool fetch, ulong *linear) { struct desc_struct desc; bool usable; ulong la; u32 lim; u16 sel; unsigned cpl; la = seg_base(ctxt, addr.seg) + addr.ea; switch (ctxt->mode) { case X86EMUL_MODE_PROT64: if (((signed long)la << 16) >> 16 != la) return emulate_gp(ctxt, 0); break; default: usable = ctxt->ops->get_segment(ctxt, &sel, &desc, NULL, addr.seg); if (!usable) goto bad; /* code segment in protected mode or read-only data segment */ if ((((ctxt->mode != X86EMUL_MODE_REAL) && (desc.type & 8)) || !(desc.type & 2)) && write) goto bad; /* unreadable code segment */ if (!fetch && (desc.type & 8) && !(desc.type & 2)) goto bad; lim = desc_limit_scaled(&desc); if ((ctxt->mode == X86EMUL_MODE_REAL) && !fetch && (ctxt->d & NoBigReal)) { /* la is between zero and 0xffff */ if (la > 0xffff || (u32)(la + size - 1) > 0xffff) goto bad; } else if ((desc.type & 8) || !(desc.type & 4)) { /* expand-up segment */ if (addr.ea > lim || (u32)(addr.ea + size - 1) > lim) goto bad; } else { /* expand-down segment */ if (addr.ea <= lim || (u32)(addr.ea + size - 1) <= lim) goto bad; lim = desc.d ? 0xffffffff : 0xffff; if (addr.ea > lim || (u32)(addr.ea + size - 1) > lim) goto bad; } cpl = ctxt->ops->cpl(ctxt); if (!(desc.type & 8)) { /* data segment */ if (cpl > desc.dpl) goto bad; } else if ((desc.type & 8) && !(desc.type & 4)) { /* nonconforming code segment */ if (cpl != desc.dpl) goto bad; } else if ((desc.type & 8) && (desc.type & 4)) { /* conforming code segment */ if (cpl < desc.dpl) goto bad; } break; } if (fetch ? ctxt->mode != X86EMUL_MODE_PROT64 : ctxt->ad_bytes != 8) la &= (u32)-1; if (insn_aligned(ctxt, size) && ((la & (size - 1)) != 0)) return emulate_gp(ctxt, 0); *linear = la; return X86EMUL_CONTINUE; bad: if (addr.seg == VCPU_SREG_SS) return emulate_ss(ctxt, sel); else return emulate_gp(ctxt, sel); } static int linearize(struct x86_emulate_ctxt *ctxt, struct segmented_address addr, unsigned size, bool write, ulong *linear) { return __linearize(ctxt, addr, size, write, false, linear); } static int segmented_read_std(struct x86_emulate_ctxt *ctxt, struct segmented_address addr, void *data, unsigned size) { int rc; ulong linear; rc = linearize(ctxt, addr, size, false, &linear); if (rc != X86EMUL_CONTINUE) return rc; return ctxt->ops->read_std(ctxt, linear, data, size, &ctxt->exception); } /* * Prefetch the remaining bytes of the instruction without crossing page * boundary if they are not in fetch_cache yet. */ static int __do_insn_fetch_bytes(struct x86_emulate_ctxt *ctxt, int op_size) { int rc; unsigned size; unsigned long linear; int cur_size = ctxt->fetch.end - ctxt->fetch.data; struct segmented_address addr = { .seg = VCPU_SREG_CS, .ea = ctxt->eip + cur_size }; size = 15UL ^ cur_size; rc = __linearize(ctxt, addr, size, false, true, &linear); if (unlikely(rc != X86EMUL_CONTINUE)) return rc; size = min_t(unsigned, size, PAGE_SIZE - offset_in_page(linear)); /* * One instruction can only straddle two pages, * and one has been loaded at the beginning of * x86_decode_insn. So, if not enough bytes * still, we must have hit the 15-byte boundary. */ if (unlikely(size < op_size)) return X86EMUL_UNHANDLEABLE; rc = ctxt->ops->fetch(ctxt, linear, ctxt->fetch.end, size, &ctxt->exception); if (unlikely(rc != X86EMUL_CONTINUE)) return rc; ctxt->fetch.end += size; return X86EMUL_CONTINUE; } static __always_inline int do_insn_fetch_bytes(struct x86_emulate_ctxt *ctxt, unsigned size) { unsigned done_size = ctxt->fetch.end - ctxt->fetch.ptr; if (unlikely(done_size < size)) return __do_insn_fetch_bytes(ctxt, size - done_size); else return X86EMUL_CONTINUE; } /* Fetch next part of the instruction being emulated. */ #define insn_fetch(_type, _ctxt) \ ({ _type _x; \ \ rc = do_insn_fetch_bytes(_ctxt, sizeof(_type)); \ if (rc != X86EMUL_CONTINUE) \ goto done; \ ctxt->_eip += sizeof(_type); \ _x = *(_type __aligned(1) *) ctxt->fetch.ptr; \ ctxt->fetch.ptr += sizeof(_type); \ _x; \ }) #define insn_fetch_arr(_arr, _size, _ctxt) \ ({ \ rc = do_insn_fetch_bytes(_ctxt, _size); \ if (rc != X86EMUL_CONTINUE) \ goto done; \ ctxt->_eip += (_size); \ memcpy(_arr, ctxt->fetch.ptr, _size); \ ctxt->fetch.ptr += (_size); \ }) /* * Given the 'reg' portion of a ModRM byte, and a register block, return a * pointer into the block that addresses the relevant register. * @highbyte_regs specifies whether to decode AH,CH,DH,BH. */ static void *decode_register(struct x86_emulate_ctxt *ctxt, u8 modrm_reg, int byteop) { void *p; int highbyte_regs = (ctxt->rex_prefix == 0) && byteop; if (highbyte_regs && modrm_reg >= 4 && modrm_reg < 8) p = (unsigned char *)reg_rmw(ctxt, modrm_reg & 3) + 1; else p = reg_rmw(ctxt, modrm_reg); return p; } static int read_descriptor(struct x86_emulate_ctxt *ctxt, struct segmented_address addr, u16 *size, unsigned long *address, int op_bytes) { int rc; if (op_bytes == 2) op_bytes = 3; *address = 0; rc = segmented_read_std(ctxt, addr, size, 2); if (rc != X86EMUL_CONTINUE) return rc; addr.ea += 2; rc = segmented_read_std(ctxt, addr, address, op_bytes); return rc; } FASTOP2(add); FASTOP2(or); FASTOP2(adc); FASTOP2(sbb); FASTOP2(and); FASTOP2(sub); FASTOP2(xor); FASTOP2(cmp); FASTOP2(test); FASTOP1SRC2(mul, mul_ex); FASTOP1SRC2(imul, imul_ex); FASTOP1SRC2EX(div, div_ex); FASTOP1SRC2EX(idiv, idiv_ex); FASTOP3WCL(shld); FASTOP3WCL(shrd); FASTOP2W(imul); FASTOP1(not); FASTOP1(neg); FASTOP1(inc); FASTOP1(dec); FASTOP2CL(rol); FASTOP2CL(ror); FASTOP2CL(rcl); FASTOP2CL(rcr); FASTOP2CL(shl); FASTOP2CL(shr); FASTOP2CL(sar); FASTOP2W(bsf); FASTOP2W(bsr); FASTOP2W(bt); FASTOP2W(bts); FASTOP2W(btr); FASTOP2W(btc); FASTOP2(xadd); static u8 test_cc(unsigned int condition, unsigned long flags) { u8 rc; void (*fop)(void) = (void *)em_setcc + 4 * (condition & 0xf); flags = (flags & EFLAGS_MASK) | X86_EFLAGS_IF; asm("push %[flags]; popf; call *%[fastop]" : "=a"(rc) : [fastop]"r"(fop), [flags]"r"(flags)); return rc; } static void fetch_register_operand(struct operand *op) { switch (op->bytes) { case 1: op->val = *(u8 *)op->addr.reg; break; case 2: op->val = *(u16 *)op->addr.reg; break; case 4: op->val = *(u32 *)op->addr.reg; break; case 8: op->val = *(u64 *)op->addr.reg; break; } } static void read_sse_reg(struct x86_emulate_ctxt *ctxt, sse128_t *data, int reg) { ctxt->ops->get_fpu(ctxt); switch (reg) { case 0: asm("movdqa %%xmm0, %0" : "=m"(*data)); break; case 1: asm("movdqa %%xmm1, %0" : "=m"(*data)); break; case 2: asm("movdqa %%xmm2, %0" : "=m"(*data)); break; case 3: asm("movdqa %%xmm3, %0" : "=m"(*data)); break; case 4: asm("movdqa %%xmm4, %0" : "=m"(*data)); break; case 5: asm("movdqa %%xmm5, %0" : "=m"(*data)); break; case 6: asm("movdqa %%xmm6, %0" : "=m"(*data)); break; case 7: asm("movdqa %%xmm7, %0" : "=m"(*data)); break; #ifdef CONFIG_X86_64 case 8: asm("movdqa %%xmm8, %0" : "=m"(*data)); break; case 9: asm("movdqa %%xmm9, %0" : "=m"(*data)); break; case 10: asm("movdqa %%xmm10, %0" : "=m"(*data)); break; case 11: asm("movdqa %%xmm11, %0" : "=m"(*data)); break; case 12: asm("movdqa %%xmm12, %0" : "=m"(*data)); break; case 13: asm("movdqa %%xmm13, %0" : "=m"(*data)); break; case 14: asm("movdqa %%xmm14, %0" : "=m"(*data)); break; case 15: asm("movdqa %%xmm15, %0" : "=m"(*data)); break; #endif default: BUG(); } ctxt->ops->put_fpu(ctxt); } static void write_sse_reg(struct x86_emulate_ctxt *ctxt, sse128_t *data, int reg) { ctxt->ops->get_fpu(ctxt); switch (reg) { case 0: asm("movdqa %0, %%xmm0" : : "m"(*data)); break; case 1: asm("movdqa %0, %%xmm1" : : "m"(*data)); break; case 2: asm("movdqa %0, %%xmm2" : : "m"(*data)); break; case 3: asm("movdqa %0, %%xmm3" : : "m"(*data)); break; case 4: asm("movdqa %0, %%xmm4" : : "m"(*data)); break; case 5: asm("movdqa %0, %%xmm5" : : "m"(*data)); break; case 6: asm("movdqa %0, %%xmm6" : : "m"(*data)); break; case 7: asm("movdqa %0, %%xmm7" : : "m"(*data)); break; #ifdef CONFIG_X86_64 case 8: asm("movdqa %0, %%xmm8" : : "m"(*data)); break; case 9: asm("movdqa %0, %%xmm9" : : "m"(*data)); break; case 10: asm("movdqa %0, %%xmm10" : : "m"(*data)); break; case 11: asm("movdqa %0, %%xmm11" : : "m"(*data)); break; case 12: asm("movdqa %0, %%xmm12" : : "m"(*data)); break; case 13: asm("movdqa %0, %%xmm13" : : "m"(*data)); break; case 14: asm("movdqa %0, %%xmm14" : : "m"(*data)); break; case 15: asm("movdqa %0, %%xmm15" : : "m"(*data)); break; #endif default: BUG(); } ctxt->ops->put_fpu(ctxt); } static void read_mmx_reg(struct x86_emulate_ctxt *ctxt, u64 *data, int reg) { ctxt->ops->get_fpu(ctxt); switch (reg) { case 0: asm("movq %%mm0, %0" : "=m"(*data)); break; case 1: asm("movq %%mm1, %0" : "=m"(*data)); break; case 2: asm("movq %%mm2, %0" : "=m"(*data)); break; case 3: asm("movq %%mm3, %0" : "=m"(*data)); break; case 4: asm("movq %%mm4, %0" : "=m"(*data)); break; case 5: asm("movq %%mm5, %0" : "=m"(*data)); break; case 6: asm("movq %%mm6, %0" : "=m"(*data)); break; case 7: asm("movq %%mm7, %0" : "=m"(*data)); break; default: BUG(); } ctxt->ops->put_fpu(ctxt); } static void write_mmx_reg(struct x86_emulate_ctxt *ctxt, u64 *data, int reg) { ctxt->ops->get_fpu(ctxt); switch (reg) { case 0: asm("movq %0, %%mm0" : : "m"(*data)); break; case 1: asm("movq %0, %%mm1" : : "m"(*data)); break; case 2: asm("movq %0, %%mm2" : : "m"(*data)); break; case 3: asm("movq %0, %%mm3" : : "m"(*data)); break; case 4: asm("movq %0, %%mm4" : : "m"(*data)); break; case 5: asm("movq %0, %%mm5" : : "m"(*data)); break; case 6: asm("movq %0, %%mm6" : : "m"(*data)); break; case 7: asm("movq %0, %%mm7" : : "m"(*data)); break; default: BUG(); } ctxt->ops->put_fpu(ctxt); } static int em_fninit(struct x86_emulate_ctxt *ctxt) { if (ctxt->ops->get_cr(ctxt, 0) & (X86_CR0_TS | X86_CR0_EM)) return emulate_nm(ctxt); ctxt->ops->get_fpu(ctxt); asm volatile("fninit"); ctxt->ops->put_fpu(ctxt); return X86EMUL_CONTINUE; } static int em_fnstcw(struct x86_emulate_ctxt *ctxt) { u16 fcw; if (ctxt->ops->get_cr(ctxt, 0) & (X86_CR0_TS | X86_CR0_EM)) return emulate_nm(ctxt); ctxt->ops->get_fpu(ctxt); asm volatile("fnstcw %0": "+m"(fcw)); ctxt->ops->put_fpu(ctxt); /* force 2 byte destination */ ctxt->dst.bytes = 2; ctxt->dst.val = fcw; return X86EMUL_CONTINUE; } static int em_fnstsw(struct x86_emulate_ctxt *ctxt) { u16 fsw; if (ctxt->ops->get_cr(ctxt, 0) & (X86_CR0_TS | X86_CR0_EM)) return emulate_nm(ctxt); ctxt->ops->get_fpu(ctxt); asm volatile("fnstsw %0": "+m"(fsw)); ctxt->ops->put_fpu(ctxt); /* force 2 byte destination */ ctxt->dst.bytes = 2; ctxt->dst.val = fsw; return X86EMUL_CONTINUE; } static void decode_register_operand(struct x86_emulate_ctxt *ctxt, struct operand *op) { unsigned reg = ctxt->modrm_reg; if (!(ctxt->d & ModRM)) reg = (ctxt->b & 7) | ((ctxt->rex_prefix & 1) << 3); if (ctxt->d & Sse) { op->type = OP_XMM; op->bytes = 16; op->addr.xmm = reg; read_sse_reg(ctxt, &op->vec_val, reg); return; } if (ctxt->d & Mmx) { reg &= 7; op->type = OP_MM; op->bytes = 8; op->addr.mm = reg; return; } op->type = OP_REG; op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes; op->addr.reg = decode_register(ctxt, reg, ctxt->d & ByteOp); fetch_register_operand(op); op->orig_val = op->val; } static void adjust_modrm_seg(struct x86_emulate_ctxt *ctxt, int base_reg) { if (base_reg == VCPU_REGS_RSP || base_reg == VCPU_REGS_RBP) ctxt->modrm_seg = VCPU_SREG_SS; } static int decode_modrm(struct x86_emulate_ctxt *ctxt, struct operand *op) { u8 sib; int index_reg, base_reg, scale; int rc = X86EMUL_CONTINUE; ulong modrm_ea = 0; ctxt->modrm_reg = ((ctxt->rex_prefix << 1) & 8); /* REX.R */ index_reg = (ctxt->rex_prefix << 2) & 8; /* REX.X */ base_reg = (ctxt->rex_prefix << 3) & 8; /* REX.B */ ctxt->modrm_mod = (ctxt->modrm & 0xc0) >> 6; ctxt->modrm_reg |= (ctxt->modrm & 0x38) >> 3; ctxt->modrm_rm = base_reg | (ctxt->modrm & 0x07); ctxt->modrm_seg = VCPU_SREG_DS; if (ctxt->modrm_mod == 3 || (ctxt->d & NoMod)) { op->type = OP_REG; op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes; op->addr.reg = decode_register(ctxt, ctxt->modrm_rm, ctxt->d & ByteOp); if (ctxt->d & Sse) { op->type = OP_XMM; op->bytes = 16; op->addr.xmm = ctxt->modrm_rm; read_sse_reg(ctxt, &op->vec_val, ctxt->modrm_rm); return rc; } if (ctxt->d & Mmx) { op->type = OP_MM; op->bytes = 8; op->addr.mm = ctxt->modrm_rm & 7; return rc; } fetch_register_operand(op); return rc; } op->type = OP_MEM; if (ctxt->ad_bytes == 2) { unsigned bx = reg_read(ctxt, VCPU_REGS_RBX); unsigned bp = reg_read(ctxt, VCPU_REGS_RBP); unsigned si = reg_read(ctxt, VCPU_REGS_RSI); unsigned di = reg_read(ctxt, VCPU_REGS_RDI); /* 16-bit ModR/M decode. */ switch (ctxt->modrm_mod) { case 0: if (ctxt->modrm_rm == 6) modrm_ea += insn_fetch(u16, ctxt); break; case 1: modrm_ea += insn_fetch(s8, ctxt); break; case 2: modrm_ea += insn_fetch(u16, ctxt); break; } switch (ctxt->modrm_rm) { case 0: modrm_ea += bx + si; break; case 1: modrm_ea += bx + di; break; case 2: modrm_ea += bp + si; break; case 3: modrm_ea += bp + di; break; case 4: modrm_ea += si; break; case 5: modrm_ea += di; break; case 6: if (ctxt->modrm_mod != 0) modrm_ea += bp; break; case 7: modrm_ea += bx; break; } if (ctxt->modrm_rm == 2 || ctxt->modrm_rm == 3 || (ctxt->modrm_rm == 6 && ctxt->modrm_mod != 0)) ctxt->modrm_seg = VCPU_SREG_SS; modrm_ea = (u16)modrm_ea; } else { /* 32/64-bit ModR/M decode. */ if ((ctxt->modrm_rm & 7) == 4) { sib = insn_fetch(u8, ctxt); index_reg |= (sib >> 3) & 7; base_reg |= sib & 7; scale = sib >> 6; if ((base_reg & 7) == 5 && ctxt->modrm_mod == 0) modrm_ea += insn_fetch(s32, ctxt); else { modrm_ea += reg_read(ctxt, base_reg); adjust_modrm_seg(ctxt, base_reg); } if (index_reg != 4) modrm_ea += reg_read(ctxt, index_reg) << scale; } else if ((ctxt->modrm_rm & 7) == 5 && ctxt->modrm_mod == 0) { if (ctxt->mode == X86EMUL_MODE_PROT64) ctxt->rip_relative = 1; } else { base_reg = ctxt->modrm_rm; modrm_ea += reg_read(ctxt, base_reg); adjust_modrm_seg(ctxt, base_reg); } switch (ctxt->modrm_mod) { case 0: if (ctxt->modrm_rm == 5) modrm_ea += insn_fetch(s32, ctxt); break; case 1: modrm_ea += insn_fetch(s8, ctxt); break; case 2: modrm_ea += insn_fetch(s32, ctxt); break; } } op->addr.mem.ea = modrm_ea; if (ctxt->ad_bytes != 8) ctxt->memop.addr.mem.ea = (u32)ctxt->memop.addr.mem.ea; done: return rc; } static int decode_abs(struct x86_emulate_ctxt *ctxt, struct operand *op) { int rc = X86EMUL_CONTINUE; op->type = OP_MEM; switch (ctxt->ad_bytes) { case 2: op->addr.mem.ea = insn_fetch(u16, ctxt); break; case 4: op->addr.mem.ea = insn_fetch(u32, ctxt); break; case 8: op->addr.mem.ea = insn_fetch(u64, ctxt); break; } done: return rc; } static void fetch_bit_operand(struct x86_emulate_ctxt *ctxt) { long sv = 0, mask; if (ctxt->dst.type == OP_MEM && ctxt->src.type == OP_REG) { mask = ~((long)ctxt->dst.bytes * 8 - 1); if (ctxt->src.bytes == 2) sv = (s16)ctxt->src.val & (s16)mask; else if (ctxt->src.bytes == 4) sv = (s32)ctxt->src.val & (s32)mask; else sv = (s64)ctxt->src.val & (s64)mask; ctxt->dst.addr.mem.ea += (sv >> 3); } /* only subword offset */ ctxt->src.val &= (ctxt->dst.bytes << 3) - 1; } static int read_emulated(struct x86_emulate_ctxt *ctxt, unsigned long addr, void *dest, unsigned size) { int rc; struct read_cache *mc = &ctxt->mem_read; if (mc->pos < mc->end) goto read_cached; WARN_ON((mc->end + size) >= sizeof(mc->data)); rc = ctxt->ops->read_emulated(ctxt, addr, mc->data + mc->end, size, &ctxt->exception); if (rc != X86EMUL_CONTINUE) return rc; mc->end += size; read_cached: memcpy(dest, mc->data + mc->pos, size); mc->pos += size; return X86EMUL_CONTINUE; } static int segmented_read(struct x86_emulate_ctxt *ctxt, struct segmented_address addr, void *data, unsigned size) { int rc; ulong linear; rc = linearize(ctxt, addr, size, false, &linear); if (rc != X86EMUL_CONTINUE) return rc; return read_emulated(ctxt, linear, data, size); } static int segmented_write(struct x86_emulate_ctxt *ctxt, struct segmented_address addr, const void *data, unsigned size) { int rc; ulong linear; rc = linearize(ctxt, addr, size, true, &linear); if (rc != X86EMUL_CONTINUE) return rc; return ctxt->ops->write_emulated(ctxt, linear, data, size, &ctxt->exception); } static int segmented_cmpxchg(struct x86_emulate_ctxt *ctxt, struct segmented_address addr, const void *orig_data, const void *data, unsigned size) { int rc; ulong linear; rc = linearize(ctxt, addr, size, true, &linear); if (rc != X86EMUL_CONTINUE) return rc; return ctxt->ops->cmpxchg_emulated(ctxt, linear, orig_data, data, size, &ctxt->exception); } static int pio_in_emulated(struct x86_emulate_ctxt *ctxt, unsigned int size, unsigned short port, void *dest) { struct read_cache *rc = &ctxt->io_read; if (rc->pos == rc->end) { /* refill pio read ahead */ unsigned int in_page, n; unsigned int count = ctxt->rep_prefix ? address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) : 1; in_page = (ctxt->eflags & EFLG_DF) ? offset_in_page(reg_read(ctxt, VCPU_REGS_RDI)) : PAGE_SIZE - offset_in_page(reg_read(ctxt, VCPU_REGS_RDI)); n = min3(in_page, (unsigned int)sizeof(rc->data) / size, count); if (n == 0) n = 1; rc->pos = rc->end = 0; if (!ctxt->ops->pio_in_emulated(ctxt, size, port, rc->data, n)) return 0; rc->end = n * size; } if (ctxt->rep_prefix && (ctxt->d & String) && !(ctxt->eflags & EFLG_DF)) { ctxt->dst.data = rc->data + rc->pos; ctxt->dst.type = OP_MEM_STR; ctxt->dst.count = (rc->end - rc->pos) / size; rc->pos = rc->end; } else { memcpy(dest, rc->data + rc->pos, size); rc->pos += size; } return 1; } static int read_interrupt_descriptor(struct x86_emulate_ctxt *ctxt, u16 index, struct desc_struct *desc) { struct desc_ptr dt; ulong addr; ctxt->ops->get_idt(ctxt, &dt); if (dt.size < index * 8 + 7) return emulate_gp(ctxt, index << 3 | 0x2); addr = dt.address + index * 8; return ctxt->ops->read_std(ctxt, addr, desc, sizeof *desc, &ctxt->exception); } static void get_descriptor_table_ptr(struct x86_emulate_ctxt *ctxt, u16 selector, struct desc_ptr *dt) { const struct x86_emulate_ops *ops = ctxt->ops; u32 base3 = 0; if (selector & 1 << 2) { struct desc_struct desc; u16 sel; memset (dt, 0, sizeof *dt); if (!ops->get_segment(ctxt, &sel, &desc, &base3, VCPU_SREG_LDTR)) return; dt->size = desc_limit_scaled(&desc); /* what if limit > 65535? */ dt->address = get_desc_base(&desc) | ((u64)base3 << 32); } else ops->get_gdt(ctxt, dt); } /* allowed just for 8 bytes segments */ static int read_segment_descriptor(struct x86_emulate_ctxt *ctxt, u16 selector, struct desc_struct *desc, ulong *desc_addr_p) { struct desc_ptr dt; u16 index = selector >> 3; ulong addr; get_descriptor_table_ptr(ctxt, selector, &dt); if (dt.size < index * 8 + 7) return emulate_gp(ctxt, selector & 0xfffc); *desc_addr_p = addr = dt.address + index * 8; return ctxt->ops->read_std(ctxt, addr, desc, sizeof *desc, &ctxt->exception); } /* allowed just for 8 bytes segments */ static int write_segment_descriptor(struct x86_emulate_ctxt *ctxt, u16 selector, struct desc_struct *desc) { struct desc_ptr dt; u16 index = selector >> 3; ulong addr; get_descriptor_table_ptr(ctxt, selector, &dt); if (dt.size < index * 8 + 7) return emulate_gp(ctxt, selector & 0xfffc); addr = dt.address + index * 8; return ctxt->ops->write_std(ctxt, addr, desc, sizeof *desc, &ctxt->exception); } /* Does not support long mode */ static int __load_segment_descriptor(struct x86_emulate_ctxt *ctxt, u16 selector, int seg, u8 cpl, bool in_task_switch, struct desc_struct *desc) { struct desc_struct seg_desc, old_desc; u8 dpl, rpl; unsigned err_vec = GP_VECTOR; u32 err_code = 0; bool null_selector = !(selector & ~0x3); /* 0000-0003 are null */ ulong desc_addr; int ret; u16 dummy; u32 base3 = 0; memset(&seg_desc, 0, sizeof seg_desc); if (ctxt->mode == X86EMUL_MODE_REAL) { /* set real mode segment descriptor (keep limit etc. for * unreal mode) */ ctxt->ops->get_segment(ctxt, &dummy, &seg_desc, NULL, seg); set_desc_base(&seg_desc, selector << 4); goto load; } else if (seg <= VCPU_SREG_GS && ctxt->mode == X86EMUL_MODE_VM86) { /* VM86 needs a clean new segment descriptor */ set_desc_base(&seg_desc, selector << 4); set_desc_limit(&seg_desc, 0xffff); seg_desc.type = 3; seg_desc.p = 1; seg_desc.s = 1; seg_desc.dpl = 3; goto load; } rpl = selector & 3; /* NULL selector is not valid for TR, CS and SS (except for long mode) */ if ((seg == VCPU_SREG_CS || (seg == VCPU_SREG_SS && (ctxt->mode != X86EMUL_MODE_PROT64 || rpl != cpl)) || seg == VCPU_SREG_TR) && null_selector) goto exception; /* TR should be in GDT only */ if (seg == VCPU_SREG_TR && (selector & (1 << 2))) goto exception; if (null_selector) /* for NULL selector skip all following checks */ goto load; ret = read_segment_descriptor(ctxt, selector, &seg_desc, &desc_addr); if (ret != X86EMUL_CONTINUE) return ret; err_code = selector & 0xfffc; err_vec = in_task_switch ? TS_VECTOR : GP_VECTOR; /* can't load system descriptor into segment selector */ if (seg <= VCPU_SREG_GS && !seg_desc.s) goto exception; if (!seg_desc.p) { err_vec = (seg == VCPU_SREG_SS) ? SS_VECTOR : NP_VECTOR; goto exception; } dpl = seg_desc.dpl; switch (seg) { case VCPU_SREG_SS: /* * segment is not a writable data segment or segment * selector's RPL != CPL or segment selector's RPL != CPL */ if (rpl != cpl || (seg_desc.type & 0xa) != 0x2 || dpl != cpl) goto exception; break; case VCPU_SREG_CS: if (!(seg_desc.type & 8)) goto exception; if (seg_desc.type & 4) { /* conforming */ if (dpl > cpl) goto exception; } else { /* nonconforming */ if (rpl > cpl || dpl != cpl) goto exception; } /* in long-mode d/b must be clear if l is set */ if (seg_desc.d && seg_desc.l) { u64 efer = 0; ctxt->ops->get_msr(ctxt, MSR_EFER, &efer); if (efer & EFER_LMA) goto exception; } /* CS(RPL) <- CPL */ selector = (selector & 0xfffc) | cpl; break; case VCPU_SREG_TR: if (seg_desc.s || (seg_desc.type != 1 && seg_desc.type != 9)) goto exception; old_desc = seg_desc; seg_desc.type |= 2; /* busy */ ret = ctxt->ops->cmpxchg_emulated(ctxt, desc_addr, &old_desc, &seg_desc, sizeof(seg_desc), &ctxt->exception); if (ret != X86EMUL_CONTINUE) return ret; break; case VCPU_SREG_LDTR: if (seg_desc.s || seg_desc.type != 2) goto exception; break; default: /* DS, ES, FS, or GS */ /* * segment is not a data or readable code segment or * ((segment is a data or nonconforming code segment) * and (both RPL and CPL > DPL)) */ if ((seg_desc.type & 0xa) == 0x8 || (((seg_desc.type & 0xc) != 0xc) && (rpl > dpl && cpl > dpl))) goto exception; break; } if (seg_desc.s) { /* mark segment as accessed */ seg_desc.type |= 1; ret = write_segment_descriptor(ctxt, selector, &seg_desc); if (ret != X86EMUL_CONTINUE) return ret; } else if (ctxt->mode == X86EMUL_MODE_PROT64) { ret = ctxt->ops->read_std(ctxt, desc_addr+8, &base3, sizeof(base3), &ctxt->exception); if (ret != X86EMUL_CONTINUE) return ret; } load: ctxt->ops->set_segment(ctxt, selector, &seg_desc, base3, seg); if (desc) *desc = seg_desc; return X86EMUL_CONTINUE; exception: return emulate_exception(ctxt, err_vec, err_code, true); } static int load_segment_descriptor(struct x86_emulate_ctxt *ctxt, u16 selector, int seg) { u8 cpl = ctxt->ops->cpl(ctxt); return __load_segment_descriptor(ctxt, selector, seg, cpl, false, NULL); } static void write_register_operand(struct operand *op) { /* The 4-byte case *is* correct: in 64-bit mode we zero-extend. */ switch (op->bytes) { case 1: *(u8 *)op->addr.reg = (u8)op->val; break; case 2: *(u16 *)op->addr.reg = (u16)op->val; break; case 4: *op->addr.reg = (u32)op->val; break; /* 64b: zero-extend */ case 8: *op->addr.reg = op->val; break; } } static int writeback(struct x86_emulate_ctxt *ctxt, struct operand *op) { switch (op->type) { case OP_REG: write_register_operand(op); break; case OP_MEM: if (ctxt->lock_prefix) return segmented_cmpxchg(ctxt, op->addr.mem, &op->orig_val, &op->val, op->bytes); else return segmented_write(ctxt, op->addr.mem, &op->val, op->bytes); break; case OP_MEM_STR: return segmented_write(ctxt, op->addr.mem, op->data, op->bytes * op->count); break; case OP_XMM: write_sse_reg(ctxt, &op->vec_val, op->addr.xmm); break; case OP_MM: write_mmx_reg(ctxt, &op->mm_val, op->addr.mm); break; case OP_NONE: /* no writeback */ break; default: break; } return X86EMUL_CONTINUE; } static int push(struct x86_emulate_ctxt *ctxt, void *data, int bytes) { struct segmented_address addr; rsp_increment(ctxt, -bytes); addr.ea = reg_read(ctxt, VCPU_REGS_RSP) & stack_mask(ctxt); addr.seg = VCPU_SREG_SS; return segmented_write(ctxt, addr, data, bytes); } static int em_push(struct x86_emulate_ctxt *ctxt) { /* Disable writeback. */ ctxt->dst.type = OP_NONE; return push(ctxt, &ctxt->src.val, ctxt->op_bytes); } static int emulate_pop(struct x86_emulate_ctxt *ctxt, void *dest, int len) { int rc; struct segmented_address addr; addr.ea = reg_read(ctxt, VCPU_REGS_RSP) & stack_mask(ctxt); addr.seg = VCPU_SREG_SS; rc = segmented_read(ctxt, addr, dest, len); if (rc != X86EMUL_CONTINUE) return rc; rsp_increment(ctxt, len); return rc; } static int em_pop(struct x86_emulate_ctxt *ctxt) { return emulate_pop(ctxt, &ctxt->dst.val, ctxt->op_bytes); } static int emulate_popf(struct x86_emulate_ctxt *ctxt, void *dest, int len) { int rc; unsigned long val, change_mask; int iopl = (ctxt->eflags & X86_EFLAGS_IOPL) >> IOPL_SHIFT; int cpl = ctxt->ops->cpl(ctxt); rc = emulate_pop(ctxt, &val, len); if (rc != X86EMUL_CONTINUE) return rc; change_mask = EFLG_CF | EFLG_PF | EFLG_AF | EFLG_ZF | EFLG_SF | EFLG_OF | EFLG_TF | EFLG_DF | EFLG_NT | EFLG_AC | EFLG_ID; switch(ctxt->mode) { case X86EMUL_MODE_PROT64: case X86EMUL_MODE_PROT32: case X86EMUL_MODE_PROT16: if (cpl == 0) change_mask |= EFLG_IOPL; if (cpl <= iopl) change_mask |= EFLG_IF; break; case X86EMUL_MODE_VM86: if (iopl < 3) return emulate_gp(ctxt, 0); change_mask |= EFLG_IF; break; default: /* real mode */ change_mask |= (EFLG_IOPL | EFLG_IF); break; } *(unsigned long *)dest = (ctxt->eflags & ~change_mask) | (val & change_mask); return rc; } static int em_popf(struct x86_emulate_ctxt *ctxt) { ctxt->dst.type = OP_REG; ctxt->dst.addr.reg = &ctxt->eflags; ctxt->dst.bytes = ctxt->op_bytes; return emulate_popf(ctxt, &ctxt->dst.val, ctxt->op_bytes); } static int em_enter(struct x86_emulate_ctxt *ctxt) { int rc; unsigned frame_size = ctxt->src.val; unsigned nesting_level = ctxt->src2.val & 31; ulong rbp; if (nesting_level) return X86EMUL_UNHANDLEABLE; rbp = reg_read(ctxt, VCPU_REGS_RBP); rc = push(ctxt, &rbp, stack_size(ctxt)); if (rc != X86EMUL_CONTINUE) return rc; assign_masked(reg_rmw(ctxt, VCPU_REGS_RBP), reg_read(ctxt, VCPU_REGS_RSP), stack_mask(ctxt)); assign_masked(reg_rmw(ctxt, VCPU_REGS_RSP), reg_read(ctxt, VCPU_REGS_RSP) - frame_size, stack_mask(ctxt)); return X86EMUL_CONTINUE; } static int em_leave(struct x86_emulate_ctxt *ctxt) { assign_masked(reg_rmw(ctxt, VCPU_REGS_RSP), reg_read(ctxt, VCPU_REGS_RBP), stack_mask(ctxt)); return emulate_pop(ctxt, reg_rmw(ctxt, VCPU_REGS_RBP), ctxt->op_bytes); } static int em_push_sreg(struct x86_emulate_ctxt *ctxt) { int seg = ctxt->src2.val; ctxt->src.val = get_segment_selector(ctxt, seg); return em_push(ctxt); } static int em_pop_sreg(struct x86_emulate_ctxt *ctxt) { int seg = ctxt->src2.val; unsigned long selector; int rc; rc = emulate_pop(ctxt, &selector, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; if (ctxt->modrm_reg == VCPU_SREG_SS) ctxt->interruptibility = KVM_X86_SHADOW_INT_MOV_SS; rc = load_segment_descriptor(ctxt, (u16)selector, seg); return rc; } static int em_pusha(struct x86_emulate_ctxt *ctxt) { unsigned long old_esp = reg_read(ctxt, VCPU_REGS_RSP); int rc = X86EMUL_CONTINUE; int reg = VCPU_REGS_RAX; while (reg <= VCPU_REGS_RDI) { (reg == VCPU_REGS_RSP) ? (ctxt->src.val = old_esp) : (ctxt->src.val = reg_read(ctxt, reg)); rc = em_push(ctxt); if (rc != X86EMUL_CONTINUE) return rc; ++reg; } return rc; } static int em_pushf(struct x86_emulate_ctxt *ctxt) { ctxt->src.val = (unsigned long)ctxt->eflags; return em_push(ctxt); } static int em_popa(struct x86_emulate_ctxt *ctxt) { int rc = X86EMUL_CONTINUE; int reg = VCPU_REGS_RDI; while (reg >= VCPU_REGS_RAX) { if (reg == VCPU_REGS_RSP) { rsp_increment(ctxt, ctxt->op_bytes); --reg; } rc = emulate_pop(ctxt, reg_rmw(ctxt, reg), ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) break; --reg; } return rc; } static int __emulate_int_real(struct x86_emulate_ctxt *ctxt, int irq) { const struct x86_emulate_ops *ops = ctxt->ops; int rc; struct desc_ptr dt; gva_t cs_addr; gva_t eip_addr; u16 cs, eip; /* TODO: Add limit checks */ ctxt->src.val = ctxt->eflags; rc = em_push(ctxt); if (rc != X86EMUL_CONTINUE) return rc; ctxt->eflags &= ~(EFLG_IF | EFLG_TF | EFLG_AC); ctxt->src.val = get_segment_selector(ctxt, VCPU_SREG_CS); rc = em_push(ctxt); if (rc != X86EMUL_CONTINUE) return rc; ctxt->src.val = ctxt->_eip; rc = em_push(ctxt); if (rc != X86EMUL_CONTINUE) return rc; ops->get_idt(ctxt, &dt); eip_addr = dt.address + (irq << 2); cs_addr = dt.address + (irq << 2) + 2; rc = ops->read_std(ctxt, cs_addr, &cs, 2, &ctxt->exception); if (rc != X86EMUL_CONTINUE) return rc; rc = ops->read_std(ctxt, eip_addr, &eip, 2, &ctxt->exception); if (rc != X86EMUL_CONTINUE) return rc; rc = load_segment_descriptor(ctxt, cs, VCPU_SREG_CS); if (rc != X86EMUL_CONTINUE) return rc; ctxt->_eip = eip; return rc; } int emulate_int_real(struct x86_emulate_ctxt *ctxt, int irq) { int rc; invalidate_registers(ctxt); rc = __emulate_int_real(ctxt, irq); if (rc == X86EMUL_CONTINUE) writeback_registers(ctxt); return rc; } static int emulate_int(struct x86_emulate_ctxt *ctxt, int irq) { switch(ctxt->mode) { case X86EMUL_MODE_REAL: return __emulate_int_real(ctxt, irq); case X86EMUL_MODE_VM86: case X86EMUL_MODE_PROT16: case X86EMUL_MODE_PROT32: case X86EMUL_MODE_PROT64: default: /* Protected mode interrupts unimplemented yet */ return X86EMUL_UNHANDLEABLE; } } static int emulate_iret_real(struct x86_emulate_ctxt *ctxt) { int rc = X86EMUL_CONTINUE; unsigned long temp_eip = 0; unsigned long temp_eflags = 0; unsigned long cs = 0; unsigned long mask = EFLG_CF | EFLG_PF | EFLG_AF | EFLG_ZF | EFLG_SF | EFLG_TF | EFLG_IF | EFLG_DF | EFLG_OF | EFLG_IOPL | EFLG_NT | EFLG_RF | EFLG_AC | EFLG_ID | (1 << 1); /* Last one is the reserved bit */ unsigned long vm86_mask = EFLG_VM | EFLG_VIF | EFLG_VIP; /* TODO: Add stack limit check */ rc = emulate_pop(ctxt, &temp_eip, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; if (temp_eip & ~0xffff) return emulate_gp(ctxt, 0); rc = emulate_pop(ctxt, &cs, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; rc = emulate_pop(ctxt, &temp_eflags, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; rc = load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS); if (rc != X86EMUL_CONTINUE) return rc; ctxt->_eip = temp_eip; if (ctxt->op_bytes == 4) ctxt->eflags = ((temp_eflags & mask) | (ctxt->eflags & vm86_mask)); else if (ctxt->op_bytes == 2) { ctxt->eflags &= ~0xffff; ctxt->eflags |= temp_eflags; } ctxt->eflags &= ~EFLG_RESERVED_ZEROS_MASK; /* Clear reserved zeros */ ctxt->eflags |= EFLG_RESERVED_ONE_MASK; return rc; } static int em_iret(struct x86_emulate_ctxt *ctxt) { switch(ctxt->mode) { case X86EMUL_MODE_REAL: return emulate_iret_real(ctxt); case X86EMUL_MODE_VM86: case X86EMUL_MODE_PROT16: case X86EMUL_MODE_PROT32: case X86EMUL_MODE_PROT64: default: /* iret from protected mode unimplemented yet */ return X86EMUL_UNHANDLEABLE; } } static int em_jmp_far(struct x86_emulate_ctxt *ctxt) { int rc; unsigned short sel, old_sel; struct desc_struct old_desc, new_desc; const struct x86_emulate_ops *ops = ctxt->ops; u8 cpl = ctxt->ops->cpl(ctxt); /* Assignment of RIP may only fail in 64-bit mode */ if (ctxt->mode == X86EMUL_MODE_PROT64) ops->get_segment(ctxt, &old_sel, &old_desc, NULL, VCPU_SREG_CS); memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2); rc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl, false, &new_desc); if (rc != X86EMUL_CONTINUE) return rc; rc = assign_eip_far(ctxt, ctxt->src.val, new_desc.l); if (rc != X86EMUL_CONTINUE) { WARN_ON(!ctxt->mode != X86EMUL_MODE_PROT64); /* assigning eip failed; restore the old cs */ ops->set_segment(ctxt, old_sel, &old_desc, 0, VCPU_SREG_CS); return rc; } return rc; } static int em_grp45(struct x86_emulate_ctxt *ctxt) { int rc = X86EMUL_CONTINUE; switch (ctxt->modrm_reg) { case 2: /* call near abs */ { long int old_eip; old_eip = ctxt->_eip; rc = assign_eip_near(ctxt, ctxt->src.val); if (rc != X86EMUL_CONTINUE) break; ctxt->src.val = old_eip; rc = em_push(ctxt); break; } case 4: /* jmp abs */ rc = assign_eip_near(ctxt, ctxt->src.val); break; case 5: /* jmp far */ rc = em_jmp_far(ctxt); break; case 6: /* push */ rc = em_push(ctxt); break; } return rc; } static int em_cmpxchg8b(struct x86_emulate_ctxt *ctxt) { u64 old = ctxt->dst.orig_val64; if (ctxt->dst.bytes == 16) return X86EMUL_UNHANDLEABLE; if (((u32) (old >> 0) != (u32) reg_read(ctxt, VCPU_REGS_RAX)) || ((u32) (old >> 32) != (u32) reg_read(ctxt, VCPU_REGS_RDX))) { *reg_write(ctxt, VCPU_REGS_RAX) = (u32) (old >> 0); *reg_write(ctxt, VCPU_REGS_RDX) = (u32) (old >> 32); ctxt->eflags &= ~EFLG_ZF; } else { ctxt->dst.val64 = ((u64)reg_read(ctxt, VCPU_REGS_RCX) << 32) | (u32) reg_read(ctxt, VCPU_REGS_RBX); ctxt->eflags |= EFLG_ZF; } return X86EMUL_CONTINUE; } static int em_ret(struct x86_emulate_ctxt *ctxt) { int rc; unsigned long eip; rc = emulate_pop(ctxt, &eip, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; return assign_eip_near(ctxt, eip); } static int em_ret_far(struct x86_emulate_ctxt *ctxt) { int rc; unsigned long eip, cs; u16 old_cs; int cpl = ctxt->ops->cpl(ctxt); struct desc_struct old_desc, new_desc; const struct x86_emulate_ops *ops = ctxt->ops; if (ctxt->mode == X86EMUL_MODE_PROT64) ops->get_segment(ctxt, &old_cs, &old_desc, NULL, VCPU_SREG_CS); rc = emulate_pop(ctxt, &eip, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; rc = emulate_pop(ctxt, &cs, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; /* Outer-privilege level return is not implemented */ if (ctxt->mode >= X86EMUL_MODE_PROT16 && (cs & 3) > cpl) return X86EMUL_UNHANDLEABLE; rc = __load_segment_descriptor(ctxt, (u16)cs, VCPU_SREG_CS, 0, false, &new_desc); if (rc != X86EMUL_CONTINUE) return rc; rc = assign_eip_far(ctxt, eip, new_desc.l); if (rc != X86EMUL_CONTINUE) { WARN_ON(!ctxt->mode != X86EMUL_MODE_PROT64); ops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS); } return rc; } static int em_ret_far_imm(struct x86_emulate_ctxt *ctxt) { int rc; rc = em_ret_far(ctxt); if (rc != X86EMUL_CONTINUE) return rc; rsp_increment(ctxt, ctxt->src.val); return X86EMUL_CONTINUE; } static int em_cmpxchg(struct x86_emulate_ctxt *ctxt) { /* Save real source value, then compare EAX against destination. */ ctxt->dst.orig_val = ctxt->dst.val; ctxt->dst.val = reg_read(ctxt, VCPU_REGS_RAX); ctxt->src.orig_val = ctxt->src.val; ctxt->src.val = ctxt->dst.orig_val; fastop(ctxt, em_cmp); if (ctxt->eflags & EFLG_ZF) { /* Success: write back to memory. */ ctxt->dst.val = ctxt->src.orig_val; } else { /* Failure: write the value we saw to EAX. */ ctxt->dst.type = OP_REG; ctxt->dst.addr.reg = reg_rmw(ctxt, VCPU_REGS_RAX); ctxt->dst.val = ctxt->dst.orig_val; } return X86EMUL_CONTINUE; } static int em_lseg(struct x86_emulate_ctxt *ctxt) { int seg = ctxt->src2.val; unsigned short sel; int rc; memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2); rc = load_segment_descriptor(ctxt, sel, seg); if (rc != X86EMUL_CONTINUE) return rc; ctxt->dst.val = ctxt->src.val; return rc; } static void setup_syscalls_segments(struct x86_emulate_ctxt *ctxt, struct desc_struct *cs, struct desc_struct *ss) { cs->l = 0; /* will be adjusted later */ set_desc_base(cs, 0); /* flat segment */ cs->g = 1; /* 4kb granularity */ set_desc_limit(cs, 0xfffff); /* 4GB limit */ cs->type = 0x0b; /* Read, Execute, Accessed */ cs->s = 1; cs->dpl = 0; /* will be adjusted later */ cs->p = 1; cs->d = 1; cs->avl = 0; set_desc_base(ss, 0); /* flat segment */ set_desc_limit(ss, 0xfffff); /* 4GB limit */ ss->g = 1; /* 4kb granularity */ ss->s = 1; ss->type = 0x03; /* Read/Write, Accessed */ ss->d = 1; /* 32bit stack segment */ ss->dpl = 0; ss->p = 1; ss->l = 0; ss->avl = 0; } static bool vendor_intel(struct x86_emulate_ctxt *ctxt) { u32 eax, ebx, ecx, edx; eax = ecx = 0; ctxt->ops->get_cpuid(ctxt, &eax, &ebx, &ecx, &edx); return ebx == X86EMUL_CPUID_VENDOR_GenuineIntel_ebx && ecx == X86EMUL_CPUID_VENDOR_GenuineIntel_ecx && edx == X86EMUL_CPUID_VENDOR_GenuineIntel_edx; } static bool em_syscall_is_enabled(struct x86_emulate_ctxt *ctxt) { const struct x86_emulate_ops *ops = ctxt->ops; u32 eax, ebx, ecx, edx; /* * syscall should always be enabled in longmode - so only become * vendor specific (cpuid) if other modes are active... */ if (ctxt->mode == X86EMUL_MODE_PROT64) return true; eax = 0x00000000; ecx = 0x00000000; ops->get_cpuid(ctxt, &eax, &ebx, &ecx, &edx); /* * Intel ("GenuineIntel") * remark: Intel CPUs only support "syscall" in 64bit * longmode. Also an 64bit guest with a * 32bit compat-app running will #UD !! While this * behaviour can be fixed (by emulating) into AMD * response - CPUs of AMD can't behave like Intel. */ if (ebx == X86EMUL_CPUID_VENDOR_GenuineIntel_ebx && ecx == X86EMUL_CPUID_VENDOR_GenuineIntel_ecx && edx == X86EMUL_CPUID_VENDOR_GenuineIntel_edx) return false; /* AMD ("AuthenticAMD") */ if (ebx == X86EMUL_CPUID_VENDOR_AuthenticAMD_ebx && ecx == X86EMUL_CPUID_VENDOR_AuthenticAMD_ecx && edx == X86EMUL_CPUID_VENDOR_AuthenticAMD_edx) return true; /* AMD ("AMDisbetter!") */ if (ebx == X86EMUL_CPUID_VENDOR_AMDisbetterI_ebx && ecx == X86EMUL_CPUID_VENDOR_AMDisbetterI_ecx && edx == X86EMUL_CPUID_VENDOR_AMDisbetterI_edx) return true; /* default: (not Intel, not AMD), apply Intel's stricter rules... */ return false; } static int em_syscall(struct x86_emulate_ctxt *ctxt) { const struct x86_emulate_ops *ops = ctxt->ops; struct desc_struct cs, ss; u64 msr_data; u16 cs_sel, ss_sel; u64 efer = 0; /* syscall is not available in real mode */ if (ctxt->mode == X86EMUL_MODE_REAL || ctxt->mode == X86EMUL_MODE_VM86) return emulate_ud(ctxt); if (!(em_syscall_is_enabled(ctxt))) return emulate_ud(ctxt); ops->get_msr(ctxt, MSR_EFER, &efer); setup_syscalls_segments(ctxt, &cs, &ss); if (!(efer & EFER_SCE)) return emulate_ud(ctxt); ops->get_msr(ctxt, MSR_STAR, &msr_data); msr_data >>= 32; cs_sel = (u16)(msr_data & 0xfffc); ss_sel = (u16)(msr_data + 8); if (efer & EFER_LMA) { cs.d = 0; cs.l = 1; } ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS); ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS); *reg_write(ctxt, VCPU_REGS_RCX) = ctxt->_eip; if (efer & EFER_LMA) { #ifdef CONFIG_X86_64 *reg_write(ctxt, VCPU_REGS_R11) = ctxt->eflags; ops->get_msr(ctxt, ctxt->mode == X86EMUL_MODE_PROT64 ? MSR_LSTAR : MSR_CSTAR, &msr_data); ctxt->_eip = msr_data; ops->get_msr(ctxt, MSR_SYSCALL_MASK, &msr_data); ctxt->eflags &= ~msr_data; #endif } else { /* legacy mode */ ops->get_msr(ctxt, MSR_STAR, &msr_data); ctxt->_eip = (u32)msr_data; ctxt->eflags &= ~(EFLG_VM | EFLG_IF); } return X86EMUL_CONTINUE; } static int em_sysenter(struct x86_emulate_ctxt *ctxt) { const struct x86_emulate_ops *ops = ctxt->ops; struct desc_struct cs, ss; u64 msr_data; u16 cs_sel, ss_sel; u64 efer = 0; ops->get_msr(ctxt, MSR_EFER, &efer); /* inject #GP if in real mode */ if (ctxt->mode == X86EMUL_MODE_REAL) return emulate_gp(ctxt, 0); /* * Not recognized on AMD in compat mode (but is recognized in legacy * mode). */ if ((ctxt->mode == X86EMUL_MODE_PROT32) && (efer & EFER_LMA) && !vendor_intel(ctxt)) return emulate_ud(ctxt); /* XXX sysenter/sysexit have not been tested in 64bit mode. * Therefore, we inject an #UD. */ if (ctxt->mode == X86EMUL_MODE_PROT64) return emulate_ud(ctxt); setup_syscalls_segments(ctxt, &cs, &ss); ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data); switch (ctxt->mode) { case X86EMUL_MODE_PROT32: if ((msr_data & 0xfffc) == 0x0) return emulate_gp(ctxt, 0); break; case X86EMUL_MODE_PROT64: if (msr_data == 0x0) return emulate_gp(ctxt, 0); break; default: break; } ctxt->eflags &= ~(EFLG_VM | EFLG_IF); cs_sel = (u16)msr_data; cs_sel &= ~SELECTOR_RPL_MASK; ss_sel = cs_sel + 8; ss_sel &= ~SELECTOR_RPL_MASK; if (ctxt->mode == X86EMUL_MODE_PROT64 || (efer & EFER_LMA)) { cs.d = 0; cs.l = 1; } ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS); ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS); ops->get_msr(ctxt, MSR_IA32_SYSENTER_EIP, &msr_data); ctxt->_eip = msr_data; ops->get_msr(ctxt, MSR_IA32_SYSENTER_ESP, &msr_data); *reg_write(ctxt, VCPU_REGS_RSP) = msr_data; return X86EMUL_CONTINUE; } static int em_sysexit(struct x86_emulate_ctxt *ctxt) { const struct x86_emulate_ops *ops = ctxt->ops; struct desc_struct cs, ss; u64 msr_data, rcx, rdx; int usermode; u16 cs_sel = 0, ss_sel = 0; /* inject #GP if in real mode or Virtual 8086 mode */ if (ctxt->mode == X86EMUL_MODE_REAL || ctxt->mode == X86EMUL_MODE_VM86) return emulate_gp(ctxt, 0); setup_syscalls_segments(ctxt, &cs, &ss); if ((ctxt->rex_prefix & 0x8) != 0x0) usermode = X86EMUL_MODE_PROT64; else usermode = X86EMUL_MODE_PROT32; rcx = reg_read(ctxt, VCPU_REGS_RCX); rdx = reg_read(ctxt, VCPU_REGS_RDX); cs.dpl = 3; ss.dpl = 3; ops->get_msr(ctxt, MSR_IA32_SYSENTER_CS, &msr_data); switch (usermode) { case X86EMUL_MODE_PROT32: cs_sel = (u16)(msr_data + 16); if ((msr_data & 0xfffc) == 0x0) return emulate_gp(ctxt, 0); ss_sel = (u16)(msr_data + 24); break; case X86EMUL_MODE_PROT64: cs_sel = (u16)(msr_data + 32); if (msr_data == 0x0) return emulate_gp(ctxt, 0); ss_sel = cs_sel + 8; cs.d = 0; cs.l = 1; if (is_noncanonical_address(rcx) || is_noncanonical_address(rdx)) return emulate_gp(ctxt, 0); break; } cs_sel |= SELECTOR_RPL_MASK; ss_sel |= SELECTOR_RPL_MASK; ops->set_segment(ctxt, cs_sel, &cs, 0, VCPU_SREG_CS); ops->set_segment(ctxt, ss_sel, &ss, 0, VCPU_SREG_SS); ctxt->_eip = rdx; *reg_write(ctxt, VCPU_REGS_RSP) = rcx; return X86EMUL_CONTINUE; } static bool emulator_bad_iopl(struct x86_emulate_ctxt *ctxt) { int iopl; if (ctxt->mode == X86EMUL_MODE_REAL) return false; if (ctxt->mode == X86EMUL_MODE_VM86) return true; iopl = (ctxt->eflags & X86_EFLAGS_IOPL) >> IOPL_SHIFT; return ctxt->ops->cpl(ctxt) > iopl; } static bool emulator_io_port_access_allowed(struct x86_emulate_ctxt *ctxt, u16 port, u16 len) { const struct x86_emulate_ops *ops = ctxt->ops; struct desc_struct tr_seg; u32 base3; int r; u16 tr, io_bitmap_ptr, perm, bit_idx = port & 0x7; unsigned mask = (1 << len) - 1; unsigned long base; ops->get_segment(ctxt, &tr, &tr_seg, &base3, VCPU_SREG_TR); if (!tr_seg.p) return false; if (desc_limit_scaled(&tr_seg) < 103) return false; base = get_desc_base(&tr_seg); #ifdef CONFIG_X86_64 base |= ((u64)base3) << 32; #endif r = ops->read_std(ctxt, base + 102, &io_bitmap_ptr, 2, NULL); if (r != X86EMUL_CONTINUE) return false; if (io_bitmap_ptr + port/8 > desc_limit_scaled(&tr_seg)) return false; r = ops->read_std(ctxt, base + io_bitmap_ptr + port/8, &perm, 2, NULL); if (r != X86EMUL_CONTINUE) return false; if ((perm >> bit_idx) & mask) return false; return true; } static bool emulator_io_permited(struct x86_emulate_ctxt *ctxt, u16 port, u16 len) { if (ctxt->perm_ok) return true; if (emulator_bad_iopl(ctxt)) if (!emulator_io_port_access_allowed(ctxt, port, len)) return false; ctxt->perm_ok = true; return true; } static void save_state_to_tss16(struct x86_emulate_ctxt *ctxt, struct tss_segment_16 *tss) { tss->ip = ctxt->_eip; tss->flag = ctxt->eflags; tss->ax = reg_read(ctxt, VCPU_REGS_RAX); tss->cx = reg_read(ctxt, VCPU_REGS_RCX); tss->dx = reg_read(ctxt, VCPU_REGS_RDX); tss->bx = reg_read(ctxt, VCPU_REGS_RBX); tss->sp = reg_read(ctxt, VCPU_REGS_RSP); tss->bp = reg_read(ctxt, VCPU_REGS_RBP); tss->si = reg_read(ctxt, VCPU_REGS_RSI); tss->di = reg_read(ctxt, VCPU_REGS_RDI); tss->es = get_segment_selector(ctxt, VCPU_SREG_ES); tss->cs = get_segment_selector(ctxt, VCPU_SREG_CS); tss->ss = get_segment_selector(ctxt, VCPU_SREG_SS); tss->ds = get_segment_selector(ctxt, VCPU_SREG_DS); tss->ldt = get_segment_selector(ctxt, VCPU_SREG_LDTR); } static int load_state_from_tss16(struct x86_emulate_ctxt *ctxt, struct tss_segment_16 *tss) { int ret; u8 cpl; ctxt->_eip = tss->ip; ctxt->eflags = tss->flag | 2; *reg_write(ctxt, VCPU_REGS_RAX) = tss->ax; *reg_write(ctxt, VCPU_REGS_RCX) = tss->cx; *reg_write(ctxt, VCPU_REGS_RDX) = tss->dx; *reg_write(ctxt, VCPU_REGS_RBX) = tss->bx; *reg_write(ctxt, VCPU_REGS_RSP) = tss->sp; *reg_write(ctxt, VCPU_REGS_RBP) = tss->bp; *reg_write(ctxt, VCPU_REGS_RSI) = tss->si; *reg_write(ctxt, VCPU_REGS_RDI) = tss->di; /* * SDM says that segment selectors are loaded before segment * descriptors */ set_segment_selector(ctxt, tss->ldt, VCPU_SREG_LDTR); set_segment_selector(ctxt, tss->es, VCPU_SREG_ES); set_segment_selector(ctxt, tss->cs, VCPU_SREG_CS); set_segment_selector(ctxt, tss->ss, VCPU_SREG_SS); set_segment_selector(ctxt, tss->ds, VCPU_SREG_DS); cpl = tss->cs & 3; /* * Now load segment descriptors. If fault happens at this stage * it is handled in a context of new task */ ret = __load_segment_descriptor(ctxt, tss->ldt, VCPU_SREG_LDTR, cpl, true, NULL); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->es, VCPU_SREG_ES, cpl, true, NULL); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->cs, VCPU_SREG_CS, cpl, true, NULL); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->ss, VCPU_SREG_SS, cpl, true, NULL); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->ds, VCPU_SREG_DS, cpl, true, NULL); if (ret != X86EMUL_CONTINUE) return ret; return X86EMUL_CONTINUE; } static int task_switch_16(struct x86_emulate_ctxt *ctxt, u16 tss_selector, u16 old_tss_sel, ulong old_tss_base, struct desc_struct *new_desc) { const struct x86_emulate_ops *ops = ctxt->ops; struct tss_segment_16 tss_seg; int ret; u32 new_tss_base = get_desc_base(new_desc); ret = ops->read_std(ctxt, old_tss_base, &tss_seg, sizeof tss_seg, &ctxt->exception); if (ret != X86EMUL_CONTINUE) /* FIXME: need to provide precise fault address */ return ret; save_state_to_tss16(ctxt, &tss_seg); ret = ops->write_std(ctxt, old_tss_base, &tss_seg, sizeof tss_seg, &ctxt->exception); if (ret != X86EMUL_CONTINUE) /* FIXME: need to provide precise fault address */ return ret; ret = ops->read_std(ctxt, new_tss_base, &tss_seg, sizeof tss_seg, &ctxt->exception); if (ret != X86EMUL_CONTINUE) /* FIXME: need to provide precise fault address */ return ret; if (old_tss_sel != 0xffff) { tss_seg.prev_task_link = old_tss_sel; ret = ops->write_std(ctxt, new_tss_base, &tss_seg.prev_task_link, sizeof tss_seg.prev_task_link, &ctxt->exception); if (ret != X86EMUL_CONTINUE) /* FIXME: need to provide precise fault address */ return ret; } return load_state_from_tss16(ctxt, &tss_seg); } static void save_state_to_tss32(struct x86_emulate_ctxt *ctxt, struct tss_segment_32 *tss) { /* CR3 and ldt selector are not saved intentionally */ tss->eip = ctxt->_eip; tss->eflags = ctxt->eflags; tss->eax = reg_read(ctxt, VCPU_REGS_RAX); tss->ecx = reg_read(ctxt, VCPU_REGS_RCX); tss->edx = reg_read(ctxt, VCPU_REGS_RDX); tss->ebx = reg_read(ctxt, VCPU_REGS_RBX); tss->esp = reg_read(ctxt, VCPU_REGS_RSP); tss->ebp = reg_read(ctxt, VCPU_REGS_RBP); tss->esi = reg_read(ctxt, VCPU_REGS_RSI); tss->edi = reg_read(ctxt, VCPU_REGS_RDI); tss->es = get_segment_selector(ctxt, VCPU_SREG_ES); tss->cs = get_segment_selector(ctxt, VCPU_SREG_CS); tss->ss = get_segment_selector(ctxt, VCPU_SREG_SS); tss->ds = get_segment_selector(ctxt, VCPU_SREG_DS); tss->fs = get_segment_selector(ctxt, VCPU_SREG_FS); tss->gs = get_segment_selector(ctxt, VCPU_SREG_GS); } static int load_state_from_tss32(struct x86_emulate_ctxt *ctxt, struct tss_segment_32 *tss) { int ret; u8 cpl; if (ctxt->ops->set_cr(ctxt, 3, tss->cr3)) return emulate_gp(ctxt, 0); ctxt->_eip = tss->eip; ctxt->eflags = tss->eflags | 2; /* General purpose registers */ *reg_write(ctxt, VCPU_REGS_RAX) = tss->eax; *reg_write(ctxt, VCPU_REGS_RCX) = tss->ecx; *reg_write(ctxt, VCPU_REGS_RDX) = tss->edx; *reg_write(ctxt, VCPU_REGS_RBX) = tss->ebx; *reg_write(ctxt, VCPU_REGS_RSP) = tss->esp; *reg_write(ctxt, VCPU_REGS_RBP) = tss->ebp; *reg_write(ctxt, VCPU_REGS_RSI) = tss->esi; *reg_write(ctxt, VCPU_REGS_RDI) = tss->edi; /* * SDM says that segment selectors are loaded before segment * descriptors. This is important because CPL checks will * use CS.RPL. */ set_segment_selector(ctxt, tss->ldt_selector, VCPU_SREG_LDTR); set_segment_selector(ctxt, tss->es, VCPU_SREG_ES); set_segment_selector(ctxt, tss->cs, VCPU_SREG_CS); set_segment_selector(ctxt, tss->ss, VCPU_SREG_SS); set_segment_selector(ctxt, tss->ds, VCPU_SREG_DS); set_segment_selector(ctxt, tss->fs, VCPU_SREG_FS); set_segment_selector(ctxt, tss->gs, VCPU_SREG_GS); /* * If we're switching between Protected Mode and VM86, we need to make * sure to update the mode before loading the segment descriptors so * that the selectors are interpreted correctly. */ if (ctxt->eflags & X86_EFLAGS_VM) { ctxt->mode = X86EMUL_MODE_VM86; cpl = 3; } else { ctxt->mode = X86EMUL_MODE_PROT32; cpl = tss->cs & 3; } /* * Now load segment descriptors. If fault happenes at this stage * it is handled in a context of new task */ ret = __load_segment_descriptor(ctxt, tss->ldt_selector, VCPU_SREG_LDTR, cpl, true, NULL); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->es, VCPU_SREG_ES, cpl, true, NULL); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->cs, VCPU_SREG_CS, cpl, true, NULL); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->ss, VCPU_SREG_SS, cpl, true, NULL); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->ds, VCPU_SREG_DS, cpl, true, NULL); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->fs, VCPU_SREG_FS, cpl, true, NULL); if (ret != X86EMUL_CONTINUE) return ret; ret = __load_segment_descriptor(ctxt, tss->gs, VCPU_SREG_GS, cpl, true, NULL); if (ret != X86EMUL_CONTINUE) return ret; return X86EMUL_CONTINUE; } static int task_switch_32(struct x86_emulate_ctxt *ctxt, u16 tss_selector, u16 old_tss_sel, ulong old_tss_base, struct desc_struct *new_desc) { const struct x86_emulate_ops *ops = ctxt->ops; struct tss_segment_32 tss_seg; int ret; u32 new_tss_base = get_desc_base(new_desc); u32 eip_offset = offsetof(struct tss_segment_32, eip); u32 ldt_sel_offset = offsetof(struct tss_segment_32, ldt_selector); ret = ops->read_std(ctxt, old_tss_base, &tss_seg, sizeof tss_seg, &ctxt->exception); if (ret != X86EMUL_CONTINUE) /* FIXME: need to provide precise fault address */ return ret; save_state_to_tss32(ctxt, &tss_seg); /* Only GP registers and segment selectors are saved */ ret = ops->write_std(ctxt, old_tss_base + eip_offset, &tss_seg.eip, ldt_sel_offset - eip_offset, &ctxt->exception); if (ret != X86EMUL_CONTINUE) /* FIXME: need to provide precise fault address */ return ret; ret = ops->read_std(ctxt, new_tss_base, &tss_seg, sizeof tss_seg, &ctxt->exception); if (ret != X86EMUL_CONTINUE) /* FIXME: need to provide precise fault address */ return ret; if (old_tss_sel != 0xffff) { tss_seg.prev_task_link = old_tss_sel; ret = ops->write_std(ctxt, new_tss_base, &tss_seg.prev_task_link, sizeof tss_seg.prev_task_link, &ctxt->exception); if (ret != X86EMUL_CONTINUE) /* FIXME: need to provide precise fault address */ return ret; } return load_state_from_tss32(ctxt, &tss_seg); } static int emulator_do_task_switch(struct x86_emulate_ctxt *ctxt, u16 tss_selector, int idt_index, int reason, bool has_error_code, u32 error_code) { const struct x86_emulate_ops *ops = ctxt->ops; struct desc_struct curr_tss_desc, next_tss_desc; int ret; u16 old_tss_sel = get_segment_selector(ctxt, VCPU_SREG_TR); ulong old_tss_base = ops->get_cached_segment_base(ctxt, VCPU_SREG_TR); u32 desc_limit; ulong desc_addr; /* FIXME: old_tss_base == ~0 ? */ ret = read_segment_descriptor(ctxt, tss_selector, &next_tss_desc, &desc_addr); if (ret != X86EMUL_CONTINUE) return ret; ret = read_segment_descriptor(ctxt, old_tss_sel, &curr_tss_desc, &desc_addr); if (ret != X86EMUL_CONTINUE) return ret; /* FIXME: check that next_tss_desc is tss */ /* * Check privileges. The three cases are task switch caused by... * * 1. jmp/call/int to task gate: Check against DPL of the task gate * 2. Exception/IRQ/iret: No check is performed * 3. jmp/call to TSS: Check against DPL of the TSS */ if (reason == TASK_SWITCH_GATE) { if (idt_index != -1) { /* Software interrupts */ struct desc_struct task_gate_desc; int dpl; ret = read_interrupt_descriptor(ctxt, idt_index, &task_gate_desc); if (ret != X86EMUL_CONTINUE) return ret; dpl = task_gate_desc.dpl; if ((tss_selector & 3) > dpl || ops->cpl(ctxt) > dpl) return emulate_gp(ctxt, (idt_index << 3) | 0x2); } } else if (reason != TASK_SWITCH_IRET) { int dpl = next_tss_desc.dpl; if ((tss_selector & 3) > dpl || ops->cpl(ctxt) > dpl) return emulate_gp(ctxt, tss_selector); } desc_limit = desc_limit_scaled(&next_tss_desc); if (!next_tss_desc.p || ((desc_limit < 0x67 && (next_tss_desc.type & 8)) || desc_limit < 0x2b)) { return emulate_ts(ctxt, tss_selector & 0xfffc); } if (reason == TASK_SWITCH_IRET || reason == TASK_SWITCH_JMP) { curr_tss_desc.type &= ~(1 << 1); /* clear busy flag */ write_segment_descriptor(ctxt, old_tss_sel, &curr_tss_desc); } if (reason == TASK_SWITCH_IRET) ctxt->eflags = ctxt->eflags & ~X86_EFLAGS_NT; /* set back link to prev task only if NT bit is set in eflags note that old_tss_sel is not used after this point */ if (reason != TASK_SWITCH_CALL && reason != TASK_SWITCH_GATE) old_tss_sel = 0xffff; if (next_tss_desc.type & 8) ret = task_switch_32(ctxt, tss_selector, old_tss_sel, old_tss_base, &next_tss_desc); else ret = task_switch_16(ctxt, tss_selector, old_tss_sel, old_tss_base, &next_tss_desc); if (ret != X86EMUL_CONTINUE) return ret; if (reason == TASK_SWITCH_CALL || reason == TASK_SWITCH_GATE) ctxt->eflags = ctxt->eflags | X86_EFLAGS_NT; if (reason != TASK_SWITCH_IRET) { next_tss_desc.type |= (1 << 1); /* set busy flag */ write_segment_descriptor(ctxt, tss_selector, &next_tss_desc); } ops->set_cr(ctxt, 0, ops->get_cr(ctxt, 0) | X86_CR0_TS); ops->set_segment(ctxt, tss_selector, &next_tss_desc, 0, VCPU_SREG_TR); if (has_error_code) { ctxt->op_bytes = ctxt->ad_bytes = (next_tss_desc.type & 8) ? 4 : 2; ctxt->lock_prefix = 0; ctxt->src.val = (unsigned long) error_code; ret = em_push(ctxt); } return ret; } int emulator_task_switch(struct x86_emulate_ctxt *ctxt, u16 tss_selector, int idt_index, int reason, bool has_error_code, u32 error_code) { int rc; invalidate_registers(ctxt); ctxt->_eip = ctxt->eip; ctxt->dst.type = OP_NONE; rc = emulator_do_task_switch(ctxt, tss_selector, idt_index, reason, has_error_code, error_code); if (rc == X86EMUL_CONTINUE) { ctxt->eip = ctxt->_eip; writeback_registers(ctxt); } return (rc == X86EMUL_UNHANDLEABLE) ? EMULATION_FAILED : EMULATION_OK; } static void string_addr_inc(struct x86_emulate_ctxt *ctxt, int reg, struct operand *op) { int df = (ctxt->eflags & EFLG_DF) ? -op->count : op->count; register_address_increment(ctxt, reg_rmw(ctxt, reg), df * op->bytes); op->addr.mem.ea = register_address(ctxt, reg_read(ctxt, reg)); } static int em_das(struct x86_emulate_ctxt *ctxt) { u8 al, old_al; bool af, cf, old_cf; cf = ctxt->eflags & X86_EFLAGS_CF; al = ctxt->dst.val; old_al = al; old_cf = cf; cf = false; af = ctxt->eflags & X86_EFLAGS_AF; if ((al & 0x0f) > 9 || af) { al -= 6; cf = old_cf | (al >= 250); af = true; } else { af = false; } if (old_al > 0x99 || old_cf) { al -= 0x60; cf = true; } ctxt->dst.val = al; /* Set PF, ZF, SF */ ctxt->src.type = OP_IMM; ctxt->src.val = 0; ctxt->src.bytes = 1; fastop(ctxt, em_or); ctxt->eflags &= ~(X86_EFLAGS_AF | X86_EFLAGS_CF); if (cf) ctxt->eflags |= X86_EFLAGS_CF; if (af) ctxt->eflags |= X86_EFLAGS_AF; return X86EMUL_CONTINUE; } static int em_aam(struct x86_emulate_ctxt *ctxt) { u8 al, ah; if (ctxt->src.val == 0) return emulate_de(ctxt); al = ctxt->dst.val & 0xff; ah = al / ctxt->src.val; al %= ctxt->src.val; ctxt->dst.val = (ctxt->dst.val & 0xffff0000) | al | (ah << 8); /* Set PF, ZF, SF */ ctxt->src.type = OP_IMM; ctxt->src.val = 0; ctxt->src.bytes = 1; fastop(ctxt, em_or); return X86EMUL_CONTINUE; } static int em_aad(struct x86_emulate_ctxt *ctxt) { u8 al = ctxt->dst.val & 0xff; u8 ah = (ctxt->dst.val >> 8) & 0xff; al = (al + (ah * ctxt->src.val)) & 0xff; ctxt->dst.val = (ctxt->dst.val & 0xffff0000) | al; /* Set PF, ZF, SF */ ctxt->src.type = OP_IMM; ctxt->src.val = 0; ctxt->src.bytes = 1; fastop(ctxt, em_or); return X86EMUL_CONTINUE; } static int em_call(struct x86_emulate_ctxt *ctxt) { int rc; long rel = ctxt->src.val; ctxt->src.val = (unsigned long)ctxt->_eip; rc = jmp_rel(ctxt, rel); if (rc != X86EMUL_CONTINUE) return rc; return em_push(ctxt); } static int em_call_far(struct x86_emulate_ctxt *ctxt) { u16 sel, old_cs; ulong old_eip; int rc; struct desc_struct old_desc, new_desc; const struct x86_emulate_ops *ops = ctxt->ops; int cpl = ctxt->ops->cpl(ctxt); old_eip = ctxt->_eip; ops->get_segment(ctxt, &old_cs, &old_desc, NULL, VCPU_SREG_CS); memcpy(&sel, ctxt->src.valptr + ctxt->op_bytes, 2); rc = __load_segment_descriptor(ctxt, sel, VCPU_SREG_CS, cpl, false, &new_desc); if (rc != X86EMUL_CONTINUE) return X86EMUL_CONTINUE; rc = assign_eip_far(ctxt, ctxt->src.val, new_desc.l); if (rc != X86EMUL_CONTINUE) goto fail; ctxt->src.val = old_cs; rc = em_push(ctxt); if (rc != X86EMUL_CONTINUE) goto fail; ctxt->src.val = old_eip; rc = em_push(ctxt); /* If we failed, we tainted the memory, but the very least we should restore cs */ if (rc != X86EMUL_CONTINUE) goto fail; return rc; fail: ops->set_segment(ctxt, old_cs, &old_desc, 0, VCPU_SREG_CS); return rc; } static int em_ret_near_imm(struct x86_emulate_ctxt *ctxt) { int rc; unsigned long eip; rc = emulate_pop(ctxt, &eip, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; rc = assign_eip_near(ctxt, eip); if (rc != X86EMUL_CONTINUE) return rc; rsp_increment(ctxt, ctxt->src.val); return X86EMUL_CONTINUE; } static int em_xchg(struct x86_emulate_ctxt *ctxt) { /* Write back the register source. */ ctxt->src.val = ctxt->dst.val; write_register_operand(&ctxt->src); /* Write back the memory destination with implicit LOCK prefix. */ ctxt->dst.val = ctxt->src.orig_val; ctxt->lock_prefix = 1; return X86EMUL_CONTINUE; } static int em_imul_3op(struct x86_emulate_ctxt *ctxt) { ctxt->dst.val = ctxt->src2.val; return fastop(ctxt, em_imul); } static int em_cwd(struct x86_emulate_ctxt *ctxt) { ctxt->dst.type = OP_REG; ctxt->dst.bytes = ctxt->src.bytes; ctxt->dst.addr.reg = reg_rmw(ctxt, VCPU_REGS_RDX); ctxt->dst.val = ~((ctxt->src.val >> (ctxt->src.bytes * 8 - 1)) - 1); return X86EMUL_CONTINUE; } static int em_rdtsc(struct x86_emulate_ctxt *ctxt) { u64 tsc = 0; ctxt->ops->get_msr(ctxt, MSR_IA32_TSC, &tsc); *reg_write(ctxt, VCPU_REGS_RAX) = (u32)tsc; *reg_write(ctxt, VCPU_REGS_RDX) = tsc >> 32; return X86EMUL_CONTINUE; } static int em_rdpmc(struct x86_emulate_ctxt *ctxt) { u64 pmc; if (ctxt->ops->read_pmc(ctxt, reg_read(ctxt, VCPU_REGS_RCX), &pmc)) return emulate_gp(ctxt, 0); *reg_write(ctxt, VCPU_REGS_RAX) = (u32)pmc; *reg_write(ctxt, VCPU_REGS_RDX) = pmc >> 32; return X86EMUL_CONTINUE; } static int em_mov(struct x86_emulate_ctxt *ctxt) { memcpy(ctxt->dst.valptr, ctxt->src.valptr, sizeof(ctxt->src.valptr)); return X86EMUL_CONTINUE; } #define FFL(x) bit(X86_FEATURE_##x) static int em_movbe(struct x86_emulate_ctxt *ctxt) { u32 ebx, ecx, edx, eax = 1; u16 tmp; /* * Check MOVBE is set in the guest-visible CPUID leaf. */ ctxt->ops->get_cpuid(ctxt, &eax, &ebx, &ecx, &edx); if (!(ecx & FFL(MOVBE))) return emulate_ud(ctxt); switch (ctxt->op_bytes) { case 2: /* * From MOVBE definition: "...When the operand size is 16 bits, * the upper word of the destination register remains unchanged * ..." * * Both casting ->valptr and ->val to u16 breaks strict aliasing * rules so we have to do the operation almost per hand. */ tmp = (u16)ctxt->src.val; ctxt->dst.val &= ~0xffffUL; ctxt->dst.val |= (unsigned long)swab16(tmp); break; case 4: ctxt->dst.val = swab32((u32)ctxt->src.val); break; case 8: ctxt->dst.val = swab64(ctxt->src.val); break; default: BUG(); } return X86EMUL_CONTINUE; } static int em_cr_write(struct x86_emulate_ctxt *ctxt) { if (ctxt->ops->set_cr(ctxt, ctxt->modrm_reg, ctxt->src.val)) return emulate_gp(ctxt, 0); /* Disable writeback. */ ctxt->dst.type = OP_NONE; return X86EMUL_CONTINUE; } static int em_dr_write(struct x86_emulate_ctxt *ctxt) { unsigned long val; if (ctxt->mode == X86EMUL_MODE_PROT64) val = ctxt->src.val & ~0ULL; else val = ctxt->src.val & ~0U; /* #UD condition is already handled. */ if (ctxt->ops->set_dr(ctxt, ctxt->modrm_reg, val) < 0) return emulate_gp(ctxt, 0); /* Disable writeback. */ ctxt->dst.type = OP_NONE; return X86EMUL_CONTINUE; } static int em_wrmsr(struct x86_emulate_ctxt *ctxt) { u64 msr_data; msr_data = (u32)reg_read(ctxt, VCPU_REGS_RAX) | ((u64)reg_read(ctxt, VCPU_REGS_RDX) << 32); if (ctxt->ops->set_msr(ctxt, reg_read(ctxt, VCPU_REGS_RCX), msr_data)) return emulate_gp(ctxt, 0); return X86EMUL_CONTINUE; } static int em_rdmsr(struct x86_emulate_ctxt *ctxt) { u64 msr_data; if (ctxt->ops->get_msr(ctxt, reg_read(ctxt, VCPU_REGS_RCX), &msr_data)) return emulate_gp(ctxt, 0); *reg_write(ctxt, VCPU_REGS_RAX) = (u32)msr_data; *reg_write(ctxt, VCPU_REGS_RDX) = msr_data >> 32; return X86EMUL_CONTINUE; } static int em_mov_rm_sreg(struct x86_emulate_ctxt *ctxt) { if (ctxt->modrm_reg > VCPU_SREG_GS) return emulate_ud(ctxt); ctxt->dst.val = get_segment_selector(ctxt, ctxt->modrm_reg); return X86EMUL_CONTINUE; } static int em_mov_sreg_rm(struct x86_emulate_ctxt *ctxt) { u16 sel = ctxt->src.val; if (ctxt->modrm_reg == VCPU_SREG_CS || ctxt->modrm_reg > VCPU_SREG_GS) return emulate_ud(ctxt); if (ctxt->modrm_reg == VCPU_SREG_SS) ctxt->interruptibility = KVM_X86_SHADOW_INT_MOV_SS; /* Disable writeback. */ ctxt->dst.type = OP_NONE; return load_segment_descriptor(ctxt, sel, ctxt->modrm_reg); } static int em_lldt(struct x86_emulate_ctxt *ctxt) { u16 sel = ctxt->src.val; /* Disable writeback. */ ctxt->dst.type = OP_NONE; return load_segment_descriptor(ctxt, sel, VCPU_SREG_LDTR); } static int em_ltr(struct x86_emulate_ctxt *ctxt) { u16 sel = ctxt->src.val; /* Disable writeback. */ ctxt->dst.type = OP_NONE; return load_segment_descriptor(ctxt, sel, VCPU_SREG_TR); } static int em_invlpg(struct x86_emulate_ctxt *ctxt) { int rc; ulong linear; rc = linearize(ctxt, ctxt->src.addr.mem, 1, false, &linear); if (rc == X86EMUL_CONTINUE) ctxt->ops->invlpg(ctxt, linear); /* Disable writeback. */ ctxt->dst.type = OP_NONE; return X86EMUL_CONTINUE; } static int em_clts(struct x86_emulate_ctxt *ctxt) { ulong cr0; cr0 = ctxt->ops->get_cr(ctxt, 0); cr0 &= ~X86_CR0_TS; ctxt->ops->set_cr(ctxt, 0, cr0); return X86EMUL_CONTINUE; } static int em_vmcall(struct x86_emulate_ctxt *ctxt) { int rc = ctxt->ops->fix_hypercall(ctxt); if (rc != X86EMUL_CONTINUE) return rc; /* Let the processor re-execute the fixed hypercall */ ctxt->_eip = ctxt->eip; /* Disable writeback. */ ctxt->dst.type = OP_NONE; return X86EMUL_CONTINUE; } static int emulate_store_desc_ptr(struct x86_emulate_ctxt *ctxt, void (*get)(struct x86_emulate_ctxt *ctxt, struct desc_ptr *ptr)) { struct desc_ptr desc_ptr; if (ctxt->mode == X86EMUL_MODE_PROT64) ctxt->op_bytes = 8; get(ctxt, &desc_ptr); if (ctxt->op_bytes == 2) { ctxt->op_bytes = 4; desc_ptr.address &= 0x00ffffff; } /* Disable writeback. */ ctxt->dst.type = OP_NONE; return segmented_write(ctxt, ctxt->dst.addr.mem, &desc_ptr, 2 + ctxt->op_bytes); } static int em_sgdt(struct x86_emulate_ctxt *ctxt) { return emulate_store_desc_ptr(ctxt, ctxt->ops->get_gdt); } static int em_sidt(struct x86_emulate_ctxt *ctxt) { return emulate_store_desc_ptr(ctxt, ctxt->ops->get_idt); } static int em_lgdt(struct x86_emulate_ctxt *ctxt) { struct desc_ptr desc_ptr; int rc; if (ctxt->mode == X86EMUL_MODE_PROT64) ctxt->op_bytes = 8; rc = read_descriptor(ctxt, ctxt->src.addr.mem, &desc_ptr.size, &desc_ptr.address, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; ctxt->ops->set_gdt(ctxt, &desc_ptr); /* Disable writeback. */ ctxt->dst.type = OP_NONE; return X86EMUL_CONTINUE; } static int em_vmmcall(struct x86_emulate_ctxt *ctxt) { int rc; rc = ctxt->ops->fix_hypercall(ctxt); /* Disable writeback. */ ctxt->dst.type = OP_NONE; return rc; } static int em_lidt(struct x86_emulate_ctxt *ctxt) { struct desc_ptr desc_ptr; int rc; if (ctxt->mode == X86EMUL_MODE_PROT64) ctxt->op_bytes = 8; rc = read_descriptor(ctxt, ctxt->src.addr.mem, &desc_ptr.size, &desc_ptr.address, ctxt->op_bytes); if (rc != X86EMUL_CONTINUE) return rc; ctxt->ops->set_idt(ctxt, &desc_ptr); /* Disable writeback. */ ctxt->dst.type = OP_NONE; return X86EMUL_CONTINUE; } static int em_smsw(struct x86_emulate_ctxt *ctxt) { if (ctxt->dst.type == OP_MEM) ctxt->dst.bytes = 2; ctxt->dst.val = ctxt->ops->get_cr(ctxt, 0); return X86EMUL_CONTINUE; } static int em_lmsw(struct x86_emulate_ctxt *ctxt) { ctxt->ops->set_cr(ctxt, 0, (ctxt->ops->get_cr(ctxt, 0) & ~0x0eul) | (ctxt->src.val & 0x0f)); ctxt->dst.type = OP_NONE; return X86EMUL_CONTINUE; } static int em_loop(struct x86_emulate_ctxt *ctxt) { int rc = X86EMUL_CONTINUE; register_address_increment(ctxt, reg_rmw(ctxt, VCPU_REGS_RCX), -1); if ((address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) != 0) && (ctxt->b == 0xe2 || test_cc(ctxt->b ^ 0x5, ctxt->eflags))) rc = jmp_rel(ctxt, ctxt->src.val); return rc; } static int em_jcxz(struct x86_emulate_ctxt *ctxt) { int rc = X86EMUL_CONTINUE; if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0) rc = jmp_rel(ctxt, ctxt->src.val); return rc; } static int em_in(struct x86_emulate_ctxt *ctxt) { if (!pio_in_emulated(ctxt, ctxt->dst.bytes, ctxt->src.val, &ctxt->dst.val)) return X86EMUL_IO_NEEDED; return X86EMUL_CONTINUE; } static int em_out(struct x86_emulate_ctxt *ctxt) { ctxt->ops->pio_out_emulated(ctxt, ctxt->src.bytes, ctxt->dst.val, &ctxt->src.val, 1); /* Disable writeback. */ ctxt->dst.type = OP_NONE; return X86EMUL_CONTINUE; } static int em_cli(struct x86_emulate_ctxt *ctxt) { if (emulator_bad_iopl(ctxt)) return emulate_gp(ctxt, 0); ctxt->eflags &= ~X86_EFLAGS_IF; return X86EMUL_CONTINUE; } static int em_sti(struct x86_emulate_ctxt *ctxt) { if (emulator_bad_iopl(ctxt)) return emulate_gp(ctxt, 0); ctxt->interruptibility = KVM_X86_SHADOW_INT_STI; ctxt->eflags |= X86_EFLAGS_IF; return X86EMUL_CONTINUE; } static int em_cpuid(struct x86_emulate_ctxt *ctxt) { u32 eax, ebx, ecx, edx; eax = reg_read(ctxt, VCPU_REGS_RAX); ecx = reg_read(ctxt, VCPU_REGS_RCX); ctxt->ops->get_cpuid(ctxt, &eax, &ebx, &ecx, &edx); *reg_write(ctxt, VCPU_REGS_RAX) = eax; *reg_write(ctxt, VCPU_REGS_RBX) = ebx; *reg_write(ctxt, VCPU_REGS_RCX) = ecx; *reg_write(ctxt, VCPU_REGS_RDX) = edx; return X86EMUL_CONTINUE; } static int em_sahf(struct x86_emulate_ctxt *ctxt) { u32 flags; flags = EFLG_CF | EFLG_PF | EFLG_AF | EFLG_ZF | EFLG_SF; flags &= *reg_rmw(ctxt, VCPU_REGS_RAX) >> 8; ctxt->eflags &= ~0xffUL; ctxt->eflags |= flags | X86_EFLAGS_FIXED; return X86EMUL_CONTINUE; } static int em_lahf(struct x86_emulate_ctxt *ctxt) { *reg_rmw(ctxt, VCPU_REGS_RAX) &= ~0xff00UL; *reg_rmw(ctxt, VCPU_REGS_RAX) |= (ctxt->eflags & 0xff) << 8; return X86EMUL_CONTINUE; } static int em_bswap(struct x86_emulate_ctxt *ctxt) { switch (ctxt->op_bytes) { #ifdef CONFIG_X86_64 case 8: asm("bswap %0" : "+r"(ctxt->dst.val)); break; #endif default: asm("bswap %0" : "+r"(*(u32 *)&ctxt->dst.val)); break; } return X86EMUL_CONTINUE; } static bool valid_cr(int nr) { switch (nr) { case 0: case 2 ... 4: case 8: return true; default: return false; } } static int check_cr_read(struct x86_emulate_ctxt *ctxt) { if (!valid_cr(ctxt->modrm_reg)) return emulate_ud(ctxt); return X86EMUL_CONTINUE; } static int check_cr_write(struct x86_emulate_ctxt *ctxt) { u64 new_val = ctxt->src.val64; int cr = ctxt->modrm_reg; u64 efer = 0; static u64 cr_reserved_bits[] = { 0xffffffff00000000ULL, 0, 0, 0, /* CR3 checked later */ CR4_RESERVED_BITS, 0, 0, 0, CR8_RESERVED_BITS, }; if (!valid_cr(cr)) return emulate_ud(ctxt); if (new_val & cr_reserved_bits[cr]) return emulate_gp(ctxt, 0); switch (cr) { case 0: { u64 cr4; if (((new_val & X86_CR0_PG) && !(new_val & X86_CR0_PE)) || ((new_val & X86_CR0_NW) && !(new_val & X86_CR0_CD))) return emulate_gp(ctxt, 0); cr4 = ctxt->ops->get_cr(ctxt, 4); ctxt->ops->get_msr(ctxt, MSR_EFER, &efer); if ((new_val & X86_CR0_PG) && (efer & EFER_LME) && !(cr4 & X86_CR4_PAE)) return emulate_gp(ctxt, 0); break; } case 3: { u64 rsvd = 0; ctxt->ops->get_msr(ctxt, MSR_EFER, &efer); if (efer & EFER_LMA) rsvd = CR3_L_MODE_RESERVED_BITS; if (new_val & rsvd) return emulate_gp(ctxt, 0); break; } case 4: { ctxt->ops->get_msr(ctxt, MSR_EFER, &efer); if ((efer & EFER_LMA) && !(new_val & X86_CR4_PAE)) return emulate_gp(ctxt, 0); break; } } return X86EMUL_CONTINUE; } static int check_dr7_gd(struct x86_emulate_ctxt *ctxt) { unsigned long dr7; ctxt->ops->get_dr(ctxt, 7, &dr7); /* Check if DR7.Global_Enable is set */ return dr7 & (1 << 13); } static int check_dr_read(struct x86_emulate_ctxt *ctxt) { int dr = ctxt->modrm_reg; u64 cr4; if (dr > 7) return emulate_ud(ctxt); cr4 = ctxt->ops->get_cr(ctxt, 4); if ((cr4 & X86_CR4_DE) && (dr == 4 || dr == 5)) return emulate_ud(ctxt); if (check_dr7_gd(ctxt)) return emulate_db(ctxt); return X86EMUL_CONTINUE; } static int check_dr_write(struct x86_emulate_ctxt *ctxt) { u64 new_val = ctxt->src.val64; int dr = ctxt->modrm_reg; if ((dr == 6 || dr == 7) && (new_val & 0xffffffff00000000ULL)) return emulate_gp(ctxt, 0); return check_dr_read(ctxt); } static int check_svme(struct x86_emulate_ctxt *ctxt) { u64 efer; ctxt->ops->get_msr(ctxt, MSR_EFER, &efer); if (!(efer & EFER_SVME)) return emulate_ud(ctxt); return X86EMUL_CONTINUE; } static int check_svme_pa(struct x86_emulate_ctxt *ctxt) { u64 rax = reg_read(ctxt, VCPU_REGS_RAX); /* Valid physical address? */ if (rax & 0xffff000000000000ULL) return emulate_gp(ctxt, 0); return check_svme(ctxt); } static int check_rdtsc(struct x86_emulate_ctxt *ctxt) { u64 cr4 = ctxt->ops->get_cr(ctxt, 4); if (cr4 & X86_CR4_TSD && ctxt->ops->cpl(ctxt)) return emulate_ud(ctxt); return X86EMUL_CONTINUE; } static int check_rdpmc(struct x86_emulate_ctxt *ctxt) { u64 cr4 = ctxt->ops->get_cr(ctxt, 4); u64 rcx = reg_read(ctxt, VCPU_REGS_RCX); if ((!(cr4 & X86_CR4_PCE) && ctxt->ops->cpl(ctxt)) || ctxt->ops->check_pmc(ctxt, rcx)) return emulate_gp(ctxt, 0); return X86EMUL_CONTINUE; } static int check_perm_in(struct x86_emulate_ctxt *ctxt) { ctxt->dst.bytes = min(ctxt->dst.bytes, 4u); if (!emulator_io_permited(ctxt, ctxt->src.val, ctxt->dst.bytes)) return emulate_gp(ctxt, 0); return X86EMUL_CONTINUE; } static int check_perm_out(struct x86_emulate_ctxt *ctxt) { ctxt->src.bytes = min(ctxt->src.bytes, 4u); if (!emulator_io_permited(ctxt, ctxt->dst.val, ctxt->src.bytes)) return emulate_gp(ctxt, 0); return X86EMUL_CONTINUE; } #define D(_y) { .flags = (_y) } #define DI(_y, _i) { .flags = (_y)|Intercept, .intercept = x86_intercept_##_i } #define DIP(_y, _i, _p) { .flags = (_y)|Intercept|CheckPerm, \ .intercept = x86_intercept_##_i, .check_perm = (_p) } #define N D(NotImpl) #define EXT(_f, _e) { .flags = ((_f) | RMExt), .u.group = (_e) } #define G(_f, _g) { .flags = ((_f) | Group | ModRM), .u.group = (_g) } #define GD(_f, _g) { .flags = ((_f) | GroupDual | ModRM), .u.gdual = (_g) } #define E(_f, _e) { .flags = ((_f) | Escape | ModRM), .u.esc = (_e) } #define I(_f, _e) { .flags = (_f), .u.execute = (_e) } #define F(_f, _e) { .flags = (_f) | Fastop, .u.fastop = (_e) } #define II(_f, _e, _i) \ { .flags = (_f)|Intercept, .u.execute = (_e), .intercept = x86_intercept_##_i } #define IIP(_f, _e, _i, _p) \ { .flags = (_f)|Intercept|CheckPerm, .u.execute = (_e), \ .intercept = x86_intercept_##_i, .check_perm = (_p) } #define GP(_f, _g) { .flags = ((_f) | Prefix), .u.gprefix = (_g) } #define D2bv(_f) D((_f) | ByteOp), D(_f) #define D2bvIP(_f, _i, _p) DIP((_f) | ByteOp, _i, _p), DIP(_f, _i, _p) #define I2bv(_f, _e) I((_f) | ByteOp, _e), I(_f, _e) #define F2bv(_f, _e) F((_f) | ByteOp, _e), F(_f, _e) #define I2bvIP(_f, _e, _i, _p) \ IIP((_f) | ByteOp, _e, _i, _p), IIP(_f, _e, _i, _p) #define F6ALU(_f, _e) F2bv((_f) | DstMem | SrcReg | ModRM, _e), \ F2bv(((_f) | DstReg | SrcMem | ModRM) & ~Lock, _e), \ F2bv(((_f) & ~Lock) | DstAcc | SrcImm, _e) static const struct opcode group7_rm0[] = { N, I(SrcNone | Priv | EmulateOnUD, em_vmcall), N, N, N, N, N, N, }; static const struct opcode group7_rm1[] = { DI(SrcNone | Priv, monitor), DI(SrcNone | Priv, mwait), N, N, N, N, N, N, }; static const struct opcode group7_rm3[] = { DIP(SrcNone | Prot | Priv, vmrun, check_svme_pa), II(SrcNone | Prot | EmulateOnUD, em_vmmcall, vmmcall), DIP(SrcNone | Prot | Priv, vmload, check_svme_pa), DIP(SrcNone | Prot | Priv, vmsave, check_svme_pa), DIP(SrcNone | Prot | Priv, stgi, check_svme), DIP(SrcNone | Prot | Priv, clgi, check_svme), DIP(SrcNone | Prot | Priv, skinit, check_svme), DIP(SrcNone | Prot | Priv, invlpga, check_svme), }; static const struct opcode group7_rm7[] = { N, DIP(SrcNone, rdtscp, check_rdtsc), N, N, N, N, N, N, }; static const struct opcode group1[] = { F(Lock, em_add), F(Lock | PageTable, em_or), F(Lock, em_adc), F(Lock, em_sbb), F(Lock | PageTable, em_and), F(Lock, em_sub), F(Lock, em_xor), F(NoWrite, em_cmp), }; static const struct opcode group1A[] = { I(DstMem | SrcNone | Mov | Stack, em_pop), N, N, N, N, N, N, N, }; static const struct opcode group2[] = { F(DstMem | ModRM, em_rol), F(DstMem | ModRM, em_ror), F(DstMem | ModRM, em_rcl), F(DstMem | ModRM, em_rcr), F(DstMem | ModRM, em_shl), F(DstMem | ModRM, em_shr), F(DstMem | ModRM, em_shl), F(DstMem | ModRM, em_sar), }; static const struct opcode group3[] = { F(DstMem | SrcImm | NoWrite, em_test), F(DstMem | SrcImm | NoWrite, em_test), F(DstMem | SrcNone | Lock, em_not), F(DstMem | SrcNone | Lock, em_neg), F(DstXacc | Src2Mem, em_mul_ex), F(DstXacc | Src2Mem, em_imul_ex), F(DstXacc | Src2Mem, em_div_ex), F(DstXacc | Src2Mem, em_idiv_ex), }; static const struct opcode group4[] = { F(ByteOp | DstMem | SrcNone | Lock, em_inc), F(ByteOp | DstMem | SrcNone | Lock, em_dec), N, N, N, N, N, N, }; static const struct opcode group5[] = { F(DstMem | SrcNone | Lock, em_inc), F(DstMem | SrcNone | Lock, em_dec), I(SrcMem | Stack, em_grp45), I(SrcMemFAddr | ImplicitOps | Stack, em_call_far), I(SrcMem | Stack, em_grp45), I(SrcMemFAddr | ImplicitOps, em_grp45), I(SrcMem | Stack, em_grp45), D(Undefined), }; static const struct opcode group6[] = { DI(Prot, sldt), DI(Prot, str), II(Prot | Priv | SrcMem16, em_lldt, lldt), II(Prot | Priv | SrcMem16, em_ltr, ltr), N, N, N, N, }; static const struct group_dual group7 = { { II(Mov | DstMem, em_sgdt, sgdt), II(Mov | DstMem, em_sidt, sidt), II(SrcMem | Priv, em_lgdt, lgdt), II(SrcMem | Priv, em_lidt, lidt), II(SrcNone | DstMem | Mov, em_smsw, smsw), N, II(SrcMem16 | Mov | Priv, em_lmsw, lmsw), II(SrcMem | ByteOp | Priv | NoAccess, em_invlpg, invlpg), }, { EXT(0, group7_rm0), EXT(0, group7_rm1), N, EXT(0, group7_rm3), II(SrcNone | DstMem | Mov, em_smsw, smsw), N, II(SrcMem16 | Mov | Priv, em_lmsw, lmsw), EXT(0, group7_rm7), } }; static const struct opcode group8[] = { N, N, N, N, F(DstMem | SrcImmByte | NoWrite, em_bt), F(DstMem | SrcImmByte | Lock | PageTable, em_bts), F(DstMem | SrcImmByte | Lock, em_btr), F(DstMem | SrcImmByte | Lock | PageTable, em_btc), }; static const struct group_dual group9 = { { N, I(DstMem64 | Lock | PageTable, em_cmpxchg8b), N, N, N, N, N, N, }, { N, N, N, N, N, N, N, N, } }; static const struct opcode group11[] = { I(DstMem | SrcImm | Mov | PageTable, em_mov), X7(D(Undefined)), }; static const struct gprefix pfx_0f_6f_0f_7f = { I(Mmx, em_mov), I(Sse | Aligned, em_mov), N, I(Sse | Unaligned, em_mov), }; static const struct gprefix pfx_0f_2b = { I(0, em_mov), I(0, em_mov), N, N, }; static const struct gprefix pfx_0f_28_0f_29 = { I(Aligned, em_mov), I(Aligned, em_mov), N, N, }; static const struct gprefix pfx_0f_e7 = { N, I(Sse, em_mov), N, N, }; static const struct escape escape_d9 = { { N, N, N, N, N, N, N, I(DstMem, em_fnstcw), }, { /* 0xC0 - 0xC7 */ N, N, N, N, N, N, N, N, /* 0xC8 - 0xCF */ N, N, N, N, N, N, N, N, /* 0xD0 - 0xC7 */ N, N, N, N, N, N, N, N, /* 0xD8 - 0xDF */ N, N, N, N, N, N, N, N, /* 0xE0 - 0xE7 */ N, N, N, N, N, N, N, N, /* 0xE8 - 0xEF */ N, N, N, N, N, N, N, N, /* 0xF0 - 0xF7 */ N, N, N, N, N, N, N, N, /* 0xF8 - 0xFF */ N, N, N, N, N, N, N, N, } }; static const struct escape escape_db = { { N, N, N, N, N, N, N, N, }, { /* 0xC0 - 0xC7 */ N, N, N, N, N, N, N, N, /* 0xC8 - 0xCF */ N, N, N, N, N, N, N, N, /* 0xD0 - 0xC7 */ N, N, N, N, N, N, N, N, /* 0xD8 - 0xDF */ N, N, N, N, N, N, N, N, /* 0xE0 - 0xE7 */ N, N, N, I(ImplicitOps, em_fninit), N, N, N, N, /* 0xE8 - 0xEF */ N, N, N, N, N, N, N, N, /* 0xF0 - 0xF7 */ N, N, N, N, N, N, N, N, /* 0xF8 - 0xFF */ N, N, N, N, N, N, N, N, } }; static const struct escape escape_dd = { { N, N, N, N, N, N, N, I(DstMem, em_fnstsw), }, { /* 0xC0 - 0xC7 */ N, N, N, N, N, N, N, N, /* 0xC8 - 0xCF */ N, N, N, N, N, N, N, N, /* 0xD0 - 0xC7 */ N, N, N, N, N, N, N, N, /* 0xD8 - 0xDF */ N, N, N, N, N, N, N, N, /* 0xE0 - 0xE7 */ N, N, N, N, N, N, N, N, /* 0xE8 - 0xEF */ N, N, N, N, N, N, N, N, /* 0xF0 - 0xF7 */ N, N, N, N, N, N, N, N, /* 0xF8 - 0xFF */ N, N, N, N, N, N, N, N, } }; static const struct opcode opcode_table[256] = { /* 0x00 - 0x07 */ F6ALU(Lock, em_add), I(ImplicitOps | Stack | No64 | Src2ES, em_push_sreg), I(ImplicitOps | Stack | No64 | Src2ES, em_pop_sreg), /* 0x08 - 0x0F */ F6ALU(Lock | PageTable, em_or), I(ImplicitOps | Stack | No64 | Src2CS, em_push_sreg), N, /* 0x10 - 0x17 */ F6ALU(Lock, em_adc), I(ImplicitOps | Stack | No64 | Src2SS, em_push_sreg), I(ImplicitOps | Stack | No64 | Src2SS, em_pop_sreg), /* 0x18 - 0x1F */ F6ALU(Lock, em_sbb), I(ImplicitOps | Stack | No64 | Src2DS, em_push_sreg), I(ImplicitOps | Stack | No64 | Src2DS, em_pop_sreg), /* 0x20 - 0x27 */ F6ALU(Lock | PageTable, em_and), N, N, /* 0x28 - 0x2F */ F6ALU(Lock, em_sub), N, I(ByteOp | DstAcc | No64, em_das), /* 0x30 - 0x37 */ F6ALU(Lock, em_xor), N, N, /* 0x38 - 0x3F */ F6ALU(NoWrite, em_cmp), N, N, /* 0x40 - 0x4F */ X8(F(DstReg, em_inc)), X8(F(DstReg, em_dec)), /* 0x50 - 0x57 */ X8(I(SrcReg | Stack, em_push)), /* 0x58 - 0x5F */ X8(I(DstReg | Stack, em_pop)), /* 0x60 - 0x67 */ I(ImplicitOps | Stack | No64, em_pusha), I(ImplicitOps | Stack | No64, em_popa), N, D(DstReg | SrcMem32 | ModRM | Mov) /* movsxd (x86/64) */ , N, N, N, N, /* 0x68 - 0x6F */ I(SrcImm | Mov | Stack, em_push), I(DstReg | SrcMem | ModRM | Src2Imm, em_imul_3op), I(SrcImmByte | Mov | Stack, em_push), I(DstReg | SrcMem | ModRM | Src2ImmByte, em_imul_3op), I2bvIP(DstDI | SrcDX | Mov | String | Unaligned, em_in, ins, check_perm_in), /* insb, insw/insd */ I2bvIP(SrcSI | DstDX | String, em_out, outs, check_perm_out), /* outsb, outsw/outsd */ /* 0x70 - 0x7F */ X16(D(SrcImmByte)), /* 0x80 - 0x87 */ G(ByteOp | DstMem | SrcImm, group1), G(DstMem | SrcImm, group1), G(ByteOp | DstMem | SrcImm | No64, group1), G(DstMem | SrcImmByte, group1), F2bv(DstMem | SrcReg | ModRM | NoWrite, em_test), I2bv(DstMem | SrcReg | ModRM | Lock | PageTable, em_xchg), /* 0x88 - 0x8F */ I2bv(DstMem | SrcReg | ModRM | Mov | PageTable, em_mov), I2bv(DstReg | SrcMem | ModRM | Mov, em_mov), I(DstMem | SrcNone | ModRM | Mov | PageTable, em_mov_rm_sreg), D(ModRM | SrcMem | NoAccess | DstReg), I(ImplicitOps | SrcMem16 | ModRM, em_mov_sreg_rm), G(0, group1A), /* 0x90 - 0x97 */ DI(SrcAcc | DstReg, pause), X7(D(SrcAcc | DstReg)), /* 0x98 - 0x9F */ D(DstAcc | SrcNone), I(ImplicitOps | SrcAcc, em_cwd), I(SrcImmFAddr | No64, em_call_far), N, II(ImplicitOps | Stack, em_pushf, pushf), II(ImplicitOps | Stack, em_popf, popf), I(ImplicitOps, em_sahf), I(ImplicitOps, em_lahf), /* 0xA0 - 0xA7 */ I2bv(DstAcc | SrcMem | Mov | MemAbs, em_mov), I2bv(DstMem | SrcAcc | Mov | MemAbs | PageTable, em_mov), I2bv(SrcSI | DstDI | Mov | String, em_mov), F2bv(SrcSI | DstDI | String | NoWrite, em_cmp), /* 0xA8 - 0xAF */ F2bv(DstAcc | SrcImm | NoWrite, em_test), I2bv(SrcAcc | DstDI | Mov | String, em_mov), I2bv(SrcSI | DstAcc | Mov | String, em_mov), F2bv(SrcAcc | DstDI | String | NoWrite, em_cmp), /* 0xB0 - 0xB7 */ X8(I(ByteOp | DstReg | SrcImm | Mov, em_mov)), /* 0xB8 - 0xBF */ X8(I(DstReg | SrcImm64 | Mov, em_mov)), /* 0xC0 - 0xC7 */ G(ByteOp | Src2ImmByte, group2), G(Src2ImmByte, group2), I(ImplicitOps | Stack | SrcImmU16, em_ret_near_imm), I(ImplicitOps | Stack, em_ret), I(DstReg | SrcMemFAddr | ModRM | No64 | Src2ES, em_lseg), I(DstReg | SrcMemFAddr | ModRM | No64 | Src2DS, em_lseg), G(ByteOp, group11), G(0, group11), /* 0xC8 - 0xCF */ I(Stack | SrcImmU16 | Src2ImmByte, em_enter), I(Stack, em_leave), I(ImplicitOps | Stack | SrcImmU16, em_ret_far_imm), I(ImplicitOps | Stack, em_ret_far), D(ImplicitOps), DI(SrcImmByte, intn), D(ImplicitOps | No64), II(ImplicitOps, em_iret, iret), /* 0xD0 - 0xD7 */ G(Src2One | ByteOp, group2), G(Src2One, group2), G(Src2CL | ByteOp, group2), G(Src2CL, group2), I(DstAcc | SrcImmUByte | No64, em_aam), I(DstAcc | SrcImmUByte | No64, em_aad), F(DstAcc | ByteOp | No64, em_salc), I(DstAcc | SrcXLat | ByteOp, em_mov), /* 0xD8 - 0xDF */ N, E(0, &escape_d9), N, E(0, &escape_db), N, E(0, &escape_dd), N, N, /* 0xE0 - 0xE7 */ X3(I(SrcImmByte, em_loop)), I(SrcImmByte, em_jcxz), I2bvIP(SrcImmUByte | DstAcc, em_in, in, check_perm_in), I2bvIP(SrcAcc | DstImmUByte, em_out, out, check_perm_out), /* 0xE8 - 0xEF */ I(SrcImm | Stack, em_call), D(SrcImm | ImplicitOps), I(SrcImmFAddr | No64, em_jmp_far), D(SrcImmByte | ImplicitOps), I2bvIP(SrcDX | DstAcc, em_in, in, check_perm_in), I2bvIP(SrcAcc | DstDX, em_out, out, check_perm_out), /* 0xF0 - 0xF7 */ N, DI(ImplicitOps, icebp), N, N, DI(ImplicitOps | Priv, hlt), D(ImplicitOps), G(ByteOp, group3), G(0, group3), /* 0xF8 - 0xFF */ D(ImplicitOps), D(ImplicitOps), I(ImplicitOps, em_cli), I(ImplicitOps, em_sti), D(ImplicitOps), D(ImplicitOps), G(0, group4), G(0, group5), }; static const struct opcode twobyte_table[256] = { /* 0x00 - 0x0F */ G(0, group6), GD(0, &group7), N, N, N, I(ImplicitOps | EmulateOnUD, em_syscall), II(ImplicitOps | Priv, em_clts, clts), N, DI(ImplicitOps | Priv, invd), DI(ImplicitOps | Priv, wbinvd), N, N, N, D(ImplicitOps | ModRM), N, N, /* 0x10 - 0x1F */ N, N, N, N, N, N, N, N, D(ImplicitOps | ModRM), N, N, N, N, N, N, D(ImplicitOps | ModRM), /* 0x20 - 0x2F */ DIP(ModRM | DstMem | Priv | Op3264 | NoMod, cr_read, check_cr_read), DIP(ModRM | DstMem | Priv | Op3264 | NoMod, dr_read, check_dr_read), IIP(ModRM | SrcMem | Priv | Op3264 | NoMod, em_cr_write, cr_write, check_cr_write), IIP(ModRM | SrcMem | Priv | Op3264 | NoMod, em_dr_write, dr_write, check_dr_write), N, N, N, N, GP(ModRM | DstReg | SrcMem | Mov | Sse, &pfx_0f_28_0f_29), GP(ModRM | DstMem | SrcReg | Mov | Sse, &pfx_0f_28_0f_29), N, GP(ModRM | DstMem | SrcReg | Mov | Sse, &pfx_0f_2b), N, N, N, N, /* 0x30 - 0x3F */ II(ImplicitOps | Priv, em_wrmsr, wrmsr), IIP(ImplicitOps, em_rdtsc, rdtsc, check_rdtsc), II(ImplicitOps | Priv, em_rdmsr, rdmsr), IIP(ImplicitOps, em_rdpmc, rdpmc, check_rdpmc), I(ImplicitOps | EmulateOnUD, em_sysenter), I(ImplicitOps | Priv | EmulateOnUD, em_sysexit), N, N, N, N, N, N, N, N, N, N, /* 0x40 - 0x4F */ X16(D(DstReg | SrcMem | ModRM)), /* 0x50 - 0x5F */ N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, /* 0x60 - 0x6F */ N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, GP(SrcMem | DstReg | ModRM | Mov, &pfx_0f_6f_0f_7f), /* 0x70 - 0x7F */ N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, GP(SrcReg | DstMem | ModRM | Mov, &pfx_0f_6f_0f_7f), /* 0x80 - 0x8F */ X16(D(SrcImm)), /* 0x90 - 0x9F */ X16(D(ByteOp | DstMem | SrcNone | ModRM| Mov)), /* 0xA0 - 0xA7 */ I(Stack | Src2FS, em_push_sreg), I(Stack | Src2FS, em_pop_sreg), II(ImplicitOps, em_cpuid, cpuid), F(DstMem | SrcReg | ModRM | BitOp | NoWrite, em_bt), F(DstMem | SrcReg | Src2ImmByte | ModRM, em_shld), F(DstMem | SrcReg | Src2CL | ModRM, em_shld), N, N, /* 0xA8 - 0xAF */ I(Stack | Src2GS, em_push_sreg), I(Stack | Src2GS, em_pop_sreg), DI(ImplicitOps, rsm), F(DstMem | SrcReg | ModRM | BitOp | Lock | PageTable, em_bts), F(DstMem | SrcReg | Src2ImmByte | ModRM, em_shrd), F(DstMem | SrcReg | Src2CL | ModRM, em_shrd), D(ModRM), F(DstReg | SrcMem | ModRM, em_imul), /* 0xB0 - 0xB7 */ I2bv(DstMem | SrcReg | ModRM | Lock | PageTable, em_cmpxchg), I(DstReg | SrcMemFAddr | ModRM | Src2SS, em_lseg), F(DstMem | SrcReg | ModRM | BitOp | Lock, em_btr), I(DstReg | SrcMemFAddr | ModRM | Src2FS, em_lseg), I(DstReg | SrcMemFAddr | ModRM | Src2GS, em_lseg), D(DstReg | SrcMem8 | ModRM | Mov), D(DstReg | SrcMem16 | ModRM | Mov), /* 0xB8 - 0xBF */ N, N, G(BitOp, group8), F(DstMem | SrcReg | ModRM | BitOp | Lock | PageTable, em_btc), F(DstReg | SrcMem | ModRM, em_bsf), F(DstReg | SrcMem | ModRM, em_bsr), D(DstReg | SrcMem8 | ModRM | Mov), D(DstReg | SrcMem16 | ModRM | Mov), /* 0xC0 - 0xC7 */ F2bv(DstMem | SrcReg | ModRM | SrcWrite | Lock, em_xadd), N, D(DstMem | SrcReg | ModRM | Mov), N, N, N, GD(0, &group9), /* 0xC8 - 0xCF */ X8(I(DstReg, em_bswap)), /* 0xD0 - 0xDF */ N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, /* 0xE0 - 0xEF */ N, N, N, N, N, N, N, GP(SrcReg | DstMem | ModRM | Mov, &pfx_0f_e7), N, N, N, N, N, N, N, N, /* 0xF0 - 0xFF */ N, N, N, N, N, N, N, N, N, N, N, N, N, N, N, N }; static const struct gprefix three_byte_0f_38_f0 = { I(DstReg | SrcMem | Mov, em_movbe), N, N, N }; static const struct gprefix three_byte_0f_38_f1 = { I(DstMem | SrcReg | Mov, em_movbe), N, N, N }; /* * Insns below are selected by the prefix which indexed by the third opcode * byte. */ static const struct opcode opcode_map_0f_38[256] = { /* 0x00 - 0x7f */ X16(N), X16(N), X16(N), X16(N), X16(N), X16(N), X16(N), X16(N), /* 0x80 - 0xef */ X16(N), X16(N), X16(N), X16(N), X16(N), X16(N), X16(N), /* 0xf0 - 0xf1 */ GP(EmulateOnUD | ModRM | Prefix, &three_byte_0f_38_f0), GP(EmulateOnUD | ModRM | Prefix, &three_byte_0f_38_f1), /* 0xf2 - 0xff */ N, N, X4(N), X8(N) }; #undef D #undef N #undef G #undef GD #undef I #undef GP #undef EXT #undef D2bv #undef D2bvIP #undef I2bv #undef I2bvIP #undef I6ALU static unsigned imm_size(struct x86_emulate_ctxt *ctxt) { unsigned size; size = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes; if (size == 8) size = 4; return size; } static int decode_imm(struct x86_emulate_ctxt *ctxt, struct operand *op, unsigned size, bool sign_extension) { int rc = X86EMUL_CONTINUE; op->type = OP_IMM; op->bytes = size; op->addr.mem.ea = ctxt->_eip; /* NB. Immediates are sign-extended as necessary. */ switch (op->bytes) { case 1: op->val = insn_fetch(s8, ctxt); break; case 2: op->val = insn_fetch(s16, ctxt); break; case 4: op->val = insn_fetch(s32, ctxt); break; case 8: op->val = insn_fetch(s64, ctxt); break; } if (!sign_extension) { switch (op->bytes) { case 1: op->val &= 0xff; break; case 2: op->val &= 0xffff; break; case 4: op->val &= 0xffffffff; break; } } done: return rc; } static int decode_operand(struct x86_emulate_ctxt *ctxt, struct operand *op, unsigned d) { int rc = X86EMUL_CONTINUE; switch (d) { case OpReg: decode_register_operand(ctxt, op); break; case OpImmUByte: rc = decode_imm(ctxt, op, 1, false); break; case OpMem: ctxt->memop.bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes; mem_common: *op = ctxt->memop; ctxt->memopp = op; if (ctxt->d & BitOp) fetch_bit_operand(ctxt); op->orig_val = op->val; break; case OpMem64: ctxt->memop.bytes = (ctxt->op_bytes == 8) ? 16 : 8; goto mem_common; case OpAcc: op->type = OP_REG; op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes; op->addr.reg = reg_rmw(ctxt, VCPU_REGS_RAX); fetch_register_operand(op); op->orig_val = op->val; break; case OpAccLo: op->type = OP_REG; op->bytes = (ctxt->d & ByteOp) ? 2 : ctxt->op_bytes; op->addr.reg = reg_rmw(ctxt, VCPU_REGS_RAX); fetch_register_operand(op); op->orig_val = op->val; break; case OpAccHi: if (ctxt->d & ByteOp) { op->type = OP_NONE; break; } op->type = OP_REG; op->bytes = ctxt->op_bytes; op->addr.reg = reg_rmw(ctxt, VCPU_REGS_RDX); fetch_register_operand(op); op->orig_val = op->val; break; case OpDI: op->type = OP_MEM; op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes; op->addr.mem.ea = register_address(ctxt, reg_read(ctxt, VCPU_REGS_RDI)); op->addr.mem.seg = VCPU_SREG_ES; op->val = 0; op->count = 1; break; case OpDX: op->type = OP_REG; op->bytes = 2; op->addr.reg = reg_rmw(ctxt, VCPU_REGS_RDX); fetch_register_operand(op); break; case OpCL: op->bytes = 1; op->val = reg_read(ctxt, VCPU_REGS_RCX) & 0xff; break; case OpImmByte: rc = decode_imm(ctxt, op, 1, true); break; case OpOne: op->bytes = 1; op->val = 1; break; case OpImm: rc = decode_imm(ctxt, op, imm_size(ctxt), true); break; case OpImm64: rc = decode_imm(ctxt, op, ctxt->op_bytes, true); break; case OpMem8: ctxt->memop.bytes = 1; if (ctxt->memop.type == OP_REG) { ctxt->memop.addr.reg = decode_register(ctxt, ctxt->modrm_rm, true); fetch_register_operand(&ctxt->memop); } goto mem_common; case OpMem16: ctxt->memop.bytes = 2; goto mem_common; case OpMem32: ctxt->memop.bytes = 4; goto mem_common; case OpImmU16: rc = decode_imm(ctxt, op, 2, false); break; case OpImmU: rc = decode_imm(ctxt, op, imm_size(ctxt), false); break; case OpSI: op->type = OP_MEM; op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes; op->addr.mem.ea = register_address(ctxt, reg_read(ctxt, VCPU_REGS_RSI)); op->addr.mem.seg = ctxt->seg_override; op->val = 0; op->count = 1; break; case OpXLat: op->type = OP_MEM; op->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes; op->addr.mem.ea = register_address(ctxt, reg_read(ctxt, VCPU_REGS_RBX) + (reg_read(ctxt, VCPU_REGS_RAX) & 0xff)); op->addr.mem.seg = ctxt->seg_override; op->val = 0; break; case OpImmFAddr: op->type = OP_IMM; op->addr.mem.ea = ctxt->_eip; op->bytes = ctxt->op_bytes + 2; insn_fetch_arr(op->valptr, op->bytes, ctxt); break; case OpMemFAddr: ctxt->memop.bytes = ctxt->op_bytes + 2; goto mem_common; case OpES: op->val = VCPU_SREG_ES; break; case OpCS: op->val = VCPU_SREG_CS; break; case OpSS: op->val = VCPU_SREG_SS; break; case OpDS: op->val = VCPU_SREG_DS; break; case OpFS: op->val = VCPU_SREG_FS; break; case OpGS: op->val = VCPU_SREG_GS; break; case OpImplicit: /* Special instructions do their own operand decoding. */ default: op->type = OP_NONE; /* Disable writeback. */ break; } done: return rc; } int x86_decode_insn(struct x86_emulate_ctxt *ctxt, void *insn, int insn_len) { int rc = X86EMUL_CONTINUE; int mode = ctxt->mode; int def_op_bytes, def_ad_bytes, goffset, simd_prefix; bool op_prefix = false; bool has_seg_override = false; struct opcode opcode; ctxt->memop.type = OP_NONE; ctxt->memopp = NULL; ctxt->_eip = ctxt->eip; ctxt->fetch.ptr = ctxt->fetch.data; ctxt->fetch.end = ctxt->fetch.data + insn_len; ctxt->opcode_len = 1; if (insn_len > 0) memcpy(ctxt->fetch.data, insn, insn_len); else { rc = __do_insn_fetch_bytes(ctxt, 1); if (rc != X86EMUL_CONTINUE) return rc; } switch (mode) { case X86EMUL_MODE_REAL: case X86EMUL_MODE_VM86: case X86EMUL_MODE_PROT16: def_op_bytes = def_ad_bytes = 2; break; case X86EMUL_MODE_PROT32: def_op_bytes = def_ad_bytes = 4; break; #ifdef CONFIG_X86_64 case X86EMUL_MODE_PROT64: def_op_bytes = 4; def_ad_bytes = 8; break; #endif default: return EMULATION_FAILED; } ctxt->op_bytes = def_op_bytes; ctxt->ad_bytes = def_ad_bytes; /* Legacy prefixes. */ for (;;) { switch (ctxt->b = insn_fetch(u8, ctxt)) { case 0x66: /* operand-size override */ op_prefix = true; /* switch between 2/4 bytes */ ctxt->op_bytes = def_op_bytes ^ 6; break; case 0x67: /* address-size override */ if (mode == X86EMUL_MODE_PROT64) /* switch between 4/8 bytes */ ctxt->ad_bytes = def_ad_bytes ^ 12; else /* switch between 2/4 bytes */ ctxt->ad_bytes = def_ad_bytes ^ 6; break; case 0x26: /* ES override */ case 0x2e: /* CS override */ case 0x36: /* SS override */ case 0x3e: /* DS override */ has_seg_override = true; ctxt->seg_override = (ctxt->b >> 3) & 3; break; case 0x64: /* FS override */ case 0x65: /* GS override */ has_seg_override = true; ctxt->seg_override = ctxt->b & 7; break; case 0x40 ... 0x4f: /* REX */ if (mode != X86EMUL_MODE_PROT64) goto done_prefixes; ctxt->rex_prefix = ctxt->b; continue; case 0xf0: /* LOCK */ ctxt->lock_prefix = 1; break; case 0xf2: /* REPNE/REPNZ */ case 0xf3: /* REP/REPE/REPZ */ ctxt->rep_prefix = ctxt->b; break; default: goto done_prefixes; } /* Any legacy prefix after a REX prefix nullifies its effect. */ ctxt->rex_prefix = 0; } done_prefixes: /* REX prefix. */ if (ctxt->rex_prefix & 8) ctxt->op_bytes = 8; /* REX.W */ /* Opcode byte(s). */ opcode = opcode_table[ctxt->b]; /* Two-byte opcode? */ if (ctxt->b == 0x0f) { ctxt->opcode_len = 2; ctxt->b = insn_fetch(u8, ctxt); opcode = twobyte_table[ctxt->b]; /* 0F_38 opcode map */ if (ctxt->b == 0x38) { ctxt->opcode_len = 3; ctxt->b = insn_fetch(u8, ctxt); opcode = opcode_map_0f_38[ctxt->b]; } } ctxt->d = opcode.flags; if (ctxt->d & ModRM) ctxt->modrm = insn_fetch(u8, ctxt); /* vex-prefix instructions are not implemented */ if (ctxt->opcode_len == 1 && (ctxt->b == 0xc5 || ctxt->b == 0xc4) && (mode == X86EMUL_MODE_PROT64 || (mode >= X86EMUL_MODE_PROT16 && (ctxt->modrm & 0x80)))) { ctxt->d = NotImpl; } while (ctxt->d & GroupMask) { switch (ctxt->d & GroupMask) { case Group: goffset = (ctxt->modrm >> 3) & 7; opcode = opcode.u.group[goffset]; break; case GroupDual: goffset = (ctxt->modrm >> 3) & 7; if ((ctxt->modrm >> 6) == 3) opcode = opcode.u.gdual->mod3[goffset]; else opcode = opcode.u.gdual->mod012[goffset]; break; case RMExt: goffset = ctxt->modrm & 7; opcode = opcode.u.group[goffset]; break; case Prefix: if (ctxt->rep_prefix && op_prefix) return EMULATION_FAILED; simd_prefix = op_prefix ? 0x66 : ctxt->rep_prefix; switch (simd_prefix) { case 0x00: opcode = opcode.u.gprefix->pfx_no; break; case 0x66: opcode = opcode.u.gprefix->pfx_66; break; case 0xf2: opcode = opcode.u.gprefix->pfx_f2; break; case 0xf3: opcode = opcode.u.gprefix->pfx_f3; break; } break; case Escape: if (ctxt->modrm > 0xbf) opcode = opcode.u.esc->high[ctxt->modrm - 0xc0]; else opcode = opcode.u.esc->op[(ctxt->modrm >> 3) & 7]; break; default: return EMULATION_FAILED; } ctxt->d &= ~(u64)GroupMask; ctxt->d |= opcode.flags; } /* Unrecognised? */ if (ctxt->d == 0) return EMULATION_FAILED; ctxt->execute = opcode.u.execute; if (unlikely(ctxt->ud) && likely(!(ctxt->d & EmulateOnUD))) return EMULATION_FAILED; if (unlikely(ctxt->d & (NotImpl|Stack|Op3264|Sse|Mmx|Intercept|CheckPerm))) { /* * These are copied unconditionally here, and checked unconditionally * in x86_emulate_insn. */ ctxt->check_perm = opcode.check_perm; ctxt->intercept = opcode.intercept; if (ctxt->d & NotImpl) return EMULATION_FAILED; if (mode == X86EMUL_MODE_PROT64 && (ctxt->d & Stack)) ctxt->op_bytes = 8; if (ctxt->d & Op3264) { if (mode == X86EMUL_MODE_PROT64) ctxt->op_bytes = 8; else ctxt->op_bytes = 4; } if (ctxt->d & Sse) ctxt->op_bytes = 16; else if (ctxt->d & Mmx) ctxt->op_bytes = 8; } /* ModRM and SIB bytes. */ if (ctxt->d & ModRM) { rc = decode_modrm(ctxt, &ctxt->memop); if (!has_seg_override) { has_seg_override = true; ctxt->seg_override = ctxt->modrm_seg; } } else if (ctxt->d & MemAbs) rc = decode_abs(ctxt, &ctxt->memop); if (rc != X86EMUL_CONTINUE) goto done; if (!has_seg_override) ctxt->seg_override = VCPU_SREG_DS; ctxt->memop.addr.mem.seg = ctxt->seg_override; /* * Decode and fetch the source operand: register, memory * or immediate. */ rc = decode_operand(ctxt, &ctxt->src, (ctxt->d >> SrcShift) & OpMask); if (rc != X86EMUL_CONTINUE) goto done; /* * Decode and fetch the second source operand: register, memory * or immediate. */ rc = decode_operand(ctxt, &ctxt->src2, (ctxt->d >> Src2Shift) & OpMask); if (rc != X86EMUL_CONTINUE) goto done; /* Decode and fetch the destination operand: register or memory. */ rc = decode_operand(ctxt, &ctxt->dst, (ctxt->d >> DstShift) & OpMask); done: if (ctxt->rip_relative) ctxt->memopp->addr.mem.ea += ctxt->_eip; return (rc != X86EMUL_CONTINUE) ? EMULATION_FAILED : EMULATION_OK; } bool x86_page_table_writing_insn(struct x86_emulate_ctxt *ctxt) { return ctxt->d & PageTable; } static bool string_insn_completed(struct x86_emulate_ctxt *ctxt) { /* The second termination condition only applies for REPE * and REPNE. Test if the repeat string operation prefix is * REPE/REPZ or REPNE/REPNZ and if it's the case it tests the * corresponding termination condition according to: * - if REPE/REPZ and ZF = 0 then done * - if REPNE/REPNZ and ZF = 1 then done */ if (((ctxt->b == 0xa6) || (ctxt->b == 0xa7) || (ctxt->b == 0xae) || (ctxt->b == 0xaf)) && (((ctxt->rep_prefix == REPE_PREFIX) && ((ctxt->eflags & EFLG_ZF) == 0)) || ((ctxt->rep_prefix == REPNE_PREFIX) && ((ctxt->eflags & EFLG_ZF) == EFLG_ZF)))) return true; return false; } static int flush_pending_x87_faults(struct x86_emulate_ctxt *ctxt) { bool fault = false; ctxt->ops->get_fpu(ctxt); asm volatile("1: fwait \n\t" "2: \n\t" ".pushsection .fixup,\"ax\" \n\t" "3: \n\t" "movb $1, %[fault] \n\t" "jmp 2b \n\t" ".popsection \n\t" _ASM_EXTABLE(1b, 3b) : [fault]"+qm"(fault)); ctxt->ops->put_fpu(ctxt); if (unlikely(fault)) return emulate_exception(ctxt, MF_VECTOR, 0, false); return X86EMUL_CONTINUE; } static void fetch_possible_mmx_operand(struct x86_emulate_ctxt *ctxt, struct operand *op) { if (op->type == OP_MM) read_mmx_reg(ctxt, &op->mm_val, op->addr.mm); } static int fastop(struct x86_emulate_ctxt *ctxt, void (*fop)(struct fastop *)) { ulong flags = (ctxt->eflags & EFLAGS_MASK) | X86_EFLAGS_IF; if (!(ctxt->d & ByteOp)) fop += __ffs(ctxt->dst.bytes) * FASTOP_SIZE; asm("push %[flags]; popf; call *%[fastop]; pushf; pop %[flags]\n" : "+a"(ctxt->dst.val), "+d"(ctxt->src.val), [flags]"+D"(flags), [fastop]"+S"(fop) : "c"(ctxt->src2.val)); ctxt->eflags = (ctxt->eflags & ~EFLAGS_MASK) | (flags & EFLAGS_MASK); if (!fop) /* exception is returned in fop variable */ return emulate_de(ctxt); return X86EMUL_CONTINUE; } void init_decode_cache(struct x86_emulate_ctxt *ctxt) { memset(&ctxt->rip_relative, 0, (void *)&ctxt->modrm - (void *)&ctxt->rip_relative); ctxt->io_read.pos = 0; ctxt->io_read.end = 0; ctxt->mem_read.end = 0; } int x86_emulate_insn(struct x86_emulate_ctxt *ctxt) { const struct x86_emulate_ops *ops = ctxt->ops; int rc = X86EMUL_CONTINUE; int saved_dst_type = ctxt->dst.type; ctxt->mem_read.pos = 0; /* LOCK prefix is allowed only with some instructions */ if (ctxt->lock_prefix && (!(ctxt->d & Lock) || ctxt->dst.type != OP_MEM)) { rc = emulate_ud(ctxt); goto done; } if ((ctxt->d & SrcMask) == SrcMemFAddr && ctxt->src.type != OP_MEM) { rc = emulate_ud(ctxt); goto done; } if (unlikely(ctxt->d & (No64|Undefined|Sse|Mmx|Intercept|CheckPerm|Priv|Prot|String))) { if ((ctxt->mode == X86EMUL_MODE_PROT64 && (ctxt->d & No64)) || (ctxt->d & Undefined)) { rc = emulate_ud(ctxt); goto done; } if (((ctxt->d & (Sse|Mmx)) && ((ops->get_cr(ctxt, 0) & X86_CR0_EM))) || ((ctxt->d & Sse) && !(ops->get_cr(ctxt, 4) & X86_CR4_OSFXSR))) { rc = emulate_ud(ctxt); goto done; } if ((ctxt->d & (Sse|Mmx)) && (ops->get_cr(ctxt, 0) & X86_CR0_TS)) { rc = emulate_nm(ctxt); goto done; } if (ctxt->d & Mmx) { rc = flush_pending_x87_faults(ctxt); if (rc != X86EMUL_CONTINUE) goto done; /* * Now that we know the fpu is exception safe, we can fetch * operands from it. */ fetch_possible_mmx_operand(ctxt, &ctxt->src); fetch_possible_mmx_operand(ctxt, &ctxt->src2); if (!(ctxt->d & Mov)) fetch_possible_mmx_operand(ctxt, &ctxt->dst); } if (unlikely(ctxt->guest_mode) && (ctxt->d & Intercept)) { rc = emulator_check_intercept(ctxt, ctxt->intercept, X86_ICPT_PRE_EXCEPT); if (rc != X86EMUL_CONTINUE) goto done; } /* Privileged instruction can be executed only in CPL=0 */ if ((ctxt->d & Priv) && ops->cpl(ctxt)) { if (ctxt->d & PrivUD) rc = emulate_ud(ctxt); else rc = emulate_gp(ctxt, 0); goto done; } /* Instruction can only be executed in protected mode */ if ((ctxt->d & Prot) && ctxt->mode < X86EMUL_MODE_PROT16) { rc = emulate_ud(ctxt); goto done; } /* Do instruction specific permission checks */ if (ctxt->d & CheckPerm) { rc = ctxt->check_perm(ctxt); if (rc != X86EMUL_CONTINUE) goto done; } if (unlikely(ctxt->guest_mode) && (ctxt->d & Intercept)) { rc = emulator_check_intercept(ctxt, ctxt->intercept, X86_ICPT_POST_EXCEPT); if (rc != X86EMUL_CONTINUE) goto done; } if (ctxt->rep_prefix && (ctxt->d & String)) { /* All REP prefixes have the same first termination condition */ if (address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) == 0) { ctxt->eip = ctxt->_eip; ctxt->eflags &= ~EFLG_RF; goto done; } } } if ((ctxt->src.type == OP_MEM) && !(ctxt->d & NoAccess)) { rc = segmented_read(ctxt, ctxt->src.addr.mem, ctxt->src.valptr, ctxt->src.bytes); if (rc != X86EMUL_CONTINUE) goto done; ctxt->src.orig_val64 = ctxt->src.val64; } if (ctxt->src2.type == OP_MEM) { rc = segmented_read(ctxt, ctxt->src2.addr.mem, &ctxt->src2.val, ctxt->src2.bytes); if (rc != X86EMUL_CONTINUE) goto done; } if ((ctxt->d & DstMask) == ImplicitOps) goto special_insn; if ((ctxt->dst.type == OP_MEM) && !(ctxt->d & Mov)) { /* optimisation - avoid slow emulated read if Mov */ rc = segmented_read(ctxt, ctxt->dst.addr.mem, &ctxt->dst.val, ctxt->dst.bytes); if (rc != X86EMUL_CONTINUE) goto done; } ctxt->dst.orig_val = ctxt->dst.val; special_insn: if (unlikely(ctxt->guest_mode) && (ctxt->d & Intercept)) { rc = emulator_check_intercept(ctxt, ctxt->intercept, X86_ICPT_POST_MEMACCESS); if (rc != X86EMUL_CONTINUE) goto done; } if (ctxt->rep_prefix && (ctxt->d & String)) ctxt->eflags |= EFLG_RF; else ctxt->eflags &= ~EFLG_RF; if (ctxt->execute) { if (ctxt->d & Fastop) { void (*fop)(struct fastop *) = (void *)ctxt->execute; rc = fastop(ctxt, fop); if (rc != X86EMUL_CONTINUE) goto done; goto writeback; } rc = ctxt->execute(ctxt); if (rc != X86EMUL_CONTINUE) goto done; goto writeback; } if (ctxt->opcode_len == 2) goto twobyte_insn; else if (ctxt->opcode_len == 3) goto threebyte_insn; switch (ctxt->b) { case 0x63: /* movsxd */ if (ctxt->mode != X86EMUL_MODE_PROT64) goto cannot_emulate; ctxt->dst.val = (s32) ctxt->src.val; break; case 0x70 ... 0x7f: /* jcc (short) */ if (test_cc(ctxt->b, ctxt->eflags)) rc = jmp_rel(ctxt, ctxt->src.val); break; case 0x8d: /* lea r16/r32, m */ ctxt->dst.val = ctxt->src.addr.mem.ea; break; case 0x90 ... 0x97: /* nop / xchg reg, rax */ if (ctxt->dst.addr.reg == reg_rmw(ctxt, VCPU_REGS_RAX)) ctxt->dst.type = OP_NONE; else rc = em_xchg(ctxt); break; case 0x98: /* cbw/cwde/cdqe */ switch (ctxt->op_bytes) { case 2: ctxt->dst.val = (s8)ctxt->dst.val; break; case 4: ctxt->dst.val = (s16)ctxt->dst.val; break; case 8: ctxt->dst.val = (s32)ctxt->dst.val; break; } break; case 0xcc: /* int3 */ rc = emulate_int(ctxt, 3); break; case 0xcd: /* int n */ rc = emulate_int(ctxt, ctxt->src.val); break; case 0xce: /* into */ if (ctxt->eflags & EFLG_OF) rc = emulate_int(ctxt, 4); break; case 0xe9: /* jmp rel */ case 0xeb: /* jmp rel short */ rc = jmp_rel(ctxt, ctxt->src.val); ctxt->dst.type = OP_NONE; /* Disable writeback. */ break; case 0xf4: /* hlt */ ctxt->ops->halt(ctxt); break; case 0xf5: /* cmc */ /* complement carry flag from eflags reg */ ctxt->eflags ^= EFLG_CF; break; case 0xf8: /* clc */ ctxt->eflags &= ~EFLG_CF; break; case 0xf9: /* stc */ ctxt->eflags |= EFLG_CF; break; case 0xfc: /* cld */ ctxt->eflags &= ~EFLG_DF; break; case 0xfd: /* std */ ctxt->eflags |= EFLG_DF; break; default: goto cannot_emulate; } if (rc != X86EMUL_CONTINUE) goto done; writeback: if (ctxt->d & SrcWrite) { BUG_ON(ctxt->src.type == OP_MEM || ctxt->src.type == OP_MEM_STR); rc = writeback(ctxt, &ctxt->src); if (rc != X86EMUL_CONTINUE) goto done; } if (!(ctxt->d & NoWrite)) { rc = writeback(ctxt, &ctxt->dst); if (rc != X86EMUL_CONTINUE) goto done; } /* * restore dst type in case the decoding will be reused * (happens for string instruction ) */ ctxt->dst.type = saved_dst_type; if ((ctxt->d & SrcMask) == SrcSI) string_addr_inc(ctxt, VCPU_REGS_RSI, &ctxt->src); if ((ctxt->d & DstMask) == DstDI) string_addr_inc(ctxt, VCPU_REGS_RDI, &ctxt->dst); if (ctxt->rep_prefix && (ctxt->d & String)) { unsigned int count; struct read_cache *r = &ctxt->io_read; if ((ctxt->d & SrcMask) == SrcSI) count = ctxt->src.count; else count = ctxt->dst.count; register_address_increment(ctxt, reg_rmw(ctxt, VCPU_REGS_RCX), -count); if (!string_insn_completed(ctxt)) { /* * Re-enter guest when pio read ahead buffer is empty * or, if it is not used, after each 1024 iteration. */ if ((r->end != 0 || reg_read(ctxt, VCPU_REGS_RCX) & 0x3ff) && (r->end == 0 || r->end != r->pos)) { /* * Reset read cache. Usually happens before * decode, but since instruction is restarted * we have to do it here. */ ctxt->mem_read.end = 0; writeback_registers(ctxt); return EMULATION_RESTART; } goto done; /* skip rip writeback */ } ctxt->eflags &= ~EFLG_RF; } ctxt->eip = ctxt->_eip; done: if (rc == X86EMUL_PROPAGATE_FAULT) { WARN_ON(ctxt->exception.vector > 0x1f); ctxt->have_exception = true; } if (rc == X86EMUL_INTERCEPTED) return EMULATION_INTERCEPTED; if (rc == X86EMUL_CONTINUE) writeback_registers(ctxt); return (rc == X86EMUL_UNHANDLEABLE) ? EMULATION_FAILED : EMULATION_OK; twobyte_insn: switch (ctxt->b) { case 0x09: /* wbinvd */ (ctxt->ops->wbinvd)(ctxt); break; case 0x08: /* invd */ case 0x0d: /* GrpP (prefetch) */ case 0x18: /* Grp16 (prefetch/nop) */ case 0x1f: /* nop */ break; case 0x20: /* mov cr, reg */ ctxt->dst.val = ops->get_cr(ctxt, ctxt->modrm_reg); break; case 0x21: /* mov from dr to reg */ ops->get_dr(ctxt, ctxt->modrm_reg, &ctxt->dst.val); break; case 0x40 ... 0x4f: /* cmov */ if (test_cc(ctxt->b, ctxt->eflags)) ctxt->dst.val = ctxt->src.val; else if (ctxt->mode != X86EMUL_MODE_PROT64 || ctxt->op_bytes != 4) ctxt->dst.type = OP_NONE; /* no writeback */ break; case 0x80 ... 0x8f: /* jnz rel, etc*/ if (test_cc(ctxt->b, ctxt->eflags)) rc = jmp_rel(ctxt, ctxt->src.val); break; case 0x90 ... 0x9f: /* setcc r/m8 */ ctxt->dst.val = test_cc(ctxt->b, ctxt->eflags); break; case 0xae: /* clflush */ break; case 0xb6 ... 0xb7: /* movzx */ ctxt->dst.bytes = ctxt->op_bytes; ctxt->dst.val = (ctxt->src.bytes == 1) ? (u8) ctxt->src.val : (u16) ctxt->src.val; break; case 0xbe ... 0xbf: /* movsx */ ctxt->dst.bytes = ctxt->op_bytes; ctxt->dst.val = (ctxt->src.bytes == 1) ? (s8) ctxt->src.val : (s16) ctxt->src.val; break; case 0xc3: /* movnti */ ctxt->dst.bytes = ctxt->op_bytes; ctxt->dst.val = (ctxt->op_bytes == 8) ? (u64) ctxt->src.val : (u32) ctxt->src.val; break; default: goto cannot_emulate; } threebyte_insn: if (rc != X86EMUL_CONTINUE) goto done; goto writeback; cannot_emulate: return EMULATION_FAILED; } void emulator_invalidate_register_cache(struct x86_emulate_ctxt *ctxt) { invalidate_registers(ctxt); } void emulator_writeback_register_cache(struct x86_emulate_ctxt *ctxt) { writeback_registers(ctxt); }
./CrossVul/dataset_final_sorted/CWE-399/c/bad_2322_0
crossvul-cpp_data_bad_5672_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; 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); 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); 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; 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, void *arg) { 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 && 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, void *arg) { 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-399/c/bad_5672_0
crossvul-cpp_data_good_3427_0
/* * 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 <net/ip.h> #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) #include <net/ipv6.h> #include <net/mld.h> #include <net/addrconf.h> #include <net/ip6_checksum.h> #endif #include "br_private.h" #define mlock_dereference(X, br) \ rcu_dereference_protected(X, lockdep_is_held(&br->multicast_lock)) #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) static inline int ipv6_is_local_multicast(const struct in6_addr *addr) { if (ipv6_addr_is_multicast(addr) && IPV6_ADDR_MC_SCOPE(addr) <= IPV6_ADDR_SCOPE_LINKLOCAL) return 1; return 0; } #endif static inline int br_ip_equal(const struct br_ip *a, const struct br_ip *b) { if (a->proto != b->proto) return 0; switch (a->proto) { case htons(ETH_P_IP): return a->u.ip4 == b->u.ip4; #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) 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) { return jhash_1word(mdb->secret, (__force u32)ip) & (mdb->max - 1); } #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) static inline int __br_ip6_hash(struct net_bridge_mdb_htable *mdb, const struct in6_addr *ip) { return jhash2((__force u32 *)ip->s6_addr32, 4, 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); #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) case htons(ETH_P_IPV6): return __br_ip6_hash(mdb, &ip->u.ip6); #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; struct hlist_node *p; hlist_for_each_entry_rcu(mp, p, &mdb->mhash[hash], hlist[mdb->ver]) { if (br_ip_equal(&mp->addr, dst)) return mp; } return NULL; } static 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) { struct br_ip br_dst; br_dst.u.ip4 = dst; br_dst.proto = htons(ETH_P_IP); return br_mdb_ip_get(mdb, &br_dst); } #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) static struct net_bridge_mdb_entry *br_mdb_ip6_get( struct net_bridge_mdb_htable *mdb, const struct in6_addr *dst) { struct br_ip br_dst; ipv6_addr_copy(&br_dst.u.ip6, dst); br_dst.proto = htons(ETH_P_IPV6); 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) { 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; switch (skb->protocol) { case htons(ETH_P_IP): ip.u.ip4 = ip_hdr(skb)->daddr; break; #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) case htons(ETH_P_IPV6): ipv6_addr_copy(&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; struct hlist_node *p; int maxlen; int len; int i; for (i = 0; i < old->max; i++) hlist_for_each_entry(mp, p, &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, p, &new->mhash[i], hlist[new->ver]) len++; if (len > maxlen) maxlen = len; } return maxlen > elasticity ? -EINVAL : 0; } static 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; if (!hlist_unhashed(&mp->mglist)) hlist_del_init(&mp->mglist); if (mp->ports) goto out; mdb = mlock_dereference(br->mdb, br); hlist_del_rcu(&mp->hlist[mdb->ver]); mdb->size--; del_timer(&mp->query_timer); 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); del_timer(&p->query_timer); call_rcu_bh(&p->rcu, br_multicast_free_pg); if (!mp->ports && hlist_unhashed(&mp->mglist) && 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)) 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; } 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 = 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 defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) static struct sk_buff *br_ip6_multicast_alloc_query(struct net_bridge *br, 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); ipv6_eth_mc_map(group, eth->h_dest); 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->saddr, 0, 0, 0, 0); ipv6_addr_set(&ip6h->daddr, htonl(0xff020000), 0, 0, htonl(1)); 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_PAD0; /* Pad0 */ hopopt[7] = IPV6_TLV_PAD0; /* Pad0 */ 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_last_member_interval : br->multicast_query_response_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; ipv6_addr_copy(&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 defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) case htons(ETH_P_IPV6): return br_ip6_multicast_alloc_query(br, &addr->u.ip6); #endif } return NULL; } static void br_multicast_send_group_query(struct net_bridge_mdb_entry *mp) { struct net_bridge *br = mp->br; struct sk_buff *skb; skb = br_multicast_alloc_query(br, &mp->addr); if (!skb) goto timer; netif_rx(skb); timer: if (++mp->queries_sent < br->multicast_last_member_count) mod_timer(&mp->query_timer, jiffies + br->multicast_last_member_interval); } static void br_multicast_group_query_expired(unsigned long data) { struct net_bridge_mdb_entry *mp = (void *)data; struct net_bridge *br = mp->br; spin_lock(&br->multicast_lock); if (!netif_running(br->dev) || hlist_unhashed(&mp->mglist) || mp->queries_sent >= br->multicast_last_member_count) goto out; br_multicast_send_group_query(mp); out: spin_unlock(&br->multicast_lock); } static void br_multicast_send_port_group_query(struct net_bridge_port_group *pg) { struct net_bridge_port *port = pg->port; struct net_bridge *br = port->br; struct sk_buff *skb; skb = br_multicast_alloc_query(br, &pg->addr); if (!skb) goto timer; br_deliver(port, skb); timer: if (++pg->queries_sent < br->multicast_last_member_count) mod_timer(&pg->query_timer, jiffies + br->multicast_last_member_interval); } static void br_multicast_port_group_query_expired(unsigned long data) { struct net_bridge_port_group *pg = (void *)data; struct net_bridge_port *port = pg->port; struct net_bridge *br = port->br; spin_lock(&br->multicast_lock); if (!netif_running(br->dev) || hlist_unhashed(&pg->mglist) || pg->queries_sent >= br->multicast_last_member_count) goto out; br_multicast_send_port_group_query(pg); out: spin_unlock(&br->multicast_lock); } 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; struct hlist_node *p; unsigned count = 0; unsigned max; int elasticity; int err; mdb = rcu_dereference_protected(br->mdb, 1); hlist_for_each_entry(mp, p, &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 " "reached, disabling snooping: %s, %d\n", port ? port->dev->name : br->dev->name, max); 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; } static 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; setup_timer(&mp->timer, br_multicast_group_expired, (unsigned long)mp); setup_timer(&mp->query_timer, br_multicast_group_query_expired, (unsigned long)mp); hlist_add_head_rcu(&mp->hlist[mdb->ver], &mdb->mhash[hash]); mdb->size++; out: return mp; } 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; unsigned long now = jiffies; 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) { if (hlist_unhashed(&mp->mglist)) hlist_add_head(&mp->mglist, &br->mglist); mod_timer(&mp->timer, now + br->multicast_membership_interval); goto out; } for (pp = &mp->ports; (p = mlock_dereference(*pp, br)) != NULL; pp = &p->next) { if (p->port == port) goto found; if ((unsigned long)p->port < (unsigned long)port) break; } p = kzalloc(sizeof(*p), GFP_ATOMIC); err = -ENOMEM; if (unlikely(!p)) goto err; p->addr = *group; p->port = port; p->next = *pp; hlist_add_head(&p->mglist, &port->mglist); setup_timer(&p->timer, br_multicast_port_group_expired, (unsigned long)p); setup_timer(&p->query_timer, br_multicast_port_group_query_expired, (unsigned long)p); rcu_assign_pointer(*pp, p); found: mod_timer(&p->timer, now + br->multicast_membership_interval); 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) { 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); return br_multicast_add_group(br, port, &br_group); } #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) static int br_ip6_multicast_add_group(struct net_bridge *br, struct net_bridge_port *port, const struct in6_addr *group) { struct br_ip br_group; if (ipv6_is_local_multicast(group)) return 0; ipv6_addr_copy(&br_group.u.ip6, group); br_group.proto = htons(ETH_P_IP); 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_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 || 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 defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) 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 *p, *n; spin_lock(&br->multicast_lock); hlist_for_each_entry_safe(pg, p, 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; if (!pskb_may_pull(skb, sizeof(*ih))) return -EINVAL; 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); if (err) break; } return err; } #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) 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; if (!pskb_may_pull(skb, sizeof(*icmp6h))) return -EINVAL; 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_mca), sizeof(_nsrcs), &_nsrcs); if (!nsrcs) return -EINVAL; if (!pskb_may_pull(skb, len + sizeof(*grec) + sizeof(struct in6_addr) * (*nsrcs))) return -EINVAL; grec = (struct mld2_grec *)(skb->data + len); len += sizeof(*grec) + sizeof(struct in6_addr) * (*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); if (!err) break; } return err; } #endif /* * Add port to rotuer_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 *n, *slot = NULL; hlist_for_each_entry(p, n, &br->router_list, rlist) { if ((unsigned long) port >= (unsigned long) p) break; slot = n; } 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) { 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; 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; mp = br_mdb_ip4_get(mlock_dereference(br->mdb, br), group); if (!mp) goto out; max_delay *= br->multicast_last_member_count; if (!hlist_unhashed(&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(&mp->timer, now + max_delay); } out: spin_unlock(&br->multicast_lock); return err; } #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) static int br_ip6_multicast_query(struct net_bridge *br, struct net_bridge_port *port, struct sk_buff *skb) { struct ipv6hdr *ip6h = ipv6_hdr(skb); struct mld_msg *mld = (struct mld_msg *) icmp6_hdr(skb); 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; struct in6_addr *group = NULL; int err = 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(htons(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(mld2q->mld2q_mrc) : 1; } if (!group) goto out; mp = br_mdb_ip6_get(mlock_dereference(br->mdb, br), group); if (!mp) goto out; max_delay *= br->multicast_last_member_count; if (!hlist_unhashed(&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(&mp->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; now = jiffies; time = now + br->multicast_last_member_count * br->multicast_last_member_interval; if (!port) { if (!hlist_unhashed(&mp->mglist) && (timer_pending(&mp->timer) ? time_after(mp->timer.expires, time) : try_to_del_timer_sync(&mp->timer) >= 0)) { mod_timer(&mp->timer, time); mp->queries_sent = 0; mod_timer(&mp->query_timer, now); } goto out; } 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); p->queries_sent = 0; mod_timer(&p->query_timer, now); } break; } out: spin_unlock(&br->multicast_lock); } static void br_ip4_multicast_leave_group(struct net_bridge *br, struct net_bridge_port *port, __be32 group) { 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_multicast_leave_group(br, port, &br_group); } #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) static void br_ip6_multicast_leave_group(struct net_bridge *br, struct net_bridge_port *port, const struct in6_addr *group) { struct br_ip br_group; if (ipv6_is_local_multicast(group)) return; ipv6_addr_copy(&br_group.u.ip6, group); br_group.proto = htons(ETH_P_IPV6); 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; struct iphdr *iph; struct igmphdr *ih; unsigned len; unsigned offset; int err; /* 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) 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_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(skb2)->mrouters_only = 1; err = br_ip4_multicast_add_group(br, port, ih->group); 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); break; } out: __skb_push(skb2, offset); err_out: if (skb2 != skb) kfree_skb(skb2); return err; } #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) static int br_multicast_ipv6_rcv(struct net_bridge *br, struct net_bridge_port *port, struct sk_buff *skb) { struct sk_buff *skb2; struct ipv6hdr *ip6h; struct icmp6hdr *icmp6h; u8 nexthdr; unsigned len; int offset; int err; 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); if (skb->len < len) return -EINVAL; nexthdr = ip6h->nexthdr; offset = ipv6_skip_exthdr(skb, sizeof(*ip6h), &nexthdr); 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); icmp6h = icmp6_hdr(skb2); switch (icmp6h->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; } switch (skb2->ip_summed) { case CHECKSUM_COMPLETE: if (!csum_fold(skb2->csum)) break; /*FALLTHROUGH*/ case CHECKSUM_NONE: skb2->csum = 0; if (skb_checksum_complete(skb2)) goto out; } err = 0; BR_INPUT_SKB_CB(skb)->igmp = 1; switch (icmp6h->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(skb2)->mrouters_only = 1; err = br_ip6_multicast_add_group(br, port, &mld->mld_mca); 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); } } 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 defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) 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_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_local_router_expired, 0); 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 *p, *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, p, n, &mdb->mhash[i], hlist[ver]) { del_timer(&mp->timer); del_timer(&mp->query_timer); 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; } int br_multicast_toggle(struct net_bridge *br, unsigned long val) { struct net_bridge_port *port; int err = 0; struct net_bridge_mdb_htable *mdb; spin_lock(&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_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); } unlock: spin_unlock(&br->multicast_lock); return err; } 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-399/c/good_3427_0
crossvul-cpp_data_good_1677_0
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * The User Datagram Protocol (UDP). * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Arnt Gulbrandsen, <agulbra@nvg.unit.no> * Alan Cox, <alan@lxorguk.ukuu.org.uk> * Hirokazu Takahashi, <taka@valinux.co.jp> * * Fixes: * Alan Cox : verify_area() calls * Alan Cox : stopped close while in use off icmp * messages. Not a fix but a botch that * for udp at least is 'valid'. * Alan Cox : Fixed icmp handling properly * Alan Cox : Correct error for oversized datagrams * Alan Cox : Tidied select() semantics. * Alan Cox : udp_err() fixed properly, also now * select and read wake correctly on errors * Alan Cox : udp_send verify_area moved to avoid mem leak * Alan Cox : UDP can count its memory * Alan Cox : send to an unknown connection causes * an ECONNREFUSED off the icmp, but * does NOT close. * Alan Cox : Switched to new sk_buff handlers. No more backlog! * Alan Cox : Using generic datagram code. Even smaller and the PEEK * bug no longer crashes it. * Fred Van Kempen : Net2e support for sk->broadcast. * Alan Cox : Uses skb_free_datagram * Alan Cox : Added get/set sockopt support. * Alan Cox : Broadcasting without option set returns EACCES. * Alan Cox : No wakeup calls. Instead we now use the callbacks. * Alan Cox : Use ip_tos and ip_ttl * Alan Cox : SNMP Mibs * Alan Cox : MSG_DONTROUTE, and 0.0.0.0 support. * Matt Dillon : UDP length checks. * Alan Cox : Smarter af_inet used properly. * Alan Cox : Use new kernel side addressing. * Alan Cox : Incorrect return on truncated datagram receive. * Arnt Gulbrandsen : New udp_send and stuff * Alan Cox : Cache last socket * Alan Cox : Route cache * Jon Peatfield : Minor efficiency fix to sendto(). * Mike Shaver : RFC1122 checks. * Alan Cox : Nonblocking error fix. * Willy Konynenberg : Transparent proxying support. * Mike McLagan : Routing by source * David S. Miller : New socket lookup architecture. * Last socket cache retained as it * does have a high hit rate. * Olaf Kirch : Don't linearise iovec on sendmsg. * Andi Kleen : Some cleanups, cache destination entry * for connect. * Vitaly E. Lavrov : Transparent proxy revived after year coma. * Melvin Smith : Check msg_name not msg_namelen in sendto(), * return ENOTCONN for unconnected sockets (POSIX) * Janos Farkas : don't deliver multi/broadcasts to a different * bound-to-device socket * Hirokazu Takahashi : HW checksumming for outgoing UDP * datagrams. * Hirokazu Takahashi : sendfile() on UDP works now. * Arnaldo C. Melo : convert /proc/net/udp to seq_file * YOSHIFUJI Hideaki @USAGI and: Support IPV6_V6ONLY socket option, which * Alexey Kuznetsov: allow both IPv4 and IPv6 sockets to bind * a single port at the same time. * Derek Atkins <derek@ihtfp.com>: Add Encapulation Support * James Chapman : Add L2TP encapsulation type. * * * 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) "UDP: " fmt #include <asm/uaccess.h> #include <asm/ioctls.h> #include <linux/bootmem.h> #include <linux/highmem.h> #include <linux/swap.h> #include <linux/types.h> #include <linux/fcntl.h> #include <linux/module.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/igmp.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 <linux/slab.h> #include <net/tcp_states.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <net/net_namespace.h> #include <net/icmp.h> #include <net/inet_hashtables.h> #include <net/route.h> #include <net/checksum.h> #include <net/xfrm.h> #include <trace/events/udp.h> #include <linux/static_key.h> #include <trace/events/skb.h> #include <net/busy_poll.h> #include "udp_impl.h" struct udp_table udp_table __read_mostly; EXPORT_SYMBOL(udp_table); long sysctl_udp_mem[3] __read_mostly; EXPORT_SYMBOL(sysctl_udp_mem); int sysctl_udp_rmem_min __read_mostly; EXPORT_SYMBOL(sysctl_udp_rmem_min); int sysctl_udp_wmem_min __read_mostly; EXPORT_SYMBOL(sysctl_udp_wmem_min); atomic_long_t udp_memory_allocated; EXPORT_SYMBOL(udp_memory_allocated); #define MAX_UDP_PORTS 65536 #define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN) static int udp_lib_lport_inuse(struct net *net, __u16 num, const struct udp_hslot *hslot, unsigned long *bitmap, struct sock *sk, int (*saddr_comp)(const struct sock *sk1, const struct sock *sk2), unsigned int log) { struct sock *sk2; struct hlist_nulls_node *node; kuid_t uid = sock_i_uid(sk); sk_nulls_for_each(sk2, node, &hslot->head) { if (net_eq(sock_net(sk2), net) && sk2 != sk && (bitmap || udp_sk(sk2)->udp_port_hash == num) && (!sk2->sk_reuse || !sk->sk_reuse) && (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if || sk2->sk_bound_dev_if == sk->sk_bound_dev_if) && (!sk2->sk_reuseport || !sk->sk_reuseport || !uid_eq(uid, sock_i_uid(sk2))) && saddr_comp(sk, sk2)) { if (!bitmap) return 1; __set_bit(udp_sk(sk2)->udp_port_hash >> log, bitmap); } } return 0; } /* * Note: we still hold spinlock of primary hash chain, so no other writer * can insert/delete a socket with local_port == num */ static int udp_lib_lport_inuse2(struct net *net, __u16 num, struct udp_hslot *hslot2, struct sock *sk, int (*saddr_comp)(const struct sock *sk1, const struct sock *sk2)) { struct sock *sk2; struct hlist_nulls_node *node; kuid_t uid = sock_i_uid(sk); int res = 0; spin_lock(&hslot2->lock); udp_portaddr_for_each_entry(sk2, node, &hslot2->head) { if (net_eq(sock_net(sk2), net) && sk2 != sk && (udp_sk(sk2)->udp_port_hash == num) && (!sk2->sk_reuse || !sk->sk_reuse) && (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if || sk2->sk_bound_dev_if == sk->sk_bound_dev_if) && (!sk2->sk_reuseport || !sk->sk_reuseport || !uid_eq(uid, sock_i_uid(sk2))) && saddr_comp(sk, sk2)) { res = 1; break; } } spin_unlock(&hslot2->lock); return res; } /** * udp_lib_get_port - UDP/-Lite port lookup for IPv4 and IPv6 * * @sk: socket struct in question * @snum: port number to look up * @saddr_comp: AF-dependent comparison of bound local IP addresses * @hash2_nulladdr: AF-dependent hash value in secondary hash chains, * with NULL address */ int udp_lib_get_port(struct sock *sk, unsigned short snum, int (*saddr_comp)(const struct sock *sk1, const struct sock *sk2), unsigned int hash2_nulladdr) { struct udp_hslot *hslot, *hslot2; struct udp_table *udptable = sk->sk_prot->h.udp_table; int error = 1; struct net *net = sock_net(sk); if (!snum) { int low, high, remaining; unsigned int rand; unsigned short first, last; DECLARE_BITMAP(bitmap, PORTS_PER_CHAIN); inet_get_local_port_range(net, &low, &high); remaining = (high - low) + 1; rand = prandom_u32(); first = reciprocal_scale(rand, remaining) + low; /* * force rand to be an odd multiple of UDP_HTABLE_SIZE */ rand = (rand | 1) * (udptable->mask + 1); last = first + udptable->mask + 1; do { hslot = udp_hashslot(udptable, net, first); bitmap_zero(bitmap, PORTS_PER_CHAIN); spin_lock_bh(&hslot->lock); udp_lib_lport_inuse(net, snum, hslot, bitmap, sk, saddr_comp, udptable->log); snum = first; /* * Iterate on all possible values of snum for this hash. * Using steps of an odd multiple of UDP_HTABLE_SIZE * give us randomization and full range coverage. */ do { if (low <= snum && snum <= high && !test_bit(snum >> udptable->log, bitmap) && !inet_is_local_reserved_port(net, snum)) goto found; snum += rand; } while (snum != first); spin_unlock_bh(&hslot->lock); } while (++first != last); goto fail; } else { hslot = udp_hashslot(udptable, net, snum); spin_lock_bh(&hslot->lock); if (hslot->count > 10) { int exist; unsigned int slot2 = udp_sk(sk)->udp_portaddr_hash ^ snum; slot2 &= udptable->mask; hash2_nulladdr &= udptable->mask; hslot2 = udp_hashslot2(udptable, slot2); if (hslot->count < hslot2->count) goto scan_primary_hash; exist = udp_lib_lport_inuse2(net, snum, hslot2, sk, saddr_comp); if (!exist && (hash2_nulladdr != slot2)) { hslot2 = udp_hashslot2(udptable, hash2_nulladdr); exist = udp_lib_lport_inuse2(net, snum, hslot2, sk, saddr_comp); } if (exist) goto fail_unlock; else goto found; } scan_primary_hash: if (udp_lib_lport_inuse(net, snum, hslot, NULL, sk, saddr_comp, 0)) goto fail_unlock; } found: inet_sk(sk)->inet_num = snum; udp_sk(sk)->udp_port_hash = snum; udp_sk(sk)->udp_portaddr_hash ^= snum; if (sk_unhashed(sk)) { sk_nulls_add_node_rcu(sk, &hslot->head); hslot->count++; sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1); hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash); spin_lock(&hslot2->lock); hlist_nulls_add_head_rcu(&udp_sk(sk)->udp_portaddr_node, &hslot2->head); hslot2->count++; spin_unlock(&hslot2->lock); } error = 0; fail_unlock: spin_unlock_bh(&hslot->lock); fail: return error; } EXPORT_SYMBOL(udp_lib_get_port); static int ipv4_rcv_saddr_equal(const struct sock *sk1, const struct sock *sk2) { struct inet_sock *inet1 = inet_sk(sk1), *inet2 = inet_sk(sk2); return (!ipv6_only_sock(sk2) && (!inet1->inet_rcv_saddr || !inet2->inet_rcv_saddr || inet1->inet_rcv_saddr == inet2->inet_rcv_saddr)); } static u32 udp4_portaddr_hash(const struct net *net, __be32 saddr, unsigned int port) { return jhash_1word((__force u32)saddr, net_hash_mix(net)) ^ port; } int udp_v4_get_port(struct sock *sk, unsigned short snum) { unsigned int hash2_nulladdr = udp4_portaddr_hash(sock_net(sk), htonl(INADDR_ANY), snum); unsigned int hash2_partial = udp4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, 0); /* precompute partial secondary hash */ udp_sk(sk)->udp_portaddr_hash = hash2_partial; return udp_lib_get_port(sk, snum, ipv4_rcv_saddr_equal, hash2_nulladdr); } static inline int compute_score(struct sock *sk, struct net *net, __be32 saddr, unsigned short hnum, __be16 sport, __be32 daddr, __be16 dport, int dif) { int score; struct inet_sock *inet; if (!net_eq(sock_net(sk), net) || udp_sk(sk)->udp_port_hash != hnum || ipv6_only_sock(sk)) return -1; score = (sk->sk_family == PF_INET) ? 2 : 1; inet = inet_sk(sk); if (inet->inet_rcv_saddr) { if (inet->inet_rcv_saddr != daddr) return -1; score += 4; } if (inet->inet_daddr) { if (inet->inet_daddr != saddr) return -1; score += 4; } if (inet->inet_dport) { if (inet->inet_dport != sport) return -1; score += 4; } if (sk->sk_bound_dev_if) { if (sk->sk_bound_dev_if != dif) return -1; score += 4; } return score; } /* * In this second variant, we check (daddr, dport) matches (inet_rcv_sadd, inet_num) */ static inline int compute_score2(struct sock *sk, struct net *net, __be32 saddr, __be16 sport, __be32 daddr, unsigned int hnum, int dif) { int score; struct inet_sock *inet; if (!net_eq(sock_net(sk), net) || ipv6_only_sock(sk)) return -1; inet = inet_sk(sk); if (inet->inet_rcv_saddr != daddr || inet->inet_num != hnum) return -1; score = (sk->sk_family == PF_INET) ? 2 : 1; if (inet->inet_daddr) { if (inet->inet_daddr != saddr) return -1; score += 4; } if (inet->inet_dport) { if (inet->inet_dport != sport) return -1; score += 4; } if (sk->sk_bound_dev_if) { if (sk->sk_bound_dev_if != dif) return -1; score += 4; } return score; } static u32 udp_ehashfn(const struct net *net, const __be32 laddr, const __u16 lport, const __be32 faddr, const __be16 fport) { static u32 udp_ehash_secret __read_mostly; net_get_random_once(&udp_ehash_secret, sizeof(udp_ehash_secret)); return __inet_ehashfn(laddr, lport, faddr, fport, udp_ehash_secret + net_hash_mix(net)); } /* called with read_rcu_lock() */ static struct sock *udp4_lib_lookup2(struct net *net, __be32 saddr, __be16 sport, __be32 daddr, unsigned int hnum, int dif, struct udp_hslot *hslot2, unsigned int slot2) { struct sock *sk, *result; struct hlist_nulls_node *node; int score, badness, matches = 0, reuseport = 0; u32 hash = 0; begin: result = NULL; badness = 0; udp_portaddr_for_each_entry_rcu(sk, node, &hslot2->head) { score = compute_score2(sk, net, saddr, sport, daddr, hnum, dif); if (score > badness) { result = sk; badness = score; reuseport = sk->sk_reuseport; if (reuseport) { hash = udp_ehashfn(net, daddr, hnum, saddr, sport); matches = 1; } } else if (score == badness && reuseport) { matches++; if (reciprocal_scale(hash, matches) == 0) result = sk; hash = next_pseudo_random32(hash); } } /* * if the nulls value we got at the end of this lookup is * not the expected one, we must restart lookup. * We probably met an item that was moved to another chain. */ if (get_nulls_value(node) != slot2) goto begin; if (result) { if (unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2))) result = NULL; else if (unlikely(compute_score2(result, net, saddr, sport, daddr, hnum, dif) < badness)) { sock_put(result); goto begin; } } return result; } /* UDP is nearly always wildcards out the wazoo, it makes no sense to try * harder than this. -DaveM */ struct sock *__udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport, __be32 daddr, __be16 dport, int dif, struct udp_table *udptable) { struct sock *sk, *result; struct hlist_nulls_node *node; unsigned short hnum = ntohs(dport); unsigned int hash2, slot2, slot = udp_hashfn(net, hnum, udptable->mask); struct udp_hslot *hslot2, *hslot = &udptable->hash[slot]; int score, badness, matches = 0, reuseport = 0; u32 hash = 0; rcu_read_lock(); if (hslot->count > 10) { hash2 = udp4_portaddr_hash(net, daddr, hnum); slot2 = hash2 & udptable->mask; hslot2 = &udptable->hash2[slot2]; if (hslot->count < hslot2->count) goto begin; result = udp4_lib_lookup2(net, saddr, sport, daddr, hnum, dif, hslot2, slot2); if (!result) { hash2 = udp4_portaddr_hash(net, htonl(INADDR_ANY), hnum); slot2 = hash2 & udptable->mask; hslot2 = &udptable->hash2[slot2]; if (hslot->count < hslot2->count) goto begin; result = udp4_lib_lookup2(net, saddr, sport, htonl(INADDR_ANY), hnum, dif, hslot2, slot2); } rcu_read_unlock(); return result; } begin: result = NULL; badness = 0; sk_nulls_for_each_rcu(sk, node, &hslot->head) { score = compute_score(sk, net, saddr, hnum, sport, daddr, dport, dif); if (score > badness) { result = sk; badness = score; reuseport = sk->sk_reuseport; if (reuseport) { hash = udp_ehashfn(net, daddr, hnum, saddr, sport); matches = 1; } } else if (score == badness && reuseport) { matches++; if (reciprocal_scale(hash, matches) == 0) result = sk; hash = next_pseudo_random32(hash); } } /* * if the nulls value we got at the end of this lookup is * not the expected one, we must restart lookup. * We probably met an item that was moved to another chain. */ if (get_nulls_value(node) != slot) goto begin; if (result) { if (unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2))) result = NULL; else if (unlikely(compute_score(result, net, saddr, hnum, sport, daddr, dport, dif) < badness)) { sock_put(result); goto begin; } } rcu_read_unlock(); return result; } EXPORT_SYMBOL_GPL(__udp4_lib_lookup); static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb, __be16 sport, __be16 dport, struct udp_table *udptable) { const struct iphdr *iph = ip_hdr(skb); return __udp4_lib_lookup(dev_net(skb_dst(skb)->dev), iph->saddr, sport, iph->daddr, dport, inet_iif(skb), udptable); } struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport, __be32 daddr, __be16 dport, int dif) { return __udp4_lib_lookup(net, saddr, sport, daddr, dport, dif, &udp_table); } EXPORT_SYMBOL_GPL(udp4_lib_lookup); static inline bool __udp_is_mcast_sock(struct net *net, struct sock *sk, __be16 loc_port, __be32 loc_addr, __be16 rmt_port, __be32 rmt_addr, int dif, unsigned short hnum) { struct inet_sock *inet = inet_sk(sk); if (!net_eq(sock_net(sk), net) || udp_sk(sk)->udp_port_hash != hnum || (inet->inet_daddr && inet->inet_daddr != rmt_addr) || (inet->inet_dport != rmt_port && inet->inet_dport) || (inet->inet_rcv_saddr && inet->inet_rcv_saddr != loc_addr) || ipv6_only_sock(sk) || (sk->sk_bound_dev_if && sk->sk_bound_dev_if != dif)) return false; if (!ip_mc_sf_allow(sk, loc_addr, rmt_addr, dif)) return false; return true; } /* * This routine is called by the ICMP module when it gets some * sort of error condition. If err < 0 then the socket should * be closed and the error returned to the user. If err > 0 * it's just the icmp type << 8 | icmp code. * Header points to the ip header of the error packet. We move * on past this. Then (as it used to claim before adjustment) * header points to the first 8 bytes of the udp header. We need * to find the appropriate port. */ void __udp4_lib_err(struct sk_buff *skb, u32 info, struct udp_table *udptable) { struct inet_sock *inet; const struct iphdr *iph = (const struct iphdr *)skb->data; struct udphdr *uh = (struct udphdr *)(skb->data+(iph->ihl<<2)); const int type = icmp_hdr(skb)->type; const int code = icmp_hdr(skb)->code; struct sock *sk; int harderr; int err; struct net *net = dev_net(skb->dev); sk = __udp4_lib_lookup(net, iph->daddr, uh->dest, iph->saddr, uh->source, skb->dev->ifindex, udptable); if (!sk) { ICMP_INC_STATS_BH(net, ICMP_MIB_INERRORS); return; /* No socket for error */ } err = 0; harderr = 0; inet = inet_sk(sk); switch (type) { default: case ICMP_TIME_EXCEEDED: err = EHOSTUNREACH; break; case ICMP_SOURCE_QUENCH: goto out; 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->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: ipv4_sk_redirect(skb, sk); goto out; } /* * RFC1122: OK. Passes ICMP errors back to application, as per * 4.1.3.3. */ if (!inet->recverr) { if (!harderr || sk->sk_state != TCP_ESTABLISHED) goto out; } else ip_icmp_error(sk, skb, err, uh->dest, info, (u8 *)(uh+1)); sk->sk_err = err; sk->sk_error_report(sk); out: sock_put(sk); } void udp_err(struct sk_buff *skb, u32 info) { __udp4_lib_err(skb, info, &udp_table); } /* * Throw away all pending data and cancel the corking. Socket is locked. */ void udp_flush_pending_frames(struct sock *sk) { struct udp_sock *up = udp_sk(sk); if (up->pending) { up->len = 0; up->pending = 0; ip_flush_pending_frames(sk); } } EXPORT_SYMBOL(udp_flush_pending_frames); /** * udp4_hwcsum - handle outgoing HW checksumming * @skb: sk_buff containing the filled-in UDP header * (checksum field must be zeroed out) * @src: source IP address * @dst: destination IP address */ void udp4_hwcsum(struct sk_buff *skb, __be32 src, __be32 dst) { struct udphdr *uh = udp_hdr(skb); int offset = skb_transport_offset(skb); int len = skb->len - offset; int hlen = len; __wsum csum = 0; if (!skb_has_frag_list(skb)) { /* * Only one fragment on the socket. */ skb->csum_start = skb_transport_header(skb) - skb->head; skb->csum_offset = offsetof(struct udphdr, check); uh->check = ~csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, 0); } else { struct sk_buff *frags; /* * HW-checksum won't work as there are two or more * fragments on the socket so that all csums of sk_buffs * should be together */ skb_walk_frags(skb, frags) { csum = csum_add(csum, frags->csum); hlen -= frags->len; } csum = skb_checksum(skb, offset, hlen, csum); skb->ip_summed = CHECKSUM_NONE; uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum); if (uh->check == 0) uh->check = CSUM_MANGLED_0; } } EXPORT_SYMBOL_GPL(udp4_hwcsum); /* Function to set UDP checksum for an IPv4 UDP packet. This is intended * for the simple case like when setting the checksum for a UDP tunnel. */ void udp_set_csum(bool nocheck, struct sk_buff *skb, __be32 saddr, __be32 daddr, int len) { struct udphdr *uh = udp_hdr(skb); if (nocheck) uh->check = 0; else if (skb_is_gso(skb)) uh->check = ~udp_v4_check(len, saddr, daddr, 0); else if (skb_dst(skb) && skb_dst(skb)->dev && (skb_dst(skb)->dev->features & NETIF_F_V4_CSUM)) { BUG_ON(skb->ip_summed == CHECKSUM_PARTIAL); skb->ip_summed = CHECKSUM_PARTIAL; skb->csum_start = skb_transport_header(skb) - skb->head; skb->csum_offset = offsetof(struct udphdr, check); uh->check = ~udp_v4_check(len, saddr, daddr, 0); } else { __wsum csum; BUG_ON(skb->ip_summed == CHECKSUM_PARTIAL); uh->check = 0; csum = skb_checksum(skb, 0, len, 0); uh->check = udp_v4_check(len, saddr, daddr, csum); if (uh->check == 0) uh->check = CSUM_MANGLED_0; skb->ip_summed = CHECKSUM_UNNECESSARY; } } EXPORT_SYMBOL(udp_set_csum); static int udp_send_skb(struct sk_buff *skb, struct flowi4 *fl4) { struct sock *sk = skb->sk; struct inet_sock *inet = inet_sk(sk); struct udphdr *uh; int err = 0; int is_udplite = IS_UDPLITE(sk); int offset = skb_transport_offset(skb); int len = skb->len - offset; __wsum csum = 0; /* * Create a UDP header */ uh = udp_hdr(skb); uh->source = inet->inet_sport; uh->dest = fl4->fl4_dport; uh->len = htons(len); uh->check = 0; if (is_udplite) /* UDP-Lite */ csum = udplite_csum(skb); else if (sk->sk_no_check_tx) { /* UDP csum disabled */ skb->ip_summed = CHECKSUM_NONE; goto send; } else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */ udp4_hwcsum(skb, fl4->saddr, fl4->daddr); goto send; } else csum = udp_csum(skb); /* add protocol-dependent pseudo-header */ uh->check = csum_tcpudp_magic(fl4->saddr, fl4->daddr, len, sk->sk_protocol, csum); if (uh->check == 0) uh->check = CSUM_MANGLED_0; send: err = ip_send_skb(sock_net(sk), skb); if (err) { if (err == -ENOBUFS && !inet->recverr) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_SNDBUFERRORS, is_udplite); err = 0; } } else UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_OUTDATAGRAMS, is_udplite); return err; } /* * Push out all pending data as one UDP datagram. Socket is locked. */ int udp_push_pending_frames(struct sock *sk) { struct udp_sock *up = udp_sk(sk); struct inet_sock *inet = inet_sk(sk); struct flowi4 *fl4 = &inet->cork.fl.u.ip4; struct sk_buff *skb; int err = 0; skb = ip_finish_skb(sk, fl4); if (!skb) goto out; err = udp_send_skb(skb, fl4); out: up->len = 0; up->pending = 0; return err; } EXPORT_SYMBOL(udp_push_pending_frames); int udp_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) { struct inet_sock *inet = inet_sk(sk); struct udp_sock *up = udp_sk(sk); struct flowi4 fl4_stack; struct flowi4 *fl4; int ulen = len; struct ipcm_cookie ipc; struct rtable *rt = NULL; int free = 0; int connected = 0; __be32 daddr, faddr, saddr; __be16 dport; u8 tos; int err, is_udplite = IS_UDPLITE(sk); int corkreq = up->corkflag || msg->msg_flags&MSG_MORE; int (*getfrag)(void *, char *, int, int, int, struct sk_buff *); struct sk_buff *skb; struct ip_options_data opt_copy; if (len > 0xFFFF) return -EMSGSIZE; /* * Check the flags. */ if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */ return -EOPNOTSUPP; ipc.opt = NULL; ipc.tx_flags = 0; ipc.ttl = 0; ipc.tos = -1; getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag; fl4 = &inet->cork.fl.u.ip4; if (up->pending) { /* * There are pending frames. * The socket lock must be held while it's corked. */ lock_sock(sk); if (likely(up->pending)) { if (unlikely(up->pending != AF_INET)) { release_sock(sk); return -EINVAL; } goto do_append_data; } release_sock(sk); } ulen += sizeof(struct udphdr); /* * Get and verify the address. */ if (msg->msg_name) { DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name); if (msg->msg_namelen < sizeof(*usin)) return -EINVAL; if (usin->sin_family != AF_INET) { if (usin->sin_family != AF_UNSPEC) return -EAFNOSUPPORT; } daddr = usin->sin_addr.s_addr; dport = usin->sin_port; if (dport == 0) return -EINVAL; } else { if (sk->sk_state != TCP_ESTABLISHED) return -EDESTADDRREQ; daddr = inet->inet_daddr; dport = inet->inet_dport; /* Open fast path for connected socket. Route will not be used, if at least one option is set. */ connected = 1; } ipc.addr = inet->inet_saddr; ipc.oif = sk->sk_bound_dev_if; sock_tx_timestamp(sk, &ipc.tx_flags); if (msg->msg_controllen) { err = ip_cmsg_send(sock_net(sk), msg, &ipc, sk->sk_family == AF_INET6); if (err) return err; if (ipc.opt) free = 1; connected = 0; } 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; connected = 0; } 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; connected = 0; } if (ipv4_is_multicast(daddr)) { if (!ipc.oif) ipc.oif = inet->mc_index; if (!saddr) saddr = inet->mc_addr; connected = 0; } else if (!ipc.oif) ipc.oif = inet->uc_index; if (connected) rt = (struct rtable *)sk_dst_check(sk, 0); if (!rt) { struct net *net = sock_net(sk); fl4 = &fl4_stack; flowi4_init_output(fl4, ipc.oif, sk->sk_mark, tos, RT_SCOPE_UNIVERSE, sk->sk_protocol, inet_sk_flowi_flags(sk), faddr, saddr, dport, inet->inet_sport); 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(net, IPSTATS_MIB_OUTNOROUTES); goto out; } err = -EACCES; if ((rt->rt_flags & RTCF_BROADCAST) && !sock_flag(sk, SOCK_BROADCAST)) goto out; if (connected) sk_dst_set(sk, dst_clone(&rt->dst)); } if (msg->msg_flags&MSG_CONFIRM) goto do_confirm; back_from_confirm: saddr = fl4->saddr; if (!ipc.addr) daddr = ipc.addr = fl4->daddr; /* Lockless fast path for the non-corking case. */ if (!corkreq) { skb = ip_make_skb(sk, fl4, getfrag, msg, ulen, sizeof(struct udphdr), &ipc, &rt, msg->msg_flags); err = PTR_ERR(skb); if (!IS_ERR_OR_NULL(skb)) err = udp_send_skb(skb, fl4); goto out; } lock_sock(sk); if (unlikely(up->pending)) { /* The socket is already corked while preparing it. */ /* ... which is an evident application bug. --ANK */ release_sock(sk); net_dbg_ratelimited("cork app bug 2\n"); err = -EINVAL; goto out; } /* * Now cork the socket to pend data. */ fl4 = &inet->cork.fl.u.ip4; fl4->daddr = daddr; fl4->saddr = saddr; fl4->fl4_dport = dport; fl4->fl4_sport = inet->inet_sport; up->pending = AF_INET; do_append_data: up->len += ulen; err = ip_append_data(sk, fl4, getfrag, msg, ulen, sizeof(struct udphdr), &ipc, &rt, corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags); if (err) udp_flush_pending_frames(sk); else if (!corkreq) err = udp_push_pending_frames(sk); else if (unlikely(skb_queue_empty(&sk->sk_write_queue))) up->pending = 0; release_sock(sk); out: ip_rt_put(rt); if (free) kfree(ipc.opt); if (!err) return len; /* * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting * ENOBUFS might not be good (it's not tunable per se), but otherwise * we don't have a good statistic (IpOutDiscards but it can be too many * things). We could add another new stat but at least for now that * seems like overkill. */ if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_SNDBUFERRORS, is_udplite); } return err; do_confirm: dst_confirm(&rt->dst); if (!(msg->msg_flags&MSG_PROBE) || len) goto back_from_confirm; err = 0; goto out; } EXPORT_SYMBOL(udp_sendmsg); int udp_sendpage(struct sock *sk, struct page *page, int offset, size_t size, int flags) { struct inet_sock *inet = inet_sk(sk); struct udp_sock *up = udp_sk(sk); int ret; if (flags & MSG_SENDPAGE_NOTLAST) flags |= MSG_MORE; if (!up->pending) { struct msghdr msg = { .msg_flags = flags|MSG_MORE }; /* Call udp_sendmsg to specify destination address which * sendpage interface can't pass. * This will succeed only when the socket is connected. */ ret = udp_sendmsg(sk, &msg, 0); if (ret < 0) return ret; } lock_sock(sk); if (unlikely(!up->pending)) { release_sock(sk); net_dbg_ratelimited("udp cork app bug 3\n"); return -EINVAL; } ret = ip_append_page(sk, &inet->cork.fl.u.ip4, page, offset, size, flags); if (ret == -EOPNOTSUPP) { release_sock(sk); return sock_no_sendpage(sk->sk_socket, page, offset, size, flags); } if (ret < 0) { udp_flush_pending_frames(sk); goto out; } up->len += size; if (!(up->corkflag || (flags&MSG_MORE))) ret = udp_push_pending_frames(sk); if (!ret) ret = size; out: release_sock(sk); return ret; } /** * first_packet_length - return length of first packet in receive queue * @sk: socket * * Drops all bad checksum frames, until a valid one is found. * Returns the length of found skb, or 0 if none is found. */ static unsigned int first_packet_length(struct sock *sk) { struct sk_buff_head list_kill, *rcvq = &sk->sk_receive_queue; struct sk_buff *skb; unsigned int res; __skb_queue_head_init(&list_kill); spin_lock_bh(&rcvq->lock); while ((skb = skb_peek(rcvq)) != NULL && udp_lib_checksum_complete(skb)) { UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_CSUMERRORS, IS_UDPLITE(sk)); UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, IS_UDPLITE(sk)); atomic_inc(&sk->sk_drops); __skb_unlink(skb, rcvq); __skb_queue_tail(&list_kill, skb); } res = skb ? skb->len : 0; spin_unlock_bh(&rcvq->lock); if (!skb_queue_empty(&list_kill)) { bool slow = lock_sock_fast(sk); __skb_queue_purge(&list_kill); sk_mem_reclaim_partial(sk); unlock_sock_fast(sk, slow); } return res; } /* * IOCTL requests applicable to the UDP protocol */ int udp_ioctl(struct sock *sk, int cmd, unsigned long arg) { switch (cmd) { case SIOCOUTQ: { int amount = sk_wmem_alloc_get(sk); return put_user(amount, (int __user *)arg); } case SIOCINQ: { unsigned int amount = first_packet_length(sk); if (amount) /* * We will only return the amount * of this packet since that is all * that will be read. */ amount -= sizeof(struct udphdr); return put_user(amount, (int __user *)arg); } default: return -ENOIOCTLCMD; } return 0; } EXPORT_SYMBOL(udp_ioctl); /* * This should be easy, if there is something there we * return it, otherwise we block. */ int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *inet = inet_sk(sk); DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name); struct sk_buff *skb; unsigned int ulen, copied; int peeked, off = 0; int err; int is_udplite = IS_UDPLITE(sk); bool slow; if (flags & MSG_ERRQUEUE) return ip_recv_error(sk, msg, len, addr_len); try_again: skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0), &peeked, &off, &err); if (!skb) goto out; ulen = skb->len - sizeof(struct udphdr); copied = len; if (copied > ulen) copied = ulen; else if (copied < ulen) msg->msg_flags |= MSG_TRUNC; /* * If checksum is needed at all, try to do it while copying the * data. If the data is truncated, or if we only want a partial * coverage checksum (UDP-Lite), do it before the copy. */ if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) { if (udp_lib_checksum_complete(skb)) goto csum_copy_err; } if (skb_csum_unnecessary(skb)) err = skb_copy_datagram_msg(skb, sizeof(struct udphdr), msg, copied); else { err = skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr), msg); if (err == -EINVAL) goto csum_copy_err; } if (unlikely(err)) { trace_kfree_skb(skb, udp_recvmsg); if (!peeked) { atomic_inc(&sk->sk_drops); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } goto out_free; } if (!peeked) UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); sock_recv_ts_and_drops(msg, sk, skb); /* Copy the address. */ if (sin) { sin->sin_family = AF_INET; sin->sin_port = udp_hdr(skb)->source; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); *addr_len = sizeof(*sin); } if (inet->cmsg_flags) ip_cmsg_recv_offset(msg, skb, sizeof(struct udphdr)); err = copied; if (flags & MSG_TRUNC) err = ulen; out_free: skb_free_datagram_locked(sk, skb); out: return err; csum_copy_err: slow = lock_sock_fast(sk); if (!skb_kill_datagram(sk, skb, flags)) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } unlock_sock_fast(sk, slow); /* starting over for a new packet, but check if we need to yield */ cond_resched(); msg->msg_flags &= ~MSG_TRUNC; goto try_again; } int udp_disconnect(struct sock *sk, int flags) { struct inet_sock *inet = inet_sk(sk); /* * 1003.1g - break association. */ sk->sk_state = TCP_CLOSE; inet->inet_daddr = 0; inet->inet_dport = 0; sock_rps_reset_rxhash(sk); sk->sk_bound_dev_if = 0; if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) inet_reset_saddr(sk); if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) { sk->sk_prot->unhash(sk); inet->inet_sport = 0; } sk_dst_reset(sk); return 0; } EXPORT_SYMBOL(udp_disconnect); void udp_lib_unhash(struct sock *sk) { if (sk_hashed(sk)) { struct udp_table *udptable = sk->sk_prot->h.udp_table; struct udp_hslot *hslot, *hslot2; hslot = udp_hashslot(udptable, sock_net(sk), udp_sk(sk)->udp_port_hash); hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash); spin_lock_bh(&hslot->lock); if (sk_nulls_del_node_init_rcu(sk)) { hslot->count--; inet_sk(sk)->inet_num = 0; sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1); spin_lock(&hslot2->lock); hlist_nulls_del_init_rcu(&udp_sk(sk)->udp_portaddr_node); hslot2->count--; spin_unlock(&hslot2->lock); } spin_unlock_bh(&hslot->lock); } } EXPORT_SYMBOL(udp_lib_unhash); /* * inet_rcv_saddr was changed, we must rehash secondary hash */ void udp_lib_rehash(struct sock *sk, u16 newhash) { if (sk_hashed(sk)) { struct udp_table *udptable = sk->sk_prot->h.udp_table; struct udp_hslot *hslot, *hslot2, *nhslot2; hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash); nhslot2 = udp_hashslot2(udptable, newhash); udp_sk(sk)->udp_portaddr_hash = newhash; if (hslot2 != nhslot2) { hslot = udp_hashslot(udptable, sock_net(sk), udp_sk(sk)->udp_port_hash); /* we must lock primary chain too */ spin_lock_bh(&hslot->lock); spin_lock(&hslot2->lock); hlist_nulls_del_init_rcu(&udp_sk(sk)->udp_portaddr_node); hslot2->count--; spin_unlock(&hslot2->lock); spin_lock(&nhslot2->lock); hlist_nulls_add_head_rcu(&udp_sk(sk)->udp_portaddr_node, &nhslot2->head); nhslot2->count++; spin_unlock(&nhslot2->lock); spin_unlock_bh(&hslot->lock); } } } EXPORT_SYMBOL(udp_lib_rehash); static void udp_v4_rehash(struct sock *sk) { u16 new_hash = udp4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, inet_sk(sk)->inet_num); udp_lib_rehash(sk, new_hash); } static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { int rc; if (inet_sk(sk)->inet_daddr) { sock_rps_save_rxhash(sk, skb); sk_mark_napi_id(sk, skb); sk_incoming_cpu_update(sk); } rc = sock_queue_rcv_skb(sk, skb); if (rc < 0) { int is_udplite = IS_UDPLITE(sk); /* Note that an ENOMEM error is charged twice */ if (rc == -ENOMEM) UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS, is_udplite); UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite); kfree_skb(skb); trace_udp_fail_queue_rcv_skb(rc, sk); return -1; } return 0; } static struct static_key udp_encap_needed __read_mostly; void udp_encap_enable(void) { if (!static_key_enabled(&udp_encap_needed)) static_key_slow_inc(&udp_encap_needed); } EXPORT_SYMBOL(udp_encap_enable); /* returns: * -1: error * 0: success * >0: "udp encap" protocol resubmission * * Note that in the success and error cases, the skb is assumed to * have either been requeued or freed. */ int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { struct udp_sock *up = udp_sk(sk); int rc; int is_udplite = IS_UDPLITE(sk); /* * Charge it to the socket, dropping if the queue is full. */ if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) goto drop; nf_reset(skb); if (static_key_false(&udp_encap_needed) && up->encap_type) { int (*encap_rcv)(struct sock *sk, struct sk_buff *skb); /* * This is an encapsulation socket so pass the skb to * the socket's udp_encap_rcv() hook. Otherwise, just * fall through and pass this up the UDP socket. * up->encap_rcv() returns the following value: * =0 if skb was successfully passed to the encap * handler or was discarded by it. * >0 if skb should be passed on to UDP. * <0 if skb should be resubmitted as proto -N */ /* if we're overly short, let UDP handle it */ encap_rcv = ACCESS_ONCE(up->encap_rcv); if (skb->len > sizeof(struct udphdr) && encap_rcv) { int ret; /* Verify checksum before giving to encap */ if (udp_lib_checksum_complete(skb)) goto csum_error; ret = encap_rcv(sk, skb); if (ret <= 0) { UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); return -ret; } } /* FALLTHROUGH -- it's a UDP Packet */ } /* * UDP-Lite specific tests, ignored on UDP sockets */ if ((is_udplite & UDPLITE_RECV_CC) && UDP_SKB_CB(skb)->partial_cov) { /* * MIB statistics other than incrementing the error count are * disabled for the following two types of errors: these depend * on the application settings, not on the functioning of the * protocol stack as such. * * RFC 3828 here recommends (sec 3.3): "There should also be a * way ... to ... at least let the receiving application block * delivery of packets with coverage values less than a value * provided by the application." */ if (up->pcrlen == 0) { /* full coverage was set */ net_dbg_ratelimited("UDPLite: partial coverage %d while full coverage %d requested\n", UDP_SKB_CB(skb)->cscov, skb->len); goto drop; } /* The next case involves violating the min. coverage requested * by the receiver. This is subtle: if receiver wants x and x is * greater than the buffersize/MTU then receiver will complain * that it wants x while sender emits packets of smaller size y. * Therefore the above ...()->partial_cov statement is essential. */ if (UDP_SKB_CB(skb)->cscov < up->pcrlen) { net_dbg_ratelimited("UDPLite: coverage %d too small, need min %d\n", UDP_SKB_CB(skb)->cscov, up->pcrlen); goto drop; } } if (rcu_access_pointer(sk->sk_filter) && udp_lib_checksum_complete(skb)) goto csum_error; if (sk_rcvqueues_full(sk, sk->sk_rcvbuf)) { UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS, is_udplite); goto drop; } rc = 0; ipv4_pktinfo_prepare(sk, skb); bh_lock_sock(sk); if (!sock_owned_by_user(sk)) rc = __udp_queue_rcv_skb(sk, skb); else if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) { bh_unlock_sock(sk); goto drop; } bh_unlock_sock(sk); return rc; csum_error: UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); drop: UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite); atomic_inc(&sk->sk_drops); kfree_skb(skb); return -1; } static void flush_stack(struct sock **stack, unsigned int count, struct sk_buff *skb, unsigned int final) { unsigned int i; struct sk_buff *skb1 = NULL; struct sock *sk; for (i = 0; i < count; i++) { sk = stack[i]; if (likely(!skb1)) skb1 = (i == final) ? skb : skb_clone(skb, GFP_ATOMIC); if (!skb1) { atomic_inc(&sk->sk_drops); UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS, IS_UDPLITE(sk)); UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, IS_UDPLITE(sk)); } if (skb1 && udp_queue_rcv_skb(sk, skb1) <= 0) skb1 = NULL; sock_put(sk); } if (unlikely(skb1)) kfree_skb(skb1); } /* For TCP sockets, sk_rx_dst is protected by socket lock * For UDP, we use xchg() to guard against concurrent changes. */ static void udp_sk_rx_dst_set(struct sock *sk, struct dst_entry *dst) { struct dst_entry *old; dst_hold(dst); old = xchg(&sk->sk_rx_dst, dst); dst_release(old); } /* * Multicasts and broadcasts go to each listener. * * Note: called only from the BH handler context. */ static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb, struct udphdr *uh, __be32 saddr, __be32 daddr, struct udp_table *udptable, int proto) { struct sock *sk, *stack[256 / sizeof(struct sock *)]; struct hlist_nulls_node *node; unsigned short hnum = ntohs(uh->dest); struct udp_hslot *hslot = udp_hashslot(udptable, net, hnum); int dif = skb->dev->ifindex; unsigned int count = 0, offset = offsetof(typeof(*sk), sk_nulls_node); unsigned int hash2 = 0, hash2_any = 0, use_hash2 = (hslot->count > 10); bool inner_flushed = false; if (use_hash2) { hash2_any = udp4_portaddr_hash(net, htonl(INADDR_ANY), hnum) & udp_table.mask; hash2 = udp4_portaddr_hash(net, daddr, hnum) & udp_table.mask; start_lookup: hslot = &udp_table.hash2[hash2]; offset = offsetof(typeof(*sk), __sk_common.skc_portaddr_node); } spin_lock(&hslot->lock); sk_nulls_for_each_entry_offset(sk, node, &hslot->head, offset) { if (__udp_is_mcast_sock(net, sk, uh->dest, daddr, uh->source, saddr, dif, hnum)) { if (unlikely(count == ARRAY_SIZE(stack))) { flush_stack(stack, count, skb, ~0); inner_flushed = true; count = 0; } stack[count++] = sk; sock_hold(sk); } } spin_unlock(&hslot->lock); /* Also lookup *:port if we are using hash2 and haven't done so yet. */ if (use_hash2 && hash2 != hash2_any) { hash2 = hash2_any; goto start_lookup; } /* * do the slow work with no lock held */ if (count) { flush_stack(stack, count, skb, count - 1); } else { if (!inner_flushed) UDP_INC_STATS_BH(net, UDP_MIB_IGNOREDMULTI, proto == IPPROTO_UDPLITE); consume_skb(skb); } return 0; } /* Initialize UDP checksum. If exited with zero value (success), * CHECKSUM_UNNECESSARY means, that no more checks are required. * Otherwise, csum completion requires chacksumming packet body, * including udp header and folding it to skb->csum. */ static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh, int proto) { int err; UDP_SKB_CB(skb)->partial_cov = 0; UDP_SKB_CB(skb)->cscov = skb->len; if (proto == IPPROTO_UDPLITE) { err = udplite_checksum_init(skb, uh); if (err) return err; } return skb_checksum_init_zero_check(skb, proto, uh->check, inet_compute_pseudo); } /* * All we need to do is get the socket, and then do a checksum. */ int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable, int proto) { struct sock *sk; struct udphdr *uh; unsigned short ulen; struct rtable *rt = skb_rtable(skb); __be32 saddr, daddr; struct net *net = dev_net(skb->dev); /* * Validate the packet. */ if (!pskb_may_pull(skb, sizeof(struct udphdr))) goto drop; /* No space for header. */ uh = udp_hdr(skb); ulen = ntohs(uh->len); saddr = ip_hdr(skb)->saddr; daddr = ip_hdr(skb)->daddr; if (ulen > skb->len) goto short_packet; if (proto == IPPROTO_UDP) { /* UDP validates ulen. */ if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen)) goto short_packet; uh = udp_hdr(skb); } if (udp4_csum_init(skb, uh, proto)) goto csum_error; sk = skb_steal_sock(skb); if (sk) { struct dst_entry *dst = skb_dst(skb); int ret; if (unlikely(sk->sk_rx_dst != dst)) udp_sk_rx_dst_set(sk, dst); ret = udp_queue_rcv_skb(sk, skb); sock_put(sk); /* a return value > 0 means to resubmit the input, but * it wants the return to be -protocol, or 0 */ if (ret > 0) return -ret; return 0; } if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST)) return __udp4_lib_mcast_deliver(net, skb, uh, saddr, daddr, udptable, proto); sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable); if (sk) { int ret; if (inet_get_convert_csum(sk) && uh->check && !IS_UDPLITE(sk)) skb_checksum_try_convert(skb, IPPROTO_UDP, uh->check, inet_compute_pseudo); ret = udp_queue_rcv_skb(sk, skb); sock_put(sk); /* a return value > 0 means to resubmit the input, but * it wants the return to be -protocol, or 0 */ if (ret > 0) return -ret; return 0; } if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) goto drop; nf_reset(skb); /* No socket. Drop packet silently, if checksum is wrong */ if (udp_lib_checksum_complete(skb)) goto csum_error; UDP_INC_STATS_BH(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE); icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0); /* * Hmm. We got an UDP packet to a port to which we * don't wanna listen. Ignore it. */ kfree_skb(skb); return 0; short_packet: net_dbg_ratelimited("UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n", proto == IPPROTO_UDPLITE ? "Lite" : "", &saddr, ntohs(uh->source), ulen, skb->len, &daddr, ntohs(uh->dest)); goto drop; csum_error: /* * RFC1122: OK. Discards the bad packet silently (as far as * the network is concerned, anyway) as per 4.1.3.4 (MUST). */ net_dbg_ratelimited("UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n", proto == IPPROTO_UDPLITE ? "Lite" : "", &saddr, ntohs(uh->source), &daddr, ntohs(uh->dest), ulen); UDP_INC_STATS_BH(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE); drop: UDP_INC_STATS_BH(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE); kfree_skb(skb); return 0; } /* We can only early demux multicast if there is a single matching socket. * If more than one socket found returns NULL */ static struct sock *__udp4_lib_mcast_demux_lookup(struct net *net, __be16 loc_port, __be32 loc_addr, __be16 rmt_port, __be32 rmt_addr, int dif) { struct sock *sk, *result; struct hlist_nulls_node *node; unsigned short hnum = ntohs(loc_port); unsigned int count, slot = udp_hashfn(net, hnum, udp_table.mask); struct udp_hslot *hslot = &udp_table.hash[slot]; /* Do not bother scanning a too big list */ if (hslot->count > 10) return NULL; rcu_read_lock(); begin: count = 0; result = NULL; sk_nulls_for_each_rcu(sk, node, &hslot->head) { if (__udp_is_mcast_sock(net, sk, loc_port, loc_addr, rmt_port, rmt_addr, dif, hnum)) { result = sk; ++count; } } /* * if the nulls value we got at the end of this lookup is * not the expected one, we must restart lookup. * We probably met an item that was moved to another chain. */ if (get_nulls_value(node) != slot) goto begin; if (result) { if (count != 1 || unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2))) result = NULL; else if (unlikely(!__udp_is_mcast_sock(net, result, loc_port, loc_addr, rmt_port, rmt_addr, dif, hnum))) { sock_put(result); result = NULL; } } rcu_read_unlock(); return result; } /* For unicast we should only early demux connected sockets or we can * break forwarding setups. The chains here can be long so only check * if the first socket is an exact match and if not move on. */ static struct sock *__udp4_lib_demux_lookup(struct net *net, __be16 loc_port, __be32 loc_addr, __be16 rmt_port, __be32 rmt_addr, int dif) { struct sock *sk, *result; struct hlist_nulls_node *node; unsigned short hnum = ntohs(loc_port); unsigned int hash2 = udp4_portaddr_hash(net, loc_addr, hnum); unsigned int slot2 = hash2 & udp_table.mask; struct udp_hslot *hslot2 = &udp_table.hash2[slot2]; INET_ADDR_COOKIE(acookie, rmt_addr, loc_addr); const __portpair ports = INET_COMBINED_PORTS(rmt_port, hnum); rcu_read_lock(); result = NULL; udp_portaddr_for_each_entry_rcu(sk, node, &hslot2->head) { if (INET_MATCH(sk, net, acookie, rmt_addr, loc_addr, ports, dif)) result = sk; /* Only check first socket in chain */ break; } if (result) { if (unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2))) result = NULL; else if (unlikely(!INET_MATCH(sk, net, acookie, rmt_addr, loc_addr, ports, dif))) { sock_put(result); result = NULL; } } rcu_read_unlock(); return result; } void udp_v4_early_demux(struct sk_buff *skb) { struct net *net = dev_net(skb->dev); const struct iphdr *iph; const struct udphdr *uh; struct sock *sk; struct dst_entry *dst; int dif = skb->dev->ifindex; /* validate the packet */ if (!pskb_may_pull(skb, skb_transport_offset(skb) + sizeof(struct udphdr))) return; iph = ip_hdr(skb); uh = udp_hdr(skb); if (skb->pkt_type == PACKET_BROADCAST || skb->pkt_type == PACKET_MULTICAST) sk = __udp4_lib_mcast_demux_lookup(net, uh->dest, iph->daddr, uh->source, iph->saddr, dif); else if (skb->pkt_type == PACKET_HOST) sk = __udp4_lib_demux_lookup(net, uh->dest, iph->daddr, uh->source, iph->saddr, dif); else return; if (!sk) return; skb->sk = sk; skb->destructor = sock_efree; dst = sk->sk_rx_dst; if (dst) dst = dst_check(dst, 0); if (dst) skb_dst_set_noref(skb, dst); } int udp_rcv(struct sk_buff *skb) { return __udp4_lib_rcv(skb, &udp_table, IPPROTO_UDP); } void udp_destroy_sock(struct sock *sk) { struct udp_sock *up = udp_sk(sk); bool slow = lock_sock_fast(sk); udp_flush_pending_frames(sk); unlock_sock_fast(sk, slow); if (static_key_false(&udp_encap_needed) && up->encap_type) { void (*encap_destroy)(struct sock *sk); encap_destroy = ACCESS_ONCE(up->encap_destroy); if (encap_destroy) encap_destroy(sk); } } /* * Socket option code for UDP */ int udp_lib_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen, int (*push_pending_frames)(struct sock *)) { struct udp_sock *up = udp_sk(sk); int val, valbool; int err = 0; int is_udplite = IS_UDPLITE(sk); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; valbool = val ? 1 : 0; switch (optname) { case UDP_CORK: if (val != 0) { up->corkflag = 1; } else { up->corkflag = 0; lock_sock(sk); push_pending_frames(sk); release_sock(sk); } break; case UDP_ENCAP: switch (val) { case 0: case UDP_ENCAP_ESPINUDP: case UDP_ENCAP_ESPINUDP_NON_IKE: up->encap_rcv = xfrm4_udp_encap_rcv; /* FALLTHROUGH */ case UDP_ENCAP_L2TPINUDP: up->encap_type = val; udp_encap_enable(); break; default: err = -ENOPROTOOPT; break; } break; case UDP_NO_CHECK6_TX: up->no_check6_tx = valbool; break; case UDP_NO_CHECK6_RX: up->no_check6_rx = valbool; break; /* * UDP-Lite's partial checksum coverage (RFC 3828). */ /* The sender sets actual checksum coverage length via this option. * The case coverage > packet length is handled by send module. */ case UDPLITE_SEND_CSCOV: if (!is_udplite) /* Disable the option on UDP sockets */ return -ENOPROTOOPT; if (val != 0 && val < 8) /* Illegal coverage: use default (8) */ val = 8; else if (val > USHRT_MAX) val = USHRT_MAX; up->pcslen = val; up->pcflag |= UDPLITE_SEND_CC; break; /* The receiver specifies a minimum checksum coverage value. To make * sense, this should be set to at least 8 (as done below). If zero is * used, this again means full checksum coverage. */ case UDPLITE_RECV_CSCOV: if (!is_udplite) /* Disable the option on UDP sockets */ return -ENOPROTOOPT; if (val != 0 && val < 8) /* Avoid silly minimal values. */ val = 8; else if (val > USHRT_MAX) val = USHRT_MAX; up->pcrlen = val; up->pcflag |= UDPLITE_RECV_CC; break; default: err = -ENOPROTOOPT; break; } return err; } EXPORT_SYMBOL(udp_lib_setsockopt); int udp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { if (level == SOL_UDP || level == SOL_UDPLITE) return udp_lib_setsockopt(sk, level, optname, optval, optlen, udp_push_pending_frames); return ip_setsockopt(sk, level, optname, optval, optlen); } #ifdef CONFIG_COMPAT int compat_udp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { if (level == SOL_UDP || level == SOL_UDPLITE) return udp_lib_setsockopt(sk, level, optname, optval, optlen, udp_push_pending_frames); return compat_ip_setsockopt(sk, level, optname, optval, optlen); } #endif int udp_lib_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { struct udp_sock *up = udp_sk(sk); int val, len; if (get_user(len, optlen)) return -EFAULT; len = min_t(unsigned int, len, sizeof(int)); if (len < 0) return -EINVAL; switch (optname) { case UDP_CORK: val = up->corkflag; break; case UDP_ENCAP: val = up->encap_type; break; case UDP_NO_CHECK6_TX: val = up->no_check6_tx; break; case UDP_NO_CHECK6_RX: val = up->no_check6_rx; break; /* The following two cannot be changed on UDP sockets, the return is * always 0 (which corresponds to the full checksum coverage of UDP). */ case UDPLITE_SEND_CSCOV: val = up->pcslen; break; case UDPLITE_RECV_CSCOV: val = up->pcrlen; break; default: return -ENOPROTOOPT; } if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; return 0; } EXPORT_SYMBOL(udp_lib_getsockopt); int udp_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { if (level == SOL_UDP || level == SOL_UDPLITE) return udp_lib_getsockopt(sk, level, optname, optval, optlen); return ip_getsockopt(sk, level, optname, optval, optlen); } #ifdef CONFIG_COMPAT int compat_udp_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { if (level == SOL_UDP || level == SOL_UDPLITE) return udp_lib_getsockopt(sk, level, optname, optval, optlen); return compat_ip_getsockopt(sk, level, optname, optval, optlen); } #endif /** * udp_poll - wait for a UDP event. * @file - file struct * @sock - socket * @wait - poll table * * This is same as datagram poll, except for the special case of * blocking sockets. If application is using a blocking fd * and a packet with checksum error is in the queue; * then it could get return from select indicating data available * but then block when reading it. Add special case code * to work around these arguably broken applications. */ unsigned int udp_poll(struct file *file, struct socket *sock, poll_table *wait) { unsigned int mask = datagram_poll(file, sock, wait); struct sock *sk = sock->sk; sock_rps_record_flow(sk); /* Check for false positives due to checksum errors */ if ((mask & POLLRDNORM) && !(file->f_flags & O_NONBLOCK) && !(sk->sk_shutdown & RCV_SHUTDOWN) && !first_packet_length(sk)) mask &= ~(POLLIN | POLLRDNORM); return mask; } EXPORT_SYMBOL(udp_poll); struct proto udp_prot = { .name = "UDP", .owner = THIS_MODULE, .close = udp_lib_close, .connect = ip4_datagram_connect, .disconnect = udp_disconnect, .ioctl = udp_ioctl, .destroy = udp_destroy_sock, .setsockopt = udp_setsockopt, .getsockopt = udp_getsockopt, .sendmsg = udp_sendmsg, .recvmsg = udp_recvmsg, .sendpage = udp_sendpage, .backlog_rcv = __udp_queue_rcv_skb, .release_cb = ip4_datagram_release_cb, .hash = udp_lib_hash, .unhash = udp_lib_unhash, .rehash = udp_v4_rehash, .get_port = udp_v4_get_port, .memory_allocated = &udp_memory_allocated, .sysctl_mem = sysctl_udp_mem, .sysctl_wmem = &sysctl_udp_wmem_min, .sysctl_rmem = &sysctl_udp_rmem_min, .obj_size = sizeof(struct udp_sock), .slab_flags = SLAB_DESTROY_BY_RCU, .h.udp_table = &udp_table, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_udp_setsockopt, .compat_getsockopt = compat_udp_getsockopt, #endif .clear_sk = sk_prot_clear_portaddr_nulls, }; EXPORT_SYMBOL(udp_prot); /* ------------------------------------------------------------------------ */ #ifdef CONFIG_PROC_FS static struct sock *udp_get_first(struct seq_file *seq, int start) { struct sock *sk; struct udp_iter_state *state = seq->private; struct net *net = seq_file_net(seq); for (state->bucket = start; state->bucket <= state->udp_table->mask; ++state->bucket) { struct hlist_nulls_node *node; struct udp_hslot *hslot = &state->udp_table->hash[state->bucket]; if (hlist_nulls_empty(&hslot->head)) continue; spin_lock_bh(&hslot->lock); sk_nulls_for_each(sk, node, &hslot->head) { if (!net_eq(sock_net(sk), net)) continue; if (sk->sk_family == state->family) goto found; } spin_unlock_bh(&hslot->lock); } sk = NULL; found: return sk; } static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk) { struct udp_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) || sk->sk_family != state->family)); if (!sk) { if (state->bucket <= state->udp_table->mask) spin_unlock_bh(&state->udp_table->hash[state->bucket].lock); return udp_get_first(seq, state->bucket + 1); } return sk; } static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos) { struct sock *sk = udp_get_first(seq, 0); if (sk) while (pos && (sk = udp_get_next(seq, sk)) != NULL) --pos; return pos ? NULL : sk; } static void *udp_seq_start(struct seq_file *seq, loff_t *pos) { struct udp_iter_state *state = seq->private; state->bucket = MAX_UDP_PORTS; return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN; } static void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos) { struct sock *sk; if (v == SEQ_START_TOKEN) sk = udp_get_idx(seq, 0); else sk = udp_get_next(seq, v); ++*pos; return sk; } static void udp_seq_stop(struct seq_file *seq, void *v) { struct udp_iter_state *state = seq->private; if (state->bucket <= state->udp_table->mask) spin_unlock_bh(&state->udp_table->hash[state->bucket].lock); } int udp_seq_open(struct inode *inode, struct file *file) { struct udp_seq_afinfo *afinfo = PDE_DATA(inode); struct udp_iter_state *s; int err; err = seq_open_net(inode, file, &afinfo->seq_ops, sizeof(struct udp_iter_state)); if (err < 0) return err; s = ((struct seq_file *)file->private_data)->private; s->family = afinfo->family; s->udp_table = afinfo->udp_table; return err; } EXPORT_SYMBOL(udp_seq_open); /* ------------------------------------------------------------------------ */ int udp_proc_register(struct net *net, struct udp_seq_afinfo *afinfo) { struct proc_dir_entry *p; int rc = 0; afinfo->seq_ops.start = udp_seq_start; afinfo->seq_ops.next = udp_seq_next; afinfo->seq_ops.stop = udp_seq_stop; p = proc_create_data(afinfo->name, S_IRUGO, net->proc_net, afinfo->seq_fops, afinfo); if (!p) rc = -ENOMEM; return rc; } EXPORT_SYMBOL(udp_proc_register); void udp_proc_unregister(struct net *net, struct udp_seq_afinfo *afinfo) { remove_proc_entry(afinfo->name, net->proc_net); } EXPORT_SYMBOL(udp_proc_unregister); /* ------------------------------------------------------------------------ */ static void udp4_format_sock(struct sock *sp, struct seq_file *f, int bucket) { 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", 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)); } int udp4_seq_show(struct seq_file *seq, void *v) { seq_setwidth(seq, 127); if (v == SEQ_START_TOKEN) seq_puts(seq, " sl local_address rem_address st tx_queue " "rx_queue tr tm->when retrnsmt uid timeout " "inode ref pointer drops"); else { struct udp_iter_state *state = seq->private; udp4_format_sock(v, seq, state->bucket); } seq_pad(seq, '\n'); return 0; } static const struct file_operations udp_afinfo_seq_fops = { .owner = THIS_MODULE, .open = udp_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net }; /* ------------------------------------------------------------------------ */ static struct udp_seq_afinfo udp4_seq_afinfo = { .name = "udp", .family = AF_INET, .udp_table = &udp_table, .seq_fops = &udp_afinfo_seq_fops, .seq_ops = { .show = udp4_seq_show, }, }; static int __net_init udp4_proc_init_net(struct net *net) { return udp_proc_register(net, &udp4_seq_afinfo); } static void __net_exit udp4_proc_exit_net(struct net *net) { udp_proc_unregister(net, &udp4_seq_afinfo); } static struct pernet_operations udp4_net_ops = { .init = udp4_proc_init_net, .exit = udp4_proc_exit_net, }; int __init udp4_proc_init(void) { return register_pernet_subsys(&udp4_net_ops); } void udp4_proc_exit(void) { unregister_pernet_subsys(&udp4_net_ops); } #endif /* CONFIG_PROC_FS */ static __initdata unsigned long uhash_entries; static int __init set_uhash_entries(char *str) { ssize_t ret; if (!str) return 0; ret = kstrtoul(str, 0, &uhash_entries); if (ret) return 0; if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN) uhash_entries = UDP_HTABLE_SIZE_MIN; return 1; } __setup("uhash_entries=", set_uhash_entries); void __init udp_table_init(struct udp_table *table, const char *name) { unsigned int i; table->hash = alloc_large_system_hash(name, 2 * sizeof(struct udp_hslot), uhash_entries, 21, /* one slot per 2 MB */ 0, &table->log, &table->mask, UDP_HTABLE_SIZE_MIN, 64 * 1024); table->hash2 = table->hash + (table->mask + 1); for (i = 0; i <= table->mask; i++) { INIT_HLIST_NULLS_HEAD(&table->hash[i].head, i); table->hash[i].count = 0; spin_lock_init(&table->hash[i].lock); } for (i = 0; i <= table->mask; i++) { INIT_HLIST_NULLS_HEAD(&table->hash2[i].head, i); table->hash2[i].count = 0; spin_lock_init(&table->hash2[i].lock); } } u32 udp_flow_hashrnd(void) { static u32 hashrnd __read_mostly; net_get_random_once(&hashrnd, sizeof(hashrnd)); return hashrnd; } EXPORT_SYMBOL(udp_flow_hashrnd); void __init udp_init(void) { unsigned long limit; udp_table_init(&udp_table, "UDP"); limit = nr_free_buffer_pages() / 8; limit = max(limit, 128UL); sysctl_udp_mem[0] = limit / 4 * 3; sysctl_udp_mem[1] = limit; sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2; sysctl_udp_rmem_min = SK_MEM_QUANTUM; sysctl_udp_wmem_min = SK_MEM_QUANTUM; }
./CrossVul/dataset_final_sorted/CWE-399/c/good_1677_0
crossvul-cpp_data_good_4815_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC AAA PPPP TTTTT IIIII OOO N N % % C A A P P T I O O NN N % % C AAAAA PPPP T I O O N N N % % C A A P T I O O N NN % % CCCC A A P T IIIII OOO N N % % % % % % Read Text Caption. % % % % Software Design % % Cristy % % February 2002 % % % % % % 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/annotate.h" #include "magick/artifact.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/composite-private.h" #include "magick/draw.h" #include "magick/draw-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/module.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/string-private.h" #include "magick/utility.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d C A P T I O N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadCAPTIONImage() reads a CAPTION 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 ReadCAPTIONImage method is: % % Image *ReadCAPTIONImage(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 *ReadCAPTIONImage(const ImageInfo *image_info, ExceptionInfo *exception) { char *caption, geometry[MaxTextExtent], *property, *text; const char *gravity, *option; DrawInfo *draw_info; Image *image; MagickBooleanType split, status; register ssize_t i; size_t height, width; TypeMetric metrics; /* Initialize Image structure. */ 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); (void) ResetImagePage(image,"0x0+0+0"); /* Format caption. */ option=GetImageOption(image_info,"filename"); if (option == (const char *) NULL) property=InterpretImageProperties(image_info,image,image_info->filename); else if (LocaleNCompare(option,"caption:",8) == 0) property=InterpretImageProperties(image_info,image,option+8); else property=InterpretImageProperties(image_info,image,option); (void) SetImageProperty(image,"caption",property); property=DestroyString(property); caption=ConstantString(GetImageProperty(image,"caption")); draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); (void) CloneString(&draw_info->text,caption); gravity=GetImageOption(image_info,"gravity"); if (gravity != (char *) NULL) draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions, MagickFalse,gravity); split=MagickFalse; status=MagickTrue; if (image->columns == 0) { text=AcquireString(caption); i=FormatMagickCaption(image,draw_info,split,&metrics,&text); (void) CloneString(&draw_info->text,text); text=DestroyString(text); (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); status=GetMultilineTypeMetrics(image,draw_info,&metrics); width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); image->columns=width; } if (image->rows == 0) { split=MagickTrue; text=AcquireString(caption); i=FormatMagickCaption(image,draw_info,split,&metrics,&text); (void) CloneString(&draw_info->text,text); text=DestroyString(text); (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); status=GetMultilineTypeMetrics(image,draw_info,&metrics); image->rows=(size_t) ((i+1)*(metrics.ascent-metrics.descent+ draw_info->interline_spacing+draw_info->stroke_width)+0.5); } if (status != MagickFalse) status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { draw_info=DestroyDrawInfo(draw_info); InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (SetImageBackgroundColor(image) == MagickFalse) { draw_info=DestroyDrawInfo(draw_info); InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } if ((fabs(image_info->pointsize) < MagickEpsilon) && (strlen(caption) > 0)) { double high, low; /* Auto fit text into bounding box. */ for ( ; ; draw_info->pointsize*=2.0) { text=AcquireString(caption); i=FormatMagickCaption(image,draw_info,split,&metrics,&text); (void) CloneString(&draw_info->text,text); text=DestroyString(text); (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); status=GetMultilineTypeMetrics(image,draw_info,&metrics); (void) status; width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); if ((image->columns != 0) && (image->rows != 0)) { if ((width >= image->columns) && (height >= image->rows)) break; } else if (((image->columns != 0) && (width >= image->columns)) || ((image->rows != 0) && (height >= image->rows))) break; } high=draw_info->pointsize; for (low=1.0; (high-low) > 0.5; ) { draw_info->pointsize=(low+high)/2.0; text=AcquireString(caption); i=FormatMagickCaption(image,draw_info,split,&metrics,&text); (void) CloneString(&draw_info->text,text); text=DestroyString(text); (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g", -metrics.bounds.x1,metrics.ascent); if (draw_info->gravity == UndefinedGravity) (void) CloneString(&draw_info->geometry,geometry); (void) GetMultilineTypeMetrics(image,draw_info,&metrics); width=(size_t) floor(metrics.width+draw_info->stroke_width+0.5); height=(size_t) floor(metrics.height+draw_info->stroke_width+0.5); if ((image->columns != 0) && (image->rows != 0)) { if ((width < image->columns) && (height < image->rows)) low=draw_info->pointsize+0.5; else high=draw_info->pointsize-0.5; } else if (((image->columns != 0) && (width < image->columns)) || ((image->rows != 0) && (height < image->rows))) low=draw_info->pointsize+0.5; else high=draw_info->pointsize-0.5; } draw_info->pointsize=floor((low+high)/2.0-0.5); } /* Draw caption. */ i=FormatMagickCaption(image,draw_info,split,&metrics,&caption); (void) CloneString(&draw_info->text,caption); (void) FormatLocaleString(geometry,MaxTextExtent,"%+g%+g",MagickMax( draw_info->direction == RightToLeftDirection ? image->columns- metrics.bounds.x2 : -metrics.bounds.x1,0.0),draw_info->gravity == UndefinedGravity ? metrics.ascent : 0.0); (void) CloneString(&draw_info->geometry,geometry); status=AnnotateImage(image,draw_info); if (image_info->pointsize == 0.0) { char pointsize[MaxTextExtent]; (void) FormatLocaleString(pointsize,MaxTextExtent,"%.20g", draw_info->pointsize); (void) SetImageProperty(image,"caption:pointsize",pointsize); } draw_info=DestroyDrawInfo(draw_info); caption=DestroyString(caption); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r C A P T I O N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterCAPTIONImage() adds attributes for the CAPTION 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 RegisterCAPTIONImage method is: % % size_t RegisterCAPTIONImage(void) % */ ModuleExport size_t RegisterCAPTIONImage(void) { MagickInfo *entry; entry=SetMagickInfo("CAPTION"); entry->decoder=(DecodeImageHandler *) ReadCAPTIONImage; entry->description=ConstantString("Caption"); entry->adjoin=MagickFalse; entry->module=ConstantString("CAPTION"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r C A P T I O N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterCAPTIONImage() removes format registrations made by the % CAPTION module from the list of supported formats. % % The format of the UnregisterCAPTIONImage method is: % % UnregisterCAPTIONImage(void) % */ ModuleExport void UnregisterCAPTIONImage(void) { (void) UnregisterMagickInfo("CAPTION"); }
./CrossVul/dataset_final_sorted/CWE-399/c/good_4815_1
crossvul-cpp_data_good_4966_2
/* scm.c - Socket level control messages processing. * * Author: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru> * Alignment and value checking mods by Craig Metz * * 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/signal.h> #include <linux/capability.h> #include <linux/errno.h> #include <linux/sched.h> #include <linux/mm.h> #include <linux/kernel.h> #include <linux/stat.h> #include <linux/socket.h> #include <linux/file.h> #include <linux/fcntl.h> #include <linux/net.h> #include <linux/interrupt.h> #include <linux/netdevice.h> #include <linux/security.h> #include <linux/pid_namespace.h> #include <linux/pid.h> #include <linux/nsproxy.h> #include <linux/slab.h> #include <asm/uaccess.h> #include <net/protocol.h> #include <linux/skbuff.h> #include <net/sock.h> #include <net/compat.h> #include <net/scm.h> #include <net/cls_cgroup.h> /* * Only allow a user to send credentials, that they could set with * setu(g)id. */ static __inline__ int scm_check_creds(struct ucred *creds) { const struct cred *cred = current_cred(); kuid_t uid = make_kuid(cred->user_ns, creds->uid); kgid_t gid = make_kgid(cred->user_ns, creds->gid); if (!uid_valid(uid) || !gid_valid(gid)) return -EINVAL; if ((creds->pid == task_tgid_vnr(current) || ns_capable(task_active_pid_ns(current)->user_ns, CAP_SYS_ADMIN)) && ((uid_eq(uid, cred->uid) || uid_eq(uid, cred->euid) || uid_eq(uid, cred->suid)) || ns_capable(cred->user_ns, CAP_SETUID)) && ((gid_eq(gid, cred->gid) || gid_eq(gid, cred->egid) || gid_eq(gid, cred->sgid)) || ns_capable(cred->user_ns, CAP_SETGID))) { return 0; } return -EPERM; } static int scm_fp_copy(struct cmsghdr *cmsg, struct scm_fp_list **fplp) { int *fdp = (int*)CMSG_DATA(cmsg); struct scm_fp_list *fpl = *fplp; struct file **fpp; int i, num; num = (cmsg->cmsg_len - CMSG_ALIGN(sizeof(struct cmsghdr)))/sizeof(int); if (num <= 0) return 0; if (num > SCM_MAX_FD) return -EINVAL; if (!fpl) { fpl = kmalloc(sizeof(struct scm_fp_list), GFP_KERNEL); if (!fpl) return -ENOMEM; *fplp = fpl; fpl->count = 0; fpl->max = SCM_MAX_FD; fpl->user = NULL; } fpp = &fpl->fp[fpl->count]; if (fpl->count + num > fpl->max) return -EINVAL; /* * Verify the descriptors and increment the usage count. */ for (i=0; i< num; i++) { int fd = fdp[i]; struct file *file; if (fd < 0 || !(file = fget_raw(fd))) return -EBADF; *fpp++ = file; fpl->count++; } if (!fpl->user) fpl->user = get_uid(current_user()); return num; } void __scm_destroy(struct scm_cookie *scm) { struct scm_fp_list *fpl = scm->fp; int i; if (fpl) { scm->fp = NULL; for (i=fpl->count-1; i>=0; i--) fput(fpl->fp[i]); free_uid(fpl->user); kfree(fpl); } } EXPORT_SYMBOL(__scm_destroy); int __scm_send(struct socket *sock, struct msghdr *msg, struct scm_cookie *p) { struct cmsghdr *cmsg; int err; for_each_cmsghdr(cmsg, msg) { err = -EINVAL; /* Verify that cmsg_len is at least sizeof(struct cmsghdr) */ /* The first check was omitted in <= 2.2.5. The reasoning was that parser checks cmsg_len in any case, so that additional check would be work duplication. But if cmsg_level is not SOL_SOCKET, we do not check for too short ancillary data object at all! Oops. OK, let's add it... */ if (!CMSG_OK(msg, cmsg)) goto error; if (cmsg->cmsg_level != SOL_SOCKET) continue; switch (cmsg->cmsg_type) { case SCM_RIGHTS: if (!sock->ops || sock->ops->family != PF_UNIX) goto error; err=scm_fp_copy(cmsg, &p->fp); if (err<0) goto error; break; case SCM_CREDENTIALS: { struct ucred creds; kuid_t uid; kgid_t gid; if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct ucred))) goto error; memcpy(&creds, CMSG_DATA(cmsg), sizeof(struct ucred)); err = scm_check_creds(&creds); if (err) goto error; p->creds.pid = creds.pid; if (!p->pid || pid_vnr(p->pid) != creds.pid) { struct pid *pid; err = -ESRCH; pid = find_get_pid(creds.pid); if (!pid) goto error; put_pid(p->pid); p->pid = pid; } err = -EINVAL; uid = make_kuid(current_user_ns(), creds.uid); gid = make_kgid(current_user_ns(), creds.gid); if (!uid_valid(uid) || !gid_valid(gid)) goto error; p->creds.uid = uid; p->creds.gid = gid; break; } default: goto error; } } if (p->fp && !p->fp->count) { kfree(p->fp); p->fp = NULL; } return 0; error: scm_destroy(p); return err; } EXPORT_SYMBOL(__scm_send); int put_cmsg(struct msghdr * msg, int level, int type, int len, void *data) { struct cmsghdr __user *cm = (__force struct cmsghdr __user *)msg->msg_control; struct cmsghdr cmhdr; int cmlen = CMSG_LEN(len); int err; if (MSG_CMSG_COMPAT & msg->msg_flags) return put_cmsg_compat(msg, level, type, len, data); if (cm==NULL || msg->msg_controllen < sizeof(*cm)) { msg->msg_flags |= MSG_CTRUNC; return 0; /* XXX: return error? check spec. */ } if (msg->msg_controllen < cmlen) { msg->msg_flags |= MSG_CTRUNC; cmlen = msg->msg_controllen; } cmhdr.cmsg_level = level; cmhdr.cmsg_type = type; cmhdr.cmsg_len = cmlen; err = -EFAULT; if (copy_to_user(cm, &cmhdr, sizeof cmhdr)) goto out; if (copy_to_user(CMSG_DATA(cm), data, cmlen - sizeof(struct cmsghdr))) goto out; cmlen = CMSG_SPACE(len); if (msg->msg_controllen < cmlen) cmlen = msg->msg_controllen; msg->msg_control += cmlen; msg->msg_controllen -= cmlen; err = 0; out: return err; } EXPORT_SYMBOL(put_cmsg); void scm_detach_fds(struct msghdr *msg, struct scm_cookie *scm) { struct cmsghdr __user *cm = (__force struct cmsghdr __user*)msg->msg_control; int fdmax = 0; int fdnum = scm->fp->count; struct file **fp = scm->fp->fp; int __user *cmfptr; int err = 0, i; if (MSG_CMSG_COMPAT & msg->msg_flags) { scm_detach_fds_compat(msg, scm); return; } if (msg->msg_controllen > sizeof(struct cmsghdr)) fdmax = ((msg->msg_controllen - sizeof(struct cmsghdr)) / sizeof(int)); if (fdnum < fdmax) fdmax = fdnum; for (i=0, cmfptr=(__force int __user *)CMSG_DATA(cm); i<fdmax; i++, cmfptr++) { struct socket *sock; int new_fd; err = security_file_receive(fp[i]); if (err) break; err = get_unused_fd_flags(MSG_CMSG_CLOEXEC & msg->msg_flags ? O_CLOEXEC : 0); if (err < 0) break; new_fd = err; err = put_user(new_fd, cmfptr); if (err) { put_unused_fd(new_fd); break; } /* Bump the usage count and install the file. */ sock = sock_from_file(fp[i], &err); if (sock) { sock_update_netprioidx(&sock->sk->sk_cgrp_data); sock_update_classid(&sock->sk->sk_cgrp_data); } fd_install(new_fd, get_file(fp[i])); } if (i > 0) { int cmlen = CMSG_LEN(i*sizeof(int)); err = put_user(SOL_SOCKET, &cm->cmsg_level); if (!err) err = put_user(SCM_RIGHTS, &cm->cmsg_type); if (!err) err = put_user(cmlen, &cm->cmsg_len); if (!err) { cmlen = CMSG_SPACE(i*sizeof(int)); if (msg->msg_controllen < cmlen) cmlen = msg->msg_controllen; msg->msg_control += cmlen; msg->msg_controllen -= cmlen; } } if (i < fdnum || (fdnum && fdmax <= 0)) msg->msg_flags |= MSG_CTRUNC; /* * All of the files that fit in the message have had their * usage counts incremented, so we just free the list. */ __scm_destroy(scm); } EXPORT_SYMBOL(scm_detach_fds); struct scm_fp_list *scm_fp_dup(struct scm_fp_list *fpl) { struct scm_fp_list *new_fpl; int i; if (!fpl) return NULL; new_fpl = kmemdup(fpl, offsetof(struct scm_fp_list, fp[fpl->count]), GFP_KERNEL); if (new_fpl) { for (i = 0; i < fpl->count; i++) get_file(fpl->fp[i]); new_fpl->max = new_fpl->count; new_fpl->user = get_uid(fpl->user); } return new_fpl; } EXPORT_SYMBOL(scm_fp_dup);
./CrossVul/dataset_final_sorted/CWE-399/c/good_4966_2
crossvul-cpp_data_good_3622_0
/* * kvm_ia64.c: Basic KVM suppport On Itanium series processors * * * Copyright (C) 2007, Intel Corporation. * Xiantao Zhang (xiantao.zhang@intel.com) * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 59 Temple * Place - Suite 330, Boston, MA 02111-1307 USA. * */ #include <linux/module.h> #include <linux/errno.h> #include <linux/percpu.h> #include <linux/fs.h> #include <linux/slab.h> #include <linux/smp.h> #include <linux/kvm_host.h> #include <linux/kvm.h> #include <linux/bitops.h> #include <linux/hrtimer.h> #include <linux/uaccess.h> #include <linux/iommu.h> #include <linux/intel-iommu.h> #include <linux/pci.h> #include <asm/pgtable.h> #include <asm/gcc_intrin.h> #include <asm/pal.h> #include <asm/cacheflush.h> #include <asm/div64.h> #include <asm/tlb.h> #include <asm/elf.h> #include <asm/sn/addrs.h> #include <asm/sn/clksupport.h> #include <asm/sn/shub_mmr.h> #include "misc.h" #include "vti.h" #include "iodev.h" #include "ioapic.h" #include "lapic.h" #include "irq.h" static unsigned long kvm_vmm_base; static unsigned long kvm_vsa_base; static unsigned long kvm_vm_buffer; static unsigned long kvm_vm_buffer_size; unsigned long kvm_vmm_gp; static long vp_env_info; static struct kvm_vmm_info *kvm_vmm_info; static DEFINE_PER_CPU(struct kvm_vcpu *, last_vcpu); struct kvm_stats_debugfs_item debugfs_entries[] = { { NULL } }; static unsigned long kvm_get_itc(struct kvm_vcpu *vcpu) { #if defined(CONFIG_IA64_SGI_SN2) || defined(CONFIG_IA64_GENERIC) if (vcpu->kvm->arch.is_sn2) return rtc_time(); else #endif return ia64_getreg(_IA64_REG_AR_ITC); } static void kvm_flush_icache(unsigned long start, unsigned long len) { int l; for (l = 0; l < (len + 32); l += 32) ia64_fc((void *)(start + l)); ia64_sync_i(); ia64_srlz_i(); } static void kvm_flush_tlb_all(void) { unsigned long i, j, count0, count1, stride0, stride1, addr; long flags; addr = local_cpu_data->ptce_base; count0 = local_cpu_data->ptce_count[0]; count1 = local_cpu_data->ptce_count[1]; stride0 = local_cpu_data->ptce_stride[0]; stride1 = local_cpu_data->ptce_stride[1]; local_irq_save(flags); for (i = 0; i < count0; ++i) { for (j = 0; j < count1; ++j) { ia64_ptce(addr); addr += stride1; } addr += stride0; } local_irq_restore(flags); ia64_srlz_i(); /* srlz.i implies srlz.d */ } long ia64_pal_vp_create(u64 *vpd, u64 *host_iva, u64 *opt_handler) { struct ia64_pal_retval iprv; PAL_CALL_STK(iprv, PAL_VP_CREATE, (u64)vpd, (u64)host_iva, (u64)opt_handler); return iprv.status; } static DEFINE_SPINLOCK(vp_lock); int kvm_arch_hardware_enable(void *garbage) { long status; long tmp_base; unsigned long pte; unsigned long saved_psr; int slot; pte = pte_val(mk_pte_phys(__pa(kvm_vmm_base), PAGE_KERNEL)); local_irq_save(saved_psr); slot = ia64_itr_entry(0x3, KVM_VMM_BASE, pte, KVM_VMM_SHIFT); local_irq_restore(saved_psr); if (slot < 0) return -EINVAL; spin_lock(&vp_lock); status = ia64_pal_vp_init_env(kvm_vsa_base ? VP_INIT_ENV : VP_INIT_ENV_INITALIZE, __pa(kvm_vm_buffer), KVM_VM_BUFFER_BASE, &tmp_base); if (status != 0) { spin_unlock(&vp_lock); printk(KERN_WARNING"kvm: Failed to Enable VT Support!!!!\n"); return -EINVAL; } if (!kvm_vsa_base) { kvm_vsa_base = tmp_base; printk(KERN_INFO"kvm: kvm_vsa_base:0x%lx\n", kvm_vsa_base); } spin_unlock(&vp_lock); ia64_ptr_entry(0x3, slot); return 0; } void kvm_arch_hardware_disable(void *garbage) { long status; int slot; unsigned long pte; unsigned long saved_psr; unsigned long host_iva = ia64_getreg(_IA64_REG_CR_IVA); pte = pte_val(mk_pte_phys(__pa(kvm_vmm_base), PAGE_KERNEL)); local_irq_save(saved_psr); slot = ia64_itr_entry(0x3, KVM_VMM_BASE, pte, KVM_VMM_SHIFT); local_irq_restore(saved_psr); if (slot < 0) return; status = ia64_pal_vp_exit_env(host_iva); if (status) printk(KERN_DEBUG"kvm: Failed to disable VT support! :%ld\n", status); ia64_ptr_entry(0x3, slot); } void kvm_arch_check_processor_compat(void *rtn) { *(int *)rtn = 0; } int kvm_dev_ioctl_check_extension(long ext) { int r; switch (ext) { case KVM_CAP_IRQCHIP: case KVM_CAP_MP_STATE: case KVM_CAP_IRQ_INJECT_STATUS: r = 1; break; case KVM_CAP_COALESCED_MMIO: r = KVM_COALESCED_MMIO_PAGE_OFFSET; break; case KVM_CAP_IOMMU: r = iommu_present(&pci_bus_type); break; default: r = 0; } return r; } static int handle_vm_error(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run) { kvm_run->exit_reason = KVM_EXIT_UNKNOWN; kvm_run->hw.hardware_exit_reason = 1; return 0; } static int handle_mmio(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run) { struct kvm_mmio_req *p; struct kvm_io_device *mmio_dev; int r; p = kvm_get_vcpu_ioreq(vcpu); if ((p->addr & PAGE_MASK) == IOAPIC_DEFAULT_BASE_ADDRESS) goto mmio; vcpu->mmio_needed = 1; vcpu->mmio_phys_addr = kvm_run->mmio.phys_addr = p->addr; vcpu->mmio_size = kvm_run->mmio.len = p->size; vcpu->mmio_is_write = kvm_run->mmio.is_write = !p->dir; if (vcpu->mmio_is_write) memcpy(vcpu->mmio_data, &p->data, p->size); memcpy(kvm_run->mmio.data, &p->data, p->size); kvm_run->exit_reason = KVM_EXIT_MMIO; return 0; mmio: if (p->dir) r = kvm_io_bus_read(vcpu->kvm, KVM_MMIO_BUS, p->addr, p->size, &p->data); else r = kvm_io_bus_write(vcpu->kvm, KVM_MMIO_BUS, p->addr, p->size, &p->data); if (r) printk(KERN_ERR"kvm: No iodevice found! addr:%lx\n", p->addr); p->state = STATE_IORESP_READY; return 1; } static int handle_pal_call(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run) { struct exit_ctl_data *p; p = kvm_get_exit_data(vcpu); if (p->exit_reason == EXIT_REASON_PAL_CALL) return kvm_pal_emul(vcpu, kvm_run); else { kvm_run->exit_reason = KVM_EXIT_UNKNOWN; kvm_run->hw.hardware_exit_reason = 2; return 0; } } static int handle_sal_call(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run) { struct exit_ctl_data *p; p = kvm_get_exit_data(vcpu); if (p->exit_reason == EXIT_REASON_SAL_CALL) { kvm_sal_emul(vcpu); return 1; } else { kvm_run->exit_reason = KVM_EXIT_UNKNOWN; kvm_run->hw.hardware_exit_reason = 3; return 0; } } static int __apic_accept_irq(struct kvm_vcpu *vcpu, uint64_t vector) { struct vpd *vpd = to_host(vcpu->kvm, vcpu->arch.vpd); if (!test_and_set_bit(vector, &vpd->irr[0])) { vcpu->arch.irq_new_pending = 1; kvm_vcpu_kick(vcpu); return 1; } return 0; } /* * offset: address offset to IPI space. * value: deliver value. */ static void vcpu_deliver_ipi(struct kvm_vcpu *vcpu, uint64_t dm, uint64_t vector) { switch (dm) { case SAPIC_FIXED: break; case SAPIC_NMI: vector = 2; break; case SAPIC_EXTINT: vector = 0; break; case SAPIC_INIT: case SAPIC_PMI: default: printk(KERN_ERR"kvm: Unimplemented Deliver reserved IPI!\n"); return; } __apic_accept_irq(vcpu, vector); } static struct kvm_vcpu *lid_to_vcpu(struct kvm *kvm, unsigned long id, unsigned long eid) { union ia64_lid lid; int i; struct kvm_vcpu *vcpu; kvm_for_each_vcpu(i, vcpu, kvm) { lid.val = VCPU_LID(vcpu); if (lid.id == id && lid.eid == eid) return vcpu; } return NULL; } static int handle_ipi(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run) { struct exit_ctl_data *p = kvm_get_exit_data(vcpu); struct kvm_vcpu *target_vcpu; struct kvm_pt_regs *regs; union ia64_ipi_a addr = p->u.ipi_data.addr; union ia64_ipi_d data = p->u.ipi_data.data; target_vcpu = lid_to_vcpu(vcpu->kvm, addr.id, addr.eid); if (!target_vcpu) return handle_vm_error(vcpu, kvm_run); if (!target_vcpu->arch.launched) { regs = vcpu_regs(target_vcpu); regs->cr_iip = vcpu->kvm->arch.rdv_sal_data.boot_ip; regs->r1 = vcpu->kvm->arch.rdv_sal_data.boot_gp; target_vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE; if (waitqueue_active(&target_vcpu->wq)) wake_up_interruptible(&target_vcpu->wq); } else { vcpu_deliver_ipi(target_vcpu, data.dm, data.vector); if (target_vcpu != vcpu) kvm_vcpu_kick(target_vcpu); } return 1; } struct call_data { struct kvm_ptc_g ptc_g_data; struct kvm_vcpu *vcpu; }; static void vcpu_global_purge(void *info) { struct call_data *p = (struct call_data *)info; struct kvm_vcpu *vcpu = p->vcpu; if (test_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests)) return; set_bit(KVM_REQ_PTC_G, &vcpu->requests); if (vcpu->arch.ptc_g_count < MAX_PTC_G_NUM) { vcpu->arch.ptc_g_data[vcpu->arch.ptc_g_count++] = p->ptc_g_data; } else { clear_bit(KVM_REQ_PTC_G, &vcpu->requests); vcpu->arch.ptc_g_count = 0; set_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests); } } static int handle_global_purge(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run) { struct exit_ctl_data *p = kvm_get_exit_data(vcpu); struct kvm *kvm = vcpu->kvm; struct call_data call_data; int i; struct kvm_vcpu *vcpui; call_data.ptc_g_data = p->u.ptc_g_data; kvm_for_each_vcpu(i, vcpui, kvm) { if (vcpui->arch.mp_state == KVM_MP_STATE_UNINITIALIZED || vcpu == vcpui) continue; if (waitqueue_active(&vcpui->wq)) wake_up_interruptible(&vcpui->wq); if (vcpui->cpu != -1) { call_data.vcpu = vcpui; smp_call_function_single(vcpui->cpu, vcpu_global_purge, &call_data, 1); } else printk(KERN_WARNING"kvm: Uninit vcpu received ipi!\n"); } return 1; } static int handle_switch_rr6(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run) { return 1; } static int kvm_sn2_setup_mappings(struct kvm_vcpu *vcpu) { unsigned long pte, rtc_phys_addr, map_addr; int slot; map_addr = KVM_VMM_BASE + (1UL << KVM_VMM_SHIFT); rtc_phys_addr = LOCAL_MMR_OFFSET | SH_RTC; pte = pte_val(mk_pte_phys(rtc_phys_addr, PAGE_KERNEL_UC)); slot = ia64_itr_entry(0x3, map_addr, pte, PAGE_SHIFT); vcpu->arch.sn_rtc_tr_slot = slot; if (slot < 0) { printk(KERN_ERR "Mayday mayday! RTC mapping failed!\n"); slot = 0; } return slot; } int kvm_emulate_halt(struct kvm_vcpu *vcpu) { ktime_t kt; long itc_diff; unsigned long vcpu_now_itc; unsigned long expires; struct hrtimer *p_ht = &vcpu->arch.hlt_timer; unsigned long cyc_per_usec = local_cpu_data->cyc_per_usec; struct vpd *vpd = to_host(vcpu->kvm, vcpu->arch.vpd); if (irqchip_in_kernel(vcpu->kvm)) { vcpu_now_itc = kvm_get_itc(vcpu) + vcpu->arch.itc_offset; if (time_after(vcpu_now_itc, vpd->itm)) { vcpu->arch.timer_check = 1; return 1; } itc_diff = vpd->itm - vcpu_now_itc; if (itc_diff < 0) itc_diff = -itc_diff; expires = div64_u64(itc_diff, cyc_per_usec); kt = ktime_set(0, 1000 * expires); vcpu->arch.ht_active = 1; hrtimer_start(p_ht, kt, HRTIMER_MODE_ABS); vcpu->arch.mp_state = KVM_MP_STATE_HALTED; kvm_vcpu_block(vcpu); hrtimer_cancel(p_ht); vcpu->arch.ht_active = 0; if (test_and_clear_bit(KVM_REQ_UNHALT, &vcpu->requests) || kvm_cpu_has_pending_timer(vcpu)) if (vcpu->arch.mp_state == KVM_MP_STATE_HALTED) vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE; if (vcpu->arch.mp_state != KVM_MP_STATE_RUNNABLE) return -EINTR; return 1; } else { printk(KERN_ERR"kvm: Unsupported userspace halt!"); return 0; } } static int handle_vm_shutdown(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run) { kvm_run->exit_reason = KVM_EXIT_SHUTDOWN; return 0; } static int handle_external_interrupt(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run) { return 1; } static int handle_vcpu_debug(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run) { printk("VMM: %s", vcpu->arch.log_buf); return 1; } static int (*kvm_vti_exit_handlers[])(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run) = { [EXIT_REASON_VM_PANIC] = handle_vm_error, [EXIT_REASON_MMIO_INSTRUCTION] = handle_mmio, [EXIT_REASON_PAL_CALL] = handle_pal_call, [EXIT_REASON_SAL_CALL] = handle_sal_call, [EXIT_REASON_SWITCH_RR6] = handle_switch_rr6, [EXIT_REASON_VM_DESTROY] = handle_vm_shutdown, [EXIT_REASON_EXTERNAL_INTERRUPT] = handle_external_interrupt, [EXIT_REASON_IPI] = handle_ipi, [EXIT_REASON_PTC_G] = handle_global_purge, [EXIT_REASON_DEBUG] = handle_vcpu_debug, }; static const int kvm_vti_max_exit_handlers = sizeof(kvm_vti_exit_handlers)/sizeof(*kvm_vti_exit_handlers); static uint32_t kvm_get_exit_reason(struct kvm_vcpu *vcpu) { struct exit_ctl_data *p_exit_data; p_exit_data = kvm_get_exit_data(vcpu); return p_exit_data->exit_reason; } /* * The guest has exited. See if we can fix it or if we need userspace * assistance. */ static int kvm_handle_exit(struct kvm_run *kvm_run, struct kvm_vcpu *vcpu) { u32 exit_reason = kvm_get_exit_reason(vcpu); vcpu->arch.last_exit = exit_reason; if (exit_reason < kvm_vti_max_exit_handlers && kvm_vti_exit_handlers[exit_reason]) return kvm_vti_exit_handlers[exit_reason](vcpu, kvm_run); else { kvm_run->exit_reason = KVM_EXIT_UNKNOWN; kvm_run->hw.hardware_exit_reason = exit_reason; } return 0; } static inline void vti_set_rr6(unsigned long rr6) { ia64_set_rr(RR6, rr6); ia64_srlz_i(); } static int kvm_insert_vmm_mapping(struct kvm_vcpu *vcpu) { unsigned long pte; struct kvm *kvm = vcpu->kvm; int r; /*Insert a pair of tr to map vmm*/ pte = pte_val(mk_pte_phys(__pa(kvm_vmm_base), PAGE_KERNEL)); r = ia64_itr_entry(0x3, KVM_VMM_BASE, pte, KVM_VMM_SHIFT); if (r < 0) goto out; vcpu->arch.vmm_tr_slot = r; /*Insert a pairt of tr to map data of vm*/ pte = pte_val(mk_pte_phys(__pa(kvm->arch.vm_base), PAGE_KERNEL)); r = ia64_itr_entry(0x3, KVM_VM_DATA_BASE, pte, KVM_VM_DATA_SHIFT); if (r < 0) goto out; vcpu->arch.vm_tr_slot = r; #if defined(CONFIG_IA64_SGI_SN2) || defined(CONFIG_IA64_GENERIC) if (kvm->arch.is_sn2) { r = kvm_sn2_setup_mappings(vcpu); if (r < 0) goto out; } #endif r = 0; out: return r; } static void kvm_purge_vmm_mapping(struct kvm_vcpu *vcpu) { struct kvm *kvm = vcpu->kvm; ia64_ptr_entry(0x3, vcpu->arch.vmm_tr_slot); ia64_ptr_entry(0x3, vcpu->arch.vm_tr_slot); #if defined(CONFIG_IA64_SGI_SN2) || defined(CONFIG_IA64_GENERIC) if (kvm->arch.is_sn2) ia64_ptr_entry(0x3, vcpu->arch.sn_rtc_tr_slot); #endif } static int kvm_vcpu_pre_transition(struct kvm_vcpu *vcpu) { unsigned long psr; int r; int cpu = smp_processor_id(); if (vcpu->arch.last_run_cpu != cpu || per_cpu(last_vcpu, cpu) != vcpu) { per_cpu(last_vcpu, cpu) = vcpu; vcpu->arch.last_run_cpu = cpu; kvm_flush_tlb_all(); } vcpu->arch.host_rr6 = ia64_get_rr(RR6); vti_set_rr6(vcpu->arch.vmm_rr); local_irq_save(psr); r = kvm_insert_vmm_mapping(vcpu); local_irq_restore(psr); return r; } static void kvm_vcpu_post_transition(struct kvm_vcpu *vcpu) { kvm_purge_vmm_mapping(vcpu); vti_set_rr6(vcpu->arch.host_rr6); } static int __vcpu_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run) { union context *host_ctx, *guest_ctx; int r, idx; idx = srcu_read_lock(&vcpu->kvm->srcu); again: if (signal_pending(current)) { r = -EINTR; kvm_run->exit_reason = KVM_EXIT_INTR; goto out; } preempt_disable(); local_irq_disable(); /*Get host and guest context with guest address space.*/ host_ctx = kvm_get_host_context(vcpu); guest_ctx = kvm_get_guest_context(vcpu); clear_bit(KVM_REQ_KICK, &vcpu->requests); r = kvm_vcpu_pre_transition(vcpu); if (r < 0) goto vcpu_run_fail; srcu_read_unlock(&vcpu->kvm->srcu, idx); vcpu->mode = IN_GUEST_MODE; kvm_guest_enter(); /* * Transition to the guest */ kvm_vmm_info->tramp_entry(host_ctx, guest_ctx); kvm_vcpu_post_transition(vcpu); vcpu->arch.launched = 1; set_bit(KVM_REQ_KICK, &vcpu->requests); local_irq_enable(); /* * We must have an instruction between local_irq_enable() and * kvm_guest_exit(), so the timer interrupt isn't delayed by * the interrupt shadow. The stat.exits increment will do nicely. * But we need to prevent reordering, hence this barrier(): */ barrier(); kvm_guest_exit(); vcpu->mode = OUTSIDE_GUEST_MODE; preempt_enable(); idx = srcu_read_lock(&vcpu->kvm->srcu); r = kvm_handle_exit(kvm_run, vcpu); if (r > 0) { if (!need_resched()) goto again; } out: srcu_read_unlock(&vcpu->kvm->srcu, idx); if (r > 0) { kvm_resched(vcpu); idx = srcu_read_lock(&vcpu->kvm->srcu); goto again; } return r; vcpu_run_fail: local_irq_enable(); preempt_enable(); kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY; goto out; } static void kvm_set_mmio_data(struct kvm_vcpu *vcpu) { struct kvm_mmio_req *p = kvm_get_vcpu_ioreq(vcpu); if (!vcpu->mmio_is_write) memcpy(&p->data, vcpu->mmio_data, 8); p->state = STATE_IORESP_READY; } int kvm_arch_vcpu_ioctl_run(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run) { int r; sigset_t sigsaved; if (vcpu->sigset_active) sigprocmask(SIG_SETMASK, &vcpu->sigset, &sigsaved); if (unlikely(vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED)) { kvm_vcpu_block(vcpu); clear_bit(KVM_REQ_UNHALT, &vcpu->requests); r = -EAGAIN; goto out; } if (vcpu->mmio_needed) { memcpy(vcpu->mmio_data, kvm_run->mmio.data, 8); kvm_set_mmio_data(vcpu); vcpu->mmio_read_completed = 1; vcpu->mmio_needed = 0; } r = __vcpu_run(vcpu, kvm_run); out: if (vcpu->sigset_active) sigprocmask(SIG_SETMASK, &sigsaved, NULL); return r; } struct kvm *kvm_arch_alloc_vm(void) { struct kvm *kvm; uint64_t vm_base; BUG_ON(sizeof(struct kvm) > KVM_VM_STRUCT_SIZE); vm_base = __get_free_pages(GFP_KERNEL, get_order(KVM_VM_DATA_SIZE)); if (!vm_base) return NULL; memset((void *)vm_base, 0, KVM_VM_DATA_SIZE); kvm = (struct kvm *)(vm_base + offsetof(struct kvm_vm_data, kvm_vm_struct)); kvm->arch.vm_base = vm_base; printk(KERN_DEBUG"kvm: vm's data area:0x%lx\n", vm_base); return kvm; } struct kvm_ia64_io_range { unsigned long start; unsigned long size; unsigned long type; }; static const struct kvm_ia64_io_range io_ranges[] = { {VGA_IO_START, VGA_IO_SIZE, GPFN_FRAME_BUFFER}, {MMIO_START, MMIO_SIZE, GPFN_LOW_MMIO}, {LEGACY_IO_START, LEGACY_IO_SIZE, GPFN_LEGACY_IO}, {IO_SAPIC_START, IO_SAPIC_SIZE, GPFN_IOSAPIC}, {PIB_START, PIB_SIZE, GPFN_PIB}, }; static void kvm_build_io_pmt(struct kvm *kvm) { unsigned long i, j; /* Mark I/O ranges */ for (i = 0; i < (sizeof(io_ranges) / sizeof(struct kvm_io_range)); i++) { for (j = io_ranges[i].start; j < io_ranges[i].start + io_ranges[i].size; j += PAGE_SIZE) kvm_set_pmt_entry(kvm, j >> PAGE_SHIFT, io_ranges[i].type, 0); } } /*Use unused rids to virtualize guest rid.*/ #define GUEST_PHYSICAL_RR0 0x1739 #define GUEST_PHYSICAL_RR4 0x2739 #define VMM_INIT_RR 0x1660 int kvm_arch_init_vm(struct kvm *kvm) { BUG_ON(!kvm); kvm->arch.is_sn2 = ia64_platform_is("sn2"); kvm->arch.metaphysical_rr0 = GUEST_PHYSICAL_RR0; kvm->arch.metaphysical_rr4 = GUEST_PHYSICAL_RR4; kvm->arch.vmm_init_rr = VMM_INIT_RR; /* *Fill P2M entries for MMIO/IO ranges */ kvm_build_io_pmt(kvm); INIT_LIST_HEAD(&kvm->arch.assigned_dev_head); /* Reserve bit 0 of irq_sources_bitmap for userspace irq source */ set_bit(KVM_USERSPACE_IRQ_SOURCE_ID, &kvm->arch.irq_sources_bitmap); return 0; } static int kvm_vm_ioctl_get_irqchip(struct kvm *kvm, struct kvm_irqchip *chip) { int r; r = 0; switch (chip->chip_id) { case KVM_IRQCHIP_IOAPIC: r = kvm_get_ioapic(kvm, &chip->chip.ioapic); break; default: r = -EINVAL; break; } return r; } static int kvm_vm_ioctl_set_irqchip(struct kvm *kvm, struct kvm_irqchip *chip) { int r; r = 0; switch (chip->chip_id) { case KVM_IRQCHIP_IOAPIC: r = kvm_set_ioapic(kvm, &chip->chip.ioapic); break; default: r = -EINVAL; break; } return r; } #define RESTORE_REGS(_x) vcpu->arch._x = regs->_x int kvm_arch_vcpu_ioctl_set_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs) { struct vpd *vpd = to_host(vcpu->kvm, vcpu->arch.vpd); int i; for (i = 0; i < 16; i++) { vpd->vgr[i] = regs->vpd.vgr[i]; vpd->vbgr[i] = regs->vpd.vbgr[i]; } for (i = 0; i < 128; i++) vpd->vcr[i] = regs->vpd.vcr[i]; vpd->vhpi = regs->vpd.vhpi; vpd->vnat = regs->vpd.vnat; vpd->vbnat = regs->vpd.vbnat; vpd->vpsr = regs->vpd.vpsr; vpd->vpr = regs->vpd.vpr; memcpy(&vcpu->arch.guest, &regs->saved_guest, sizeof(union context)); RESTORE_REGS(mp_state); RESTORE_REGS(vmm_rr); memcpy(vcpu->arch.itrs, regs->itrs, sizeof(struct thash_data) * NITRS); memcpy(vcpu->arch.dtrs, regs->dtrs, sizeof(struct thash_data) * NDTRS); RESTORE_REGS(itr_regions); RESTORE_REGS(dtr_regions); RESTORE_REGS(tc_regions); RESTORE_REGS(irq_check); RESTORE_REGS(itc_check); RESTORE_REGS(timer_check); RESTORE_REGS(timer_pending); RESTORE_REGS(last_itc); for (i = 0; i < 8; i++) { vcpu->arch.vrr[i] = regs->vrr[i]; vcpu->arch.ibr[i] = regs->ibr[i]; vcpu->arch.dbr[i] = regs->dbr[i]; } for (i = 0; i < 4; i++) vcpu->arch.insvc[i] = regs->insvc[i]; RESTORE_REGS(xtp); RESTORE_REGS(metaphysical_rr0); RESTORE_REGS(metaphysical_rr4); RESTORE_REGS(metaphysical_saved_rr0); RESTORE_REGS(metaphysical_saved_rr4); RESTORE_REGS(fp_psr); RESTORE_REGS(saved_gp); vcpu->arch.irq_new_pending = 1; vcpu->arch.itc_offset = regs->saved_itc - kvm_get_itc(vcpu); set_bit(KVM_REQ_RESUME, &vcpu->requests); return 0; } long kvm_arch_vm_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg) { struct kvm *kvm = filp->private_data; void __user *argp = (void __user *)arg; int r = -ENOTTY; switch (ioctl) { case KVM_SET_MEMORY_REGION: { struct kvm_memory_region kvm_mem; struct kvm_userspace_memory_region kvm_userspace_mem; r = -EFAULT; if (copy_from_user(&kvm_mem, argp, sizeof kvm_mem)) goto out; kvm_userspace_mem.slot = kvm_mem.slot; kvm_userspace_mem.flags = kvm_mem.flags; kvm_userspace_mem.guest_phys_addr = kvm_mem.guest_phys_addr; kvm_userspace_mem.memory_size = kvm_mem.memory_size; r = kvm_vm_ioctl_set_memory_region(kvm, &kvm_userspace_mem, 0); if (r) goto out; break; } case KVM_CREATE_IRQCHIP: r = -EFAULT; r = kvm_ioapic_init(kvm); if (r) goto out; r = kvm_setup_default_irq_routing(kvm); if (r) { mutex_lock(&kvm->slots_lock); kvm_ioapic_destroy(kvm); mutex_unlock(&kvm->slots_lock); goto out; } break; case KVM_IRQ_LINE_STATUS: case KVM_IRQ_LINE: { struct kvm_irq_level irq_event; r = -EFAULT; if (copy_from_user(&irq_event, argp, sizeof irq_event)) goto out; r = -ENXIO; if (irqchip_in_kernel(kvm)) { __s32 status; status = kvm_set_irq(kvm, KVM_USERSPACE_IRQ_SOURCE_ID, irq_event.irq, irq_event.level); if (ioctl == KVM_IRQ_LINE_STATUS) { r = -EFAULT; irq_event.status = status; if (copy_to_user(argp, &irq_event, sizeof irq_event)) goto out; } r = 0; } break; } case KVM_GET_IRQCHIP: { /* 0: PIC master, 1: PIC slave, 2: IOAPIC */ struct kvm_irqchip chip; r = -EFAULT; if (copy_from_user(&chip, argp, sizeof chip)) goto out; r = -ENXIO; if (!irqchip_in_kernel(kvm)) goto out; r = kvm_vm_ioctl_get_irqchip(kvm, &chip); if (r) goto out; r = -EFAULT; if (copy_to_user(argp, &chip, sizeof chip)) goto out; r = 0; break; } case KVM_SET_IRQCHIP: { /* 0: PIC master, 1: PIC slave, 2: IOAPIC */ struct kvm_irqchip chip; r = -EFAULT; if (copy_from_user(&chip, argp, sizeof chip)) goto out; r = -ENXIO; if (!irqchip_in_kernel(kvm)) goto out; r = kvm_vm_ioctl_set_irqchip(kvm, &chip); if (r) goto out; r = 0; break; } default: ; } out: return r; } int kvm_arch_vcpu_ioctl_set_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs) { return -EINVAL; } int kvm_arch_vcpu_ioctl_get_sregs(struct kvm_vcpu *vcpu, struct kvm_sregs *sregs) { return -EINVAL; } int kvm_arch_vcpu_ioctl_translate(struct kvm_vcpu *vcpu, struct kvm_translation *tr) { return -EINVAL; } static int kvm_alloc_vmm_area(void) { if (!kvm_vmm_base && (kvm_vm_buffer_size < KVM_VM_BUFFER_SIZE)) { kvm_vmm_base = __get_free_pages(GFP_KERNEL, get_order(KVM_VMM_SIZE)); if (!kvm_vmm_base) return -ENOMEM; memset((void *)kvm_vmm_base, 0, KVM_VMM_SIZE); kvm_vm_buffer = kvm_vmm_base + VMM_SIZE; printk(KERN_DEBUG"kvm:VMM's Base Addr:0x%lx, vm_buffer:0x%lx\n", kvm_vmm_base, kvm_vm_buffer); } return 0; } static void kvm_free_vmm_area(void) { if (kvm_vmm_base) { /*Zero this area before free to avoid bits leak!!*/ memset((void *)kvm_vmm_base, 0, KVM_VMM_SIZE); free_pages(kvm_vmm_base, get_order(KVM_VMM_SIZE)); kvm_vmm_base = 0; kvm_vm_buffer = 0; kvm_vsa_base = 0; } } static int vti_init_vpd(struct kvm_vcpu *vcpu) { int i; union cpuid3_t cpuid3; struct vpd *vpd = to_host(vcpu->kvm, vcpu->arch.vpd); if (IS_ERR(vpd)) return PTR_ERR(vpd); /* CPUID init */ for (i = 0; i < 5; i++) vpd->vcpuid[i] = ia64_get_cpuid(i); /* Limit the CPUID number to 5 */ cpuid3.value = vpd->vcpuid[3]; cpuid3.number = 4; /* 5 - 1 */ vpd->vcpuid[3] = cpuid3.value; /*Set vac and vdc fields*/ vpd->vac.a_from_int_cr = 1; vpd->vac.a_to_int_cr = 1; vpd->vac.a_from_psr = 1; vpd->vac.a_from_cpuid = 1; vpd->vac.a_cover = 1; vpd->vac.a_bsw = 1; vpd->vac.a_int = 1; vpd->vdc.d_vmsw = 1; /*Set virtual buffer*/ vpd->virt_env_vaddr = KVM_VM_BUFFER_BASE; return 0; } static int vti_create_vp(struct kvm_vcpu *vcpu) { long ret; struct vpd *vpd = vcpu->arch.vpd; unsigned long vmm_ivt; vmm_ivt = kvm_vmm_info->vmm_ivt; printk(KERN_DEBUG "kvm: vcpu:%p,ivt: 0x%lx\n", vcpu, vmm_ivt); ret = ia64_pal_vp_create((u64 *)vpd, (u64 *)vmm_ivt, 0); if (ret) { printk(KERN_ERR"kvm: ia64_pal_vp_create failed!\n"); return -EINVAL; } return 0; } static void init_ptce_info(struct kvm_vcpu *vcpu) { ia64_ptce_info_t ptce = {0}; ia64_get_ptce(&ptce); vcpu->arch.ptce_base = ptce.base; vcpu->arch.ptce_count[0] = ptce.count[0]; vcpu->arch.ptce_count[1] = ptce.count[1]; vcpu->arch.ptce_stride[0] = ptce.stride[0]; vcpu->arch.ptce_stride[1] = ptce.stride[1]; } static void kvm_migrate_hlt_timer(struct kvm_vcpu *vcpu) { struct hrtimer *p_ht = &vcpu->arch.hlt_timer; if (hrtimer_cancel(p_ht)) hrtimer_start_expires(p_ht, HRTIMER_MODE_ABS); } static enum hrtimer_restart hlt_timer_fn(struct hrtimer *data) { struct kvm_vcpu *vcpu; wait_queue_head_t *q; vcpu = container_of(data, struct kvm_vcpu, arch.hlt_timer); q = &vcpu->wq; if (vcpu->arch.mp_state != KVM_MP_STATE_HALTED) goto out; if (waitqueue_active(q)) wake_up_interruptible(q); out: vcpu->arch.timer_fired = 1; vcpu->arch.timer_check = 1; return HRTIMER_NORESTART; } #define PALE_RESET_ENTRY 0x80000000ffffffb0UL bool kvm_vcpu_compatible(struct kvm_vcpu *vcpu) { return irqchip_in_kernel(vcpu->kcm) == (vcpu->arch.apic != NULL); } int kvm_arch_vcpu_init(struct kvm_vcpu *vcpu) { struct kvm_vcpu *v; int r; int i; long itc_offset; struct kvm *kvm = vcpu->kvm; struct kvm_pt_regs *regs = vcpu_regs(vcpu); union context *p_ctx = &vcpu->arch.guest; struct kvm_vcpu *vmm_vcpu = to_guest(vcpu->kvm, vcpu); /*Init vcpu context for first run.*/ if (IS_ERR(vmm_vcpu)) return PTR_ERR(vmm_vcpu); if (kvm_vcpu_is_bsp(vcpu)) { vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE; /*Set entry address for first run.*/ regs->cr_iip = PALE_RESET_ENTRY; /*Initialize itc offset for vcpus*/ itc_offset = 0UL - kvm_get_itc(vcpu); for (i = 0; i < KVM_MAX_VCPUS; i++) { v = (struct kvm_vcpu *)((char *)vcpu + sizeof(struct kvm_vcpu_data) * i); v->arch.itc_offset = itc_offset; v->arch.last_itc = 0; } } else vcpu->arch.mp_state = KVM_MP_STATE_UNINITIALIZED; r = -ENOMEM; vcpu->arch.apic = kzalloc(sizeof(struct kvm_lapic), GFP_KERNEL); if (!vcpu->arch.apic) goto out; vcpu->arch.apic->vcpu = vcpu; p_ctx->gr[1] = 0; p_ctx->gr[12] = (unsigned long)((char *)vmm_vcpu + KVM_STK_OFFSET); p_ctx->gr[13] = (unsigned long)vmm_vcpu; p_ctx->psr = 0x1008522000UL; p_ctx->ar[40] = FPSR_DEFAULT; /*fpsr*/ p_ctx->caller_unat = 0; p_ctx->pr = 0x0; p_ctx->ar[36] = 0x0; /*unat*/ p_ctx->ar[19] = 0x0; /*rnat*/ p_ctx->ar[18] = (unsigned long)vmm_vcpu + ((sizeof(struct kvm_vcpu)+15) & ~15); p_ctx->ar[64] = 0x0; /*pfs*/ p_ctx->cr[0] = 0x7e04UL; p_ctx->cr[2] = (unsigned long)kvm_vmm_info->vmm_ivt; p_ctx->cr[8] = 0x3c; /*Initialize region register*/ p_ctx->rr[0] = 0x30; p_ctx->rr[1] = 0x30; p_ctx->rr[2] = 0x30; p_ctx->rr[3] = 0x30; p_ctx->rr[4] = 0x30; p_ctx->rr[5] = 0x30; p_ctx->rr[7] = 0x30; /*Initialize branch register 0*/ p_ctx->br[0] = *(unsigned long *)kvm_vmm_info->vmm_entry; vcpu->arch.vmm_rr = kvm->arch.vmm_init_rr; vcpu->arch.metaphysical_rr0 = kvm->arch.metaphysical_rr0; vcpu->arch.metaphysical_rr4 = kvm->arch.metaphysical_rr4; hrtimer_init(&vcpu->arch.hlt_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS); vcpu->arch.hlt_timer.function = hlt_timer_fn; vcpu->arch.last_run_cpu = -1; vcpu->arch.vpd = (struct vpd *)VPD_BASE(vcpu->vcpu_id); vcpu->arch.vsa_base = kvm_vsa_base; vcpu->arch.__gp = kvm_vmm_gp; vcpu->arch.dirty_log_lock_pa = __pa(&kvm->arch.dirty_log_lock); vcpu->arch.vhpt.hash = (struct thash_data *)VHPT_BASE(vcpu->vcpu_id); vcpu->arch.vtlb.hash = (struct thash_data *)VTLB_BASE(vcpu->vcpu_id); init_ptce_info(vcpu); r = 0; out: return r; } static int vti_vcpu_setup(struct kvm_vcpu *vcpu, int id) { unsigned long psr; int r; local_irq_save(psr); r = kvm_insert_vmm_mapping(vcpu); local_irq_restore(psr); if (r) goto fail; r = kvm_vcpu_init(vcpu, vcpu->kvm, id); if (r) goto fail; r = vti_init_vpd(vcpu); if (r) { printk(KERN_DEBUG"kvm: vpd init error!!\n"); goto uninit; } r = vti_create_vp(vcpu); if (r) goto uninit; kvm_purge_vmm_mapping(vcpu); return 0; uninit: kvm_vcpu_uninit(vcpu); fail: return r; } struct kvm_vcpu *kvm_arch_vcpu_create(struct kvm *kvm, unsigned int id) { struct kvm_vcpu *vcpu; unsigned long vm_base = kvm->arch.vm_base; int r; int cpu; BUG_ON(sizeof(struct kvm_vcpu) > VCPU_STRUCT_SIZE/2); r = -EINVAL; if (id >= KVM_MAX_VCPUS) { printk(KERN_ERR"kvm: Can't configure vcpus > %ld", KVM_MAX_VCPUS); goto fail; } r = -ENOMEM; if (!vm_base) { printk(KERN_ERR"kvm: Create vcpu[%d] error!\n", id); goto fail; } vcpu = (struct kvm_vcpu *)(vm_base + offsetof(struct kvm_vm_data, vcpu_data[id].vcpu_struct)); vcpu->kvm = kvm; cpu = get_cpu(); r = vti_vcpu_setup(vcpu, id); put_cpu(); if (r) { printk(KERN_DEBUG"kvm: vcpu_setup error!!\n"); goto fail; } return vcpu; fail: return ERR_PTR(r); } int kvm_arch_vcpu_setup(struct kvm_vcpu *vcpu) { 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_set_guest_debug(struct kvm_vcpu *vcpu, struct kvm_guest_debug *dbg) { return -EINVAL; } void kvm_arch_free_vm(struct kvm *kvm) { unsigned long vm_base = kvm->arch.vm_base; if (vm_base) { memset((void *)vm_base, 0, KVM_VM_DATA_SIZE); free_pages(vm_base, get_order(KVM_VM_DATA_SIZE)); } } static void kvm_release_vm_pages(struct kvm *kvm) { struct kvm_memslots *slots; struct kvm_memory_slot *memslot; int j; unsigned long base_gfn; slots = kvm_memslots(kvm); kvm_for_each_memslot(memslot, slots) { base_gfn = memslot->base_gfn; for (j = 0; j < memslot->npages; j++) { if (memslot->rmap[j]) put_page((struct page *)memslot->rmap[j]); } } } void kvm_arch_sync_events(struct kvm *kvm) { } void kvm_arch_destroy_vm(struct kvm *kvm) { kvm_iommu_unmap_guest(kvm); #ifdef KVM_CAP_DEVICE_ASSIGNMENT kvm_free_all_assigned_devices(kvm); #endif kfree(kvm->arch.vioapic); kvm_release_vm_pages(kvm); } void kvm_arch_vcpu_put(struct kvm_vcpu *vcpu) { } void kvm_arch_vcpu_load(struct kvm_vcpu *vcpu, int cpu) { if (cpu != vcpu->cpu) { vcpu->cpu = cpu; if (vcpu->arch.ht_active) kvm_migrate_hlt_timer(vcpu); } } #define SAVE_REGS(_x) regs->_x = vcpu->arch._x int kvm_arch_vcpu_ioctl_get_regs(struct kvm_vcpu *vcpu, struct kvm_regs *regs) { struct vpd *vpd = to_host(vcpu->kvm, vcpu->arch.vpd); int i; vcpu_load(vcpu); for (i = 0; i < 16; i++) { regs->vpd.vgr[i] = vpd->vgr[i]; regs->vpd.vbgr[i] = vpd->vbgr[i]; } for (i = 0; i < 128; i++) regs->vpd.vcr[i] = vpd->vcr[i]; regs->vpd.vhpi = vpd->vhpi; regs->vpd.vnat = vpd->vnat; regs->vpd.vbnat = vpd->vbnat; regs->vpd.vpsr = vpd->vpsr; regs->vpd.vpr = vpd->vpr; memcpy(&regs->saved_guest, &vcpu->arch.guest, sizeof(union context)); SAVE_REGS(mp_state); SAVE_REGS(vmm_rr); memcpy(regs->itrs, vcpu->arch.itrs, sizeof(struct thash_data) * NITRS); memcpy(regs->dtrs, vcpu->arch.dtrs, sizeof(struct thash_data) * NDTRS); SAVE_REGS(itr_regions); SAVE_REGS(dtr_regions); SAVE_REGS(tc_regions); SAVE_REGS(irq_check); SAVE_REGS(itc_check); SAVE_REGS(timer_check); SAVE_REGS(timer_pending); SAVE_REGS(last_itc); for (i = 0; i < 8; i++) { regs->vrr[i] = vcpu->arch.vrr[i]; regs->ibr[i] = vcpu->arch.ibr[i]; regs->dbr[i] = vcpu->arch.dbr[i]; } for (i = 0; i < 4; i++) regs->insvc[i] = vcpu->arch.insvc[i]; regs->saved_itc = vcpu->arch.itc_offset + kvm_get_itc(vcpu); SAVE_REGS(xtp); SAVE_REGS(metaphysical_rr0); SAVE_REGS(metaphysical_rr4); SAVE_REGS(metaphysical_saved_rr0); SAVE_REGS(metaphysical_saved_rr4); SAVE_REGS(fp_psr); SAVE_REGS(saved_gp); vcpu_put(vcpu); return 0; } int kvm_arch_vcpu_ioctl_get_stack(struct kvm_vcpu *vcpu, struct kvm_ia64_vcpu_stack *stack) { memcpy(stack, vcpu, sizeof(struct kvm_ia64_vcpu_stack)); return 0; } int kvm_arch_vcpu_ioctl_set_stack(struct kvm_vcpu *vcpu, struct kvm_ia64_vcpu_stack *stack) { memcpy(vcpu + 1, &stack->stack[0] + sizeof(struct kvm_vcpu), sizeof(struct kvm_ia64_vcpu_stack) - sizeof(struct kvm_vcpu)); vcpu->arch.exit_data = ((struct kvm_vcpu *)stack)->arch.exit_data; return 0; } void kvm_arch_vcpu_uninit(struct kvm_vcpu *vcpu) { hrtimer_cancel(&vcpu->arch.hlt_timer); kfree(vcpu->arch.apic); } long kvm_arch_vcpu_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg) { struct kvm_vcpu *vcpu = filp->private_data; void __user *argp = (void __user *)arg; struct kvm_ia64_vcpu_stack *stack = NULL; long r; switch (ioctl) { case KVM_IA64_VCPU_GET_STACK: { struct kvm_ia64_vcpu_stack __user *user_stack; void __user *first_p = argp; r = -EFAULT; if (copy_from_user(&user_stack, first_p, sizeof(void *))) goto out; if (!access_ok(VERIFY_WRITE, user_stack, sizeof(struct kvm_ia64_vcpu_stack))) { printk(KERN_INFO "KVM_IA64_VCPU_GET_STACK: " "Illegal user destination address for stack\n"); goto out; } stack = kzalloc(sizeof(struct kvm_ia64_vcpu_stack), GFP_KERNEL); if (!stack) { r = -ENOMEM; goto out; } r = kvm_arch_vcpu_ioctl_get_stack(vcpu, stack); if (r) goto out; if (copy_to_user(user_stack, stack, sizeof(struct kvm_ia64_vcpu_stack))) { r = -EFAULT; goto out; } break; } case KVM_IA64_VCPU_SET_STACK: { struct kvm_ia64_vcpu_stack __user *user_stack; void __user *first_p = argp; r = -EFAULT; if (copy_from_user(&user_stack, first_p, sizeof(void *))) goto out; if (!access_ok(VERIFY_READ, user_stack, sizeof(struct kvm_ia64_vcpu_stack))) { printk(KERN_INFO "KVM_IA64_VCPU_SET_STACK: " "Illegal user address for stack\n"); goto out; } stack = kmalloc(sizeof(struct kvm_ia64_vcpu_stack), GFP_KERNEL); if (!stack) { r = -ENOMEM; goto out; } if (copy_from_user(stack, user_stack, sizeof(struct kvm_ia64_vcpu_stack))) goto out; r = kvm_arch_vcpu_ioctl_set_stack(vcpu, stack); break; } default: r = -EINVAL; } out: kfree(stack); return r; } int kvm_arch_prepare_memory_region(struct kvm *kvm, struct kvm_memory_slot *memslot, struct kvm_memory_slot old, struct kvm_userspace_memory_region *mem, int user_alloc) { unsigned long i; unsigned long pfn; int npages = memslot->npages; unsigned long base_gfn = memslot->base_gfn; if (base_gfn + npages > (KVM_MAX_MEM_SIZE >> PAGE_SHIFT)) return -ENOMEM; for (i = 0; i < npages; i++) { pfn = gfn_to_pfn(kvm, base_gfn + i); if (!kvm_is_mmio_pfn(pfn)) { kvm_set_pmt_entry(kvm, base_gfn + i, pfn << PAGE_SHIFT, _PAGE_AR_RWX | _PAGE_MA_WB); memslot->rmap[i] = (unsigned long)pfn_to_page(pfn); } else { kvm_set_pmt_entry(kvm, base_gfn + i, GPFN_PHYS_MMIO | (pfn << PAGE_SHIFT), _PAGE_MA_UC); memslot->rmap[i] = 0; } } return 0; } void kvm_arch_commit_memory_region(struct kvm *kvm, struct kvm_userspace_memory_region *mem, struct kvm_memory_slot old, int user_alloc) { return; } void kvm_arch_flush_shadow(struct kvm *kvm) { kvm_flush_remote_tlbs(kvm); } long kvm_arch_dev_ioctl(struct file *filp, unsigned int ioctl, unsigned long arg) { return -EINVAL; } void kvm_arch_vcpu_destroy(struct kvm_vcpu *vcpu) { kvm_vcpu_uninit(vcpu); } static int vti_cpu_has_kvm_support(void) { long avail = 1, status = 1, control = 1; long ret; ret = ia64_pal_proc_get_features(&avail, &status, &control, 0); if (ret) goto out; if (!(avail & PAL_PROC_VM_BIT)) goto out; printk(KERN_DEBUG"kvm: Hardware Supports VT\n"); ret = ia64_pal_vp_env_info(&kvm_vm_buffer_size, &vp_env_info); if (ret) goto out; printk(KERN_DEBUG"kvm: VM Buffer Size:0x%lx\n", kvm_vm_buffer_size); if (!(vp_env_info & VP_OPCODE)) { printk(KERN_WARNING"kvm: No opcode ability on hardware, " "vm_env_info:0x%lx\n", vp_env_info); } return 1; out: return 0; } /* * On SN2, the ITC isn't stable, so copy in fast path code to use the * SN2 RTC, replacing the ITC based default verion. */ static void kvm_patch_vmm(struct kvm_vmm_info *vmm_info, struct module *module) { unsigned long new_ar, new_ar_sn2; unsigned long module_base; if (!ia64_platform_is("sn2")) return; module_base = (unsigned long)module->module_core; new_ar = kvm_vmm_base + vmm_info->patch_mov_ar - module_base; new_ar_sn2 = kvm_vmm_base + vmm_info->patch_mov_ar_sn2 - module_base; printk(KERN_INFO "kvm: Patching ITC emulation to use SGI SN2 RTC " "as source\n"); /* * Copy the SN2 version of mov_ar into place. They are both * the same size, so 6 bundles is sufficient (6 * 0x10). */ memcpy((void *)new_ar, (void *)new_ar_sn2, 0x60); } static int kvm_relocate_vmm(struct kvm_vmm_info *vmm_info, struct module *module) { unsigned long module_base; unsigned long vmm_size; unsigned long vmm_offset, func_offset, fdesc_offset; struct fdesc *p_fdesc; BUG_ON(!module); if (!kvm_vmm_base) { printk("kvm: kvm area hasn't been initialized yet!!\n"); return -EFAULT; } /*Calculate new position of relocated vmm module.*/ module_base = (unsigned long)module->module_core; vmm_size = module->core_size; if (unlikely(vmm_size > KVM_VMM_SIZE)) return -EFAULT; memcpy((void *)kvm_vmm_base, (void *)module_base, vmm_size); kvm_patch_vmm(vmm_info, module); kvm_flush_icache(kvm_vmm_base, vmm_size); /*Recalculate kvm_vmm_info based on new VMM*/ vmm_offset = vmm_info->vmm_ivt - module_base; kvm_vmm_info->vmm_ivt = KVM_VMM_BASE + vmm_offset; printk(KERN_DEBUG"kvm: Relocated VMM's IVT Base Addr:%lx\n", kvm_vmm_info->vmm_ivt); fdesc_offset = (unsigned long)vmm_info->vmm_entry - module_base; kvm_vmm_info->vmm_entry = (kvm_vmm_entry *)(KVM_VMM_BASE + fdesc_offset); func_offset = *(unsigned long *)vmm_info->vmm_entry - module_base; p_fdesc = (struct fdesc *)(kvm_vmm_base + fdesc_offset); p_fdesc->ip = KVM_VMM_BASE + func_offset; p_fdesc->gp = KVM_VMM_BASE+(p_fdesc->gp - module_base); printk(KERN_DEBUG"kvm: Relocated VMM's Init Entry Addr:%lx\n", KVM_VMM_BASE+func_offset); fdesc_offset = (unsigned long)vmm_info->tramp_entry - module_base; kvm_vmm_info->tramp_entry = (kvm_tramp_entry *)(KVM_VMM_BASE + fdesc_offset); func_offset = *(unsigned long *)vmm_info->tramp_entry - module_base; p_fdesc = (struct fdesc *)(kvm_vmm_base + fdesc_offset); p_fdesc->ip = KVM_VMM_BASE + func_offset; p_fdesc->gp = KVM_VMM_BASE + (p_fdesc->gp - module_base); kvm_vmm_gp = p_fdesc->gp; printk(KERN_DEBUG"kvm: Relocated VMM's Entry IP:%p\n", kvm_vmm_info->vmm_entry); printk(KERN_DEBUG"kvm: Relocated VMM's Trampoline Entry IP:0x%lx\n", KVM_VMM_BASE + func_offset); return 0; } int kvm_arch_init(void *opaque) { int r; struct kvm_vmm_info *vmm_info = (struct kvm_vmm_info *)opaque; if (!vti_cpu_has_kvm_support()) { printk(KERN_ERR "kvm: No Hardware Virtualization Support!\n"); r = -EOPNOTSUPP; goto out; } if (kvm_vmm_info) { printk(KERN_ERR "kvm: Already loaded VMM module!\n"); r = -EEXIST; goto out; } r = -ENOMEM; kvm_vmm_info = kzalloc(sizeof(struct kvm_vmm_info), GFP_KERNEL); if (!kvm_vmm_info) goto out; if (kvm_alloc_vmm_area()) goto out_free0; r = kvm_relocate_vmm(vmm_info, vmm_info->module); if (r) goto out_free1; return 0; out_free1: kvm_free_vmm_area(); out_free0: kfree(kvm_vmm_info); out: return r; } void kvm_arch_exit(void) { kvm_free_vmm_area(); kfree(kvm_vmm_info); kvm_vmm_info = NULL; } static void kvm_ia64_sync_dirty_log(struct kvm *kvm, struct kvm_memory_slot *memslot) { int i; long base; unsigned long n; unsigned long *dirty_bitmap = (unsigned long *)(kvm->arch.vm_base + offsetof(struct kvm_vm_data, kvm_mem_dirty_log)); n = kvm_dirty_bitmap_bytes(memslot); base = memslot->base_gfn / BITS_PER_LONG; spin_lock(&kvm->arch.dirty_log_lock); for (i = 0; i < n/sizeof(long); ++i) { memslot->dirty_bitmap[i] = dirty_bitmap[base + i]; dirty_bitmap[base + i] = 0; } spin_unlock(&kvm->arch.dirty_log_lock); } int kvm_vm_ioctl_get_dirty_log(struct kvm *kvm, struct kvm_dirty_log *log) { int r; unsigned long n; struct kvm_memory_slot *memslot; int is_dirty = 0; mutex_lock(&kvm->slots_lock); r = -EINVAL; if (log->slot >= KVM_MEMORY_SLOTS) goto out; memslot = id_to_memslot(kvm->memslots, log->slot); r = -ENOENT; if (!memslot->dirty_bitmap) goto out; kvm_ia64_sync_dirty_log(kvm, memslot); r = kvm_get_dirty_log(kvm, log, &is_dirty); if (r) goto out; /* If nothing is dirty, don't bother messing with page tables. */ if (is_dirty) { kvm_flush_remote_tlbs(kvm); n = kvm_dirty_bitmap_bytes(memslot); memset(memslot->dirty_bitmap, 0, n); } r = 0; out: mutex_unlock(&kvm->slots_lock); return r; } int kvm_arch_hardware_setup(void) { return 0; } void kvm_arch_hardware_unsetup(void) { } void kvm_vcpu_kick(struct kvm_vcpu *vcpu) { int me; int cpu = vcpu->cpu; if (waitqueue_active(&vcpu->wq)) wake_up_interruptible(&vcpu->wq); me = get_cpu(); if (cpu != me && (unsigned) cpu < nr_cpu_ids && cpu_online(cpu)) if (!test_and_set_bit(KVM_REQ_KICK, &vcpu->requests)) smp_send_reschedule(cpu); put_cpu(); } int kvm_apic_set_irq(struct kvm_vcpu *vcpu, struct kvm_lapic_irq *irq) { return __apic_accept_irq(vcpu, irq->vector); } int kvm_apic_match_physical_addr(struct kvm_lapic *apic, u16 dest) { return apic->vcpu->vcpu_id == dest; } int kvm_apic_match_logical_addr(struct kvm_lapic *apic, u8 mda) { return 0; } int kvm_apic_compare_prio(struct kvm_vcpu *vcpu1, struct kvm_vcpu *vcpu2) { return vcpu1->arch.xtp - vcpu2->arch.xtp; } int kvm_apic_match_dest(struct kvm_vcpu *vcpu, struct kvm_lapic *source, int short_hand, int dest, int dest_mode) { struct kvm_lapic *target = vcpu->arch.apic; return (dest_mode == 0) ? kvm_apic_match_physical_addr(target, dest) : kvm_apic_match_logical_addr(target, dest); } static int find_highest_bits(int *dat) { u32 bits, bitnum; int i; /* loop for all 256 bits */ for (i = 7; i >= 0 ; i--) { bits = dat[i]; if (bits) { bitnum = fls(bits); return i * 32 + bitnum - 1; } } return -1; } int kvm_highest_pending_irq(struct kvm_vcpu *vcpu) { struct vpd *vpd = to_host(vcpu->kvm, vcpu->arch.vpd); if (vpd->irr[0] & (1UL << NMI_VECTOR)) return NMI_VECTOR; if (vpd->irr[0] & (1UL << ExtINT_VECTOR)) return ExtINT_VECTOR; return find_highest_bits((int *)&vpd->irr[0]); } int kvm_cpu_has_pending_timer(struct kvm_vcpu *vcpu) { return vcpu->arch.timer_fired; } int kvm_arch_vcpu_runnable(struct kvm_vcpu *vcpu) { return (vcpu->arch.mp_state == KVM_MP_STATE_RUNNABLE) || (kvm_highest_pending_irq(vcpu) != -1); } int kvm_arch_vcpu_ioctl_get_mpstate(struct kvm_vcpu *vcpu, struct kvm_mp_state *mp_state) { mp_state->mp_state = vcpu->arch.mp_state; return 0; } static int vcpu_reset(struct kvm_vcpu *vcpu) { int r; long psr; local_irq_save(psr); r = kvm_insert_vmm_mapping(vcpu); local_irq_restore(psr); if (r) goto fail; vcpu->arch.launched = 0; kvm_arch_vcpu_uninit(vcpu); r = kvm_arch_vcpu_init(vcpu); if (r) goto fail; kvm_purge_vmm_mapping(vcpu); r = 0; fail: return r; } int kvm_arch_vcpu_ioctl_set_mpstate(struct kvm_vcpu *vcpu, struct kvm_mp_state *mp_state) { int r = 0; vcpu->arch.mp_state = mp_state->mp_state; if (vcpu->arch.mp_state == KVM_MP_STATE_UNINITIALIZED) r = vcpu_reset(vcpu); return r; }
./CrossVul/dataset_final_sorted/CWE-399/c/good_3622_0
crossvul-cpp_data_good_1493_0
/* crypto/bn/bn_gf2m.c */ /* ==================================================================== * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * * The Elliptic Curve Public-Key Crypto Library (ECC Code) included * herein is developed by SUN MICROSYSTEMS, INC., and is contributed * to the OpenSSL project. * * The ECC Code is licensed pursuant to the OpenSSL open source * license provided below. * * In addition, Sun covenants to all licensees who provide a reciprocal * covenant with respect to their own patents if any, not to sue under * current and future patent claims necessarily infringed by the making, * using, practicing, selling, offering for sale and/or otherwise * disposing of the ECC Code as delivered hereunder (or portions thereof), * provided that such covenant shall not apply: * 1) for code that a licensee deletes from the ECC Code; * 2) separates from the ECC Code; or * 3) for infringements caused by: * i) the modification of the ECC Code or * ii) the combination of the ECC Code with other software or * devices where such combination causes the infringement. * * The software is originally written by Sheueling Chang Shantz and * Douglas Stebila of Sun Microsystems Laboratories. * */ /* * NOTE: This file is licensed pursuant to the OpenSSL license below and may * be modified; but after modifications, the above covenant may no longer * apply! In such cases, the corresponding paragraph ["In addition, Sun * covenants ... causes the infringement."] and this note can be edited out; * but please keep the Sun copyright notice and attribution. */ /* ==================================================================== * Copyright (c) 1998-2002 The OpenSSL 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: * * 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. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include <assert.h> #include <limits.h> #include <stdio.h> #include "internal/cryptlib.h" #include "bn_lcl.h" #ifndef OPENSSL_NO_EC2M /* * Maximum number of iterations before BN_GF2m_mod_solve_quad_arr should * fail. */ # define MAX_ITERATIONS 50 static const BN_ULONG SQR_tb[16] = { 0, 1, 4, 5, 16, 17, 20, 21, 64, 65, 68, 69, 80, 81, 84, 85 }; /* Platform-specific macros to accelerate squaring. */ # if defined(SIXTY_FOUR_BIT) || defined(SIXTY_FOUR_BIT_LONG) # define SQR1(w) \ SQR_tb[(w) >> 60 & 0xF] << 56 | SQR_tb[(w) >> 56 & 0xF] << 48 | \ SQR_tb[(w) >> 52 & 0xF] << 40 | SQR_tb[(w) >> 48 & 0xF] << 32 | \ SQR_tb[(w) >> 44 & 0xF] << 24 | SQR_tb[(w) >> 40 & 0xF] << 16 | \ SQR_tb[(w) >> 36 & 0xF] << 8 | SQR_tb[(w) >> 32 & 0xF] # define SQR0(w) \ SQR_tb[(w) >> 28 & 0xF] << 56 | SQR_tb[(w) >> 24 & 0xF] << 48 | \ SQR_tb[(w) >> 20 & 0xF] << 40 | SQR_tb[(w) >> 16 & 0xF] << 32 | \ SQR_tb[(w) >> 12 & 0xF] << 24 | SQR_tb[(w) >> 8 & 0xF] << 16 | \ SQR_tb[(w) >> 4 & 0xF] << 8 | SQR_tb[(w) & 0xF] # endif # ifdef THIRTY_TWO_BIT # define SQR1(w) \ SQR_tb[(w) >> 28 & 0xF] << 24 | SQR_tb[(w) >> 24 & 0xF] << 16 | \ SQR_tb[(w) >> 20 & 0xF] << 8 | SQR_tb[(w) >> 16 & 0xF] # define SQR0(w) \ SQR_tb[(w) >> 12 & 0xF] << 24 | SQR_tb[(w) >> 8 & 0xF] << 16 | \ SQR_tb[(w) >> 4 & 0xF] << 8 | SQR_tb[(w) & 0xF] # endif # if !defined(OPENSSL_BN_ASM_GF2m) /* * Product of two polynomials a, b each with degree < BN_BITS2 - 1, result is * a polynomial r with degree < 2 * BN_BITS - 1 The caller MUST ensure that * the variables have the right amount of space allocated. */ # ifdef THIRTY_TWO_BIT static void bn_GF2m_mul_1x1(BN_ULONG *r1, BN_ULONG *r0, const BN_ULONG a, const BN_ULONG b) { register BN_ULONG h, l, s; BN_ULONG tab[8], top2b = a >> 30; register BN_ULONG a1, a2, a4; a1 = a & (0x3FFFFFFF); a2 = a1 << 1; a4 = a2 << 1; tab[0] = 0; tab[1] = a1; tab[2] = a2; tab[3] = a1 ^ a2; tab[4] = a4; tab[5] = a1 ^ a4; tab[6] = a2 ^ a4; tab[7] = a1 ^ a2 ^ a4; s = tab[b & 0x7]; l = s; s = tab[b >> 3 & 0x7]; l ^= s << 3; h = s >> 29; s = tab[b >> 6 & 0x7]; l ^= s << 6; h ^= s >> 26; s = tab[b >> 9 & 0x7]; l ^= s << 9; h ^= s >> 23; s = tab[b >> 12 & 0x7]; l ^= s << 12; h ^= s >> 20; s = tab[b >> 15 & 0x7]; l ^= s << 15; h ^= s >> 17; s = tab[b >> 18 & 0x7]; l ^= s << 18; h ^= s >> 14; s = tab[b >> 21 & 0x7]; l ^= s << 21; h ^= s >> 11; s = tab[b >> 24 & 0x7]; l ^= s << 24; h ^= s >> 8; s = tab[b >> 27 & 0x7]; l ^= s << 27; h ^= s >> 5; s = tab[b >> 30]; l ^= s << 30; h ^= s >> 2; /* compensate for the top two bits of a */ if (top2b & 01) { l ^= b << 30; h ^= b >> 2; } if (top2b & 02) { l ^= b << 31; h ^= b >> 1; } *r1 = h; *r0 = l; } # endif # if defined(SIXTY_FOUR_BIT) || defined(SIXTY_FOUR_BIT_LONG) static void bn_GF2m_mul_1x1(BN_ULONG *r1, BN_ULONG *r0, const BN_ULONG a, const BN_ULONG b) { register BN_ULONG h, l, s; BN_ULONG tab[16], top3b = a >> 61; register BN_ULONG a1, a2, a4, a8; a1 = a & (0x1FFFFFFFFFFFFFFFULL); a2 = a1 << 1; a4 = a2 << 1; a8 = a4 << 1; tab[0] = 0; tab[1] = a1; tab[2] = a2; tab[3] = a1 ^ a2; tab[4] = a4; tab[5] = a1 ^ a4; tab[6] = a2 ^ a4; tab[7] = a1 ^ a2 ^ a4; tab[8] = a8; tab[9] = a1 ^ a8; tab[10] = a2 ^ a8; tab[11] = a1 ^ a2 ^ a8; tab[12] = a4 ^ a8; tab[13] = a1 ^ a4 ^ a8; tab[14] = a2 ^ a4 ^ a8; tab[15] = a1 ^ a2 ^ a4 ^ a8; s = tab[b & 0xF]; l = s; s = tab[b >> 4 & 0xF]; l ^= s << 4; h = s >> 60; s = tab[b >> 8 & 0xF]; l ^= s << 8; h ^= s >> 56; s = tab[b >> 12 & 0xF]; l ^= s << 12; h ^= s >> 52; s = tab[b >> 16 & 0xF]; l ^= s << 16; h ^= s >> 48; s = tab[b >> 20 & 0xF]; l ^= s << 20; h ^= s >> 44; s = tab[b >> 24 & 0xF]; l ^= s << 24; h ^= s >> 40; s = tab[b >> 28 & 0xF]; l ^= s << 28; h ^= s >> 36; s = tab[b >> 32 & 0xF]; l ^= s << 32; h ^= s >> 32; s = tab[b >> 36 & 0xF]; l ^= s << 36; h ^= s >> 28; s = tab[b >> 40 & 0xF]; l ^= s << 40; h ^= s >> 24; s = tab[b >> 44 & 0xF]; l ^= s << 44; h ^= s >> 20; s = tab[b >> 48 & 0xF]; l ^= s << 48; h ^= s >> 16; s = tab[b >> 52 & 0xF]; l ^= s << 52; h ^= s >> 12; s = tab[b >> 56 & 0xF]; l ^= s << 56; h ^= s >> 8; s = tab[b >> 60]; l ^= s << 60; h ^= s >> 4; /* compensate for the top three bits of a */ if (top3b & 01) { l ^= b << 61; h ^= b >> 3; } if (top3b & 02) { l ^= b << 62; h ^= b >> 2; } if (top3b & 04) { l ^= b << 63; h ^= b >> 1; } *r1 = h; *r0 = l; } # endif /* * Product of two polynomials a, b each with degree < 2 * BN_BITS2 - 1, * result is a polynomial r with degree < 4 * BN_BITS2 - 1 The caller MUST * ensure that the variables have the right amount of space allocated. */ static void bn_GF2m_mul_2x2(BN_ULONG *r, const BN_ULONG a1, const BN_ULONG a0, const BN_ULONG b1, const BN_ULONG b0) { BN_ULONG m1, m0; /* r[3] = h1, r[2] = h0; r[1] = l1; r[0] = l0 */ bn_GF2m_mul_1x1(r + 3, r + 2, a1, b1); bn_GF2m_mul_1x1(r + 1, r, a0, b0); bn_GF2m_mul_1x1(&m1, &m0, a0 ^ a1, b0 ^ b1); /* Correction on m1 ^= l1 ^ h1; m0 ^= l0 ^ h0; */ r[2] ^= m1 ^ r[1] ^ r[3]; /* h0 ^= m1 ^ l1 ^ h1; */ r[1] = r[3] ^ r[2] ^ r[0] ^ m1 ^ m0; /* l1 ^= l0 ^ h0 ^ m0; */ } # else void bn_GF2m_mul_2x2(BN_ULONG *r, BN_ULONG a1, BN_ULONG a0, BN_ULONG b1, BN_ULONG b0); # endif /* * Add polynomials a and b and store result in r; r could be a or b, a and b * could be equal; r is the bitwise XOR of a and b. */ int BN_GF2m_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b) { int i; const BIGNUM *at, *bt; bn_check_top(a); bn_check_top(b); if (a->top < b->top) { at = b; bt = a; } else { at = a; bt = b; } if (bn_wexpand(r, at->top) == NULL) return 0; for (i = 0; i < bt->top; i++) { r->d[i] = at->d[i] ^ bt->d[i]; } for (; i < at->top; i++) { r->d[i] = at->d[i]; } r->top = at->top; bn_correct_top(r); return 1; } /*- * Some functions allow for representation of the irreducible polynomials * as an int[], say p. The irreducible f(t) is then of the form: * t^p[0] + t^p[1] + ... + t^p[k] * where m = p[0] > p[1] > ... > p[k] = 0. */ /* Performs modular reduction of a and store result in r. r could be a. */ int BN_GF2m_mod_arr(BIGNUM *r, const BIGNUM *a, const int p[]) { int j, k; int n, dN, d0, d1; BN_ULONG zz, *z; bn_check_top(a); if (!p[0]) { /* reduction mod 1 => return 0 */ BN_zero(r); return 1; } /* * Since the algorithm does reduction in the r value, if a != r, copy the * contents of a into r so we can do reduction in r. */ if (a != r) { if (!bn_wexpand(r, a->top)) return 0; for (j = 0; j < a->top; j++) { r->d[j] = a->d[j]; } r->top = a->top; } z = r->d; /* start reduction */ dN = p[0] / BN_BITS2; for (j = r->top - 1; j > dN;) { zz = z[j]; if (z[j] == 0) { j--; continue; } z[j] = 0; for (k = 1; p[k] != 0; k++) { /* reducing component t^p[k] */ n = p[0] - p[k]; d0 = n % BN_BITS2; d1 = BN_BITS2 - d0; n /= BN_BITS2; z[j - n] ^= (zz >> d0); if (d0) z[j - n - 1] ^= (zz << d1); } /* reducing component t^0 */ n = dN; d0 = p[0] % BN_BITS2; d1 = BN_BITS2 - d0; z[j - n] ^= (zz >> d0); if (d0) z[j - n - 1] ^= (zz << d1); } /* final round of reduction */ while (j == dN) { d0 = p[0] % BN_BITS2; zz = z[dN] >> d0; if (zz == 0) break; d1 = BN_BITS2 - d0; /* clear up the top d1 bits */ if (d0) z[dN] = (z[dN] << d1) >> d1; else z[dN] = 0; z[0] ^= zz; /* reduction t^0 component */ for (k = 1; p[k] != 0; k++) { BN_ULONG tmp_ulong; /* reducing component t^p[k] */ n = p[k] / BN_BITS2; d0 = p[k] % BN_BITS2; d1 = BN_BITS2 - d0; z[n] ^= (zz << d0); if (d0 && (tmp_ulong = zz >> d1)) z[n + 1] ^= tmp_ulong; } } bn_correct_top(r); return 1; } /* * Performs modular reduction of a by p and store result in r. r could be a. * This function calls down to the BN_GF2m_mod_arr implementation; this wrapper * function is only provided for convenience; for best performance, use the * BN_GF2m_mod_arr function. */ int BN_GF2m_mod(BIGNUM *r, const BIGNUM *a, const BIGNUM *p) { int ret = 0; int arr[6]; bn_check_top(a); bn_check_top(p); ret = BN_GF2m_poly2arr(p, arr, OSSL_NELEM(arr)); if (!ret || ret > (int)OSSL_NELEM(arr)) { BNerr(BN_F_BN_GF2M_MOD, BN_R_INVALID_LENGTH); return 0; } ret = BN_GF2m_mod_arr(r, a, arr); bn_check_top(r); return ret; } /* * Compute the product of two polynomials a and b, reduce modulo p, and store * the result in r. r could be a or b; a could be b. */ int BN_GF2m_mod_mul_arr(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const int p[], BN_CTX *ctx) { int zlen, i, j, k, ret = 0; BIGNUM *s; BN_ULONG x1, x0, y1, y0, zz[4]; bn_check_top(a); bn_check_top(b); if (a == b) { return BN_GF2m_mod_sqr_arr(r, a, p, ctx); } BN_CTX_start(ctx); if ((s = BN_CTX_get(ctx)) == NULL) goto err; zlen = a->top + b->top + 4; if (!bn_wexpand(s, zlen)) goto err; s->top = zlen; for (i = 0; i < zlen; i++) s->d[i] = 0; for (j = 0; j < b->top; j += 2) { y0 = b->d[j]; y1 = ((j + 1) == b->top) ? 0 : b->d[j + 1]; for (i = 0; i < a->top; i += 2) { x0 = a->d[i]; x1 = ((i + 1) == a->top) ? 0 : a->d[i + 1]; bn_GF2m_mul_2x2(zz, x1, x0, y1, y0); for (k = 0; k < 4; k++) s->d[i + j + k] ^= zz[k]; } } bn_correct_top(s); if (BN_GF2m_mod_arr(r, s, p)) ret = 1; bn_check_top(r); err: BN_CTX_end(ctx); return ret; } /* * Compute the product of two polynomials a and b, reduce modulo p, and store * the result in r. r could be a or b; a could equal b. This function calls * down to the BN_GF2m_mod_mul_arr implementation; this wrapper function is * only provided for convenience; for best performance, use the * BN_GF2m_mod_mul_arr function. */ int BN_GF2m_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *p, BN_CTX *ctx) { int ret = 0; const int max = BN_num_bits(p) + 1; int *arr = NULL; bn_check_top(a); bn_check_top(b); bn_check_top(p); if ((arr = OPENSSL_malloc(sizeof(*arr) * max)) == NULL) goto err; ret = BN_GF2m_poly2arr(p, arr, max); if (!ret || ret > max) { BNerr(BN_F_BN_GF2M_MOD_MUL, BN_R_INVALID_LENGTH); goto err; } ret = BN_GF2m_mod_mul_arr(r, a, b, arr, ctx); bn_check_top(r); err: OPENSSL_free(arr); return ret; } /* Square a, reduce the result mod p, and store it in a. r could be a. */ int BN_GF2m_mod_sqr_arr(BIGNUM *r, const BIGNUM *a, const int p[], BN_CTX *ctx) { int i, ret = 0; BIGNUM *s; bn_check_top(a); BN_CTX_start(ctx); if ((s = BN_CTX_get(ctx)) == NULL) return 0; if (!bn_wexpand(s, 2 * a->top)) goto err; for (i = a->top - 1; i >= 0; i--) { s->d[2 * i + 1] = SQR1(a->d[i]); s->d[2 * i] = SQR0(a->d[i]); } s->top = 2 * a->top; bn_correct_top(s); if (!BN_GF2m_mod_arr(r, s, p)) goto err; bn_check_top(r); ret = 1; err: BN_CTX_end(ctx); return ret; } /* * Square a, reduce the result mod p, and store it in a. r could be a. This * function calls down to the BN_GF2m_mod_sqr_arr implementation; this * wrapper function is only provided for convenience; for best performance, * use the BN_GF2m_mod_sqr_arr function. */ int BN_GF2m_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { int ret = 0; const int max = BN_num_bits(p) + 1; int *arr = NULL; bn_check_top(a); bn_check_top(p); if ((arr = OPENSSL_malloc(sizeof(*arr) * max)) == NULL) goto err; ret = BN_GF2m_poly2arr(p, arr, max); if (!ret || ret > max) { BNerr(BN_F_BN_GF2M_MOD_SQR, BN_R_INVALID_LENGTH); goto err; } ret = BN_GF2m_mod_sqr_arr(r, a, arr, ctx); bn_check_top(r); err: OPENSSL_free(arr); return ret; } /* * Invert a, reduce modulo p, and store the result in r. r could be a. Uses * Modified Almost Inverse Algorithm (Algorithm 10) from Hankerson, D., * Hernandez, J.L., and Menezes, A. "Software Implementation of Elliptic * Curve Cryptography Over Binary Fields". */ int BN_GF2m_mod_inv(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { BIGNUM *b, *c = NULL, *u = NULL, *v = NULL, *tmp; int ret = 0; bn_check_top(a); bn_check_top(p); BN_CTX_start(ctx); if ((b = BN_CTX_get(ctx)) == NULL) goto err; if ((c = BN_CTX_get(ctx)) == NULL) goto err; if ((u = BN_CTX_get(ctx)) == NULL) goto err; if ((v = BN_CTX_get(ctx)) == NULL) goto err; if (!BN_GF2m_mod(u, a, p)) goto err; if (BN_is_zero(u)) goto err; if (!BN_copy(v, p)) goto err; # if 0 if (!BN_one(b)) goto err; while (1) { while (!BN_is_odd(u)) { if (BN_is_zero(u)) goto err; if (!BN_rshift1(u, u)) goto err; if (BN_is_odd(b)) { if (!BN_GF2m_add(b, b, p)) goto err; } if (!BN_rshift1(b, b)) goto err; } if (BN_abs_is_word(u, 1)) break; if (BN_num_bits(u) < BN_num_bits(v)) { tmp = u; u = v; v = tmp; tmp = b; b = c; c = tmp; } if (!BN_GF2m_add(u, u, v)) goto err; if (!BN_GF2m_add(b, b, c)) goto err; } # else { int i; int ubits = BN_num_bits(u); int vbits = BN_num_bits(v); /* v is copy of p */ int top = p->top; BN_ULONG *udp, *bdp, *vdp, *cdp; bn_wexpand(u, top); udp = u->d; for (i = u->top; i < top; i++) udp[i] = 0; u->top = top; bn_wexpand(b, top); bdp = b->d; bdp[0] = 1; for (i = 1; i < top; i++) bdp[i] = 0; b->top = top; bn_wexpand(c, top); cdp = c->d; for (i = 0; i < top; i++) cdp[i] = 0; c->top = top; vdp = v->d; /* It pays off to "cache" *->d pointers, * because it allows optimizer to be more * aggressive. But we don't have to "cache" * p->d, because *p is declared 'const'... */ while (1) { while (ubits && !(udp[0] & 1)) { BN_ULONG u0, u1, b0, b1, mask; u0 = udp[0]; b0 = bdp[0]; mask = (BN_ULONG)0 - (b0 & 1); b0 ^= p->d[0] & mask; for (i = 0; i < top - 1; i++) { u1 = udp[i + 1]; udp[i] = ((u0 >> 1) | (u1 << (BN_BITS2 - 1))) & BN_MASK2; u0 = u1; b1 = bdp[i + 1] ^ (p->d[i + 1] & mask); bdp[i] = ((b0 >> 1) | (b1 << (BN_BITS2 - 1))) & BN_MASK2; b0 = b1; } udp[i] = u0 >> 1; bdp[i] = b0 >> 1; ubits--; } if (ubits <= BN_BITS2) { if (udp[0] == 0) /* poly was reducible */ goto err; if (udp[0] == 1) break; } if (ubits < vbits) { i = ubits; ubits = vbits; vbits = i; tmp = u; u = v; v = tmp; tmp = b; b = c; c = tmp; udp = vdp; vdp = v->d; bdp = cdp; cdp = c->d; } for (i = 0; i < top; i++) { udp[i] ^= vdp[i]; bdp[i] ^= cdp[i]; } if (ubits == vbits) { BN_ULONG ul; int utop = (ubits - 1) / BN_BITS2; while ((ul = udp[utop]) == 0 && utop) utop--; ubits = utop * BN_BITS2 + BN_num_bits_word(ul); } } bn_correct_top(b); } # endif if (!BN_copy(r, b)) goto err; bn_check_top(r); ret = 1; err: # ifdef BN_DEBUG /* BN_CTX_end would complain about the * expanded form */ bn_correct_top(c); bn_correct_top(u); bn_correct_top(v); # endif BN_CTX_end(ctx); return ret; } /* * Invert xx, reduce modulo p, and store the result in r. r could be xx. * This function calls down to the BN_GF2m_mod_inv implementation; this * wrapper function is only provided for convenience; for best performance, * use the BN_GF2m_mod_inv function. */ int BN_GF2m_mod_inv_arr(BIGNUM *r, const BIGNUM *xx, const int p[], BN_CTX *ctx) { BIGNUM *field; int ret = 0; bn_check_top(xx); BN_CTX_start(ctx); if ((field = BN_CTX_get(ctx)) == NULL) goto err; if (!BN_GF2m_arr2poly(p, field)) goto err; ret = BN_GF2m_mod_inv(r, xx, field, ctx); bn_check_top(r); err: BN_CTX_end(ctx); return ret; } # ifndef OPENSSL_SUN_GF2M_DIV /* * Divide y by x, reduce modulo p, and store the result in r. r could be x * or y, x could equal y. */ int BN_GF2m_mod_div(BIGNUM *r, const BIGNUM *y, const BIGNUM *x, const BIGNUM *p, BN_CTX *ctx) { BIGNUM *xinv = NULL; int ret = 0; bn_check_top(y); bn_check_top(x); bn_check_top(p); BN_CTX_start(ctx); xinv = BN_CTX_get(ctx); if (xinv == NULL) goto err; if (!BN_GF2m_mod_inv(xinv, x, p, ctx)) goto err; if (!BN_GF2m_mod_mul(r, y, xinv, p, ctx)) goto err; bn_check_top(r); ret = 1; err: BN_CTX_end(ctx); return ret; } # else /* * Divide y by x, reduce modulo p, and store the result in r. r could be x * or y, x could equal y. Uses algorithm Modular_Division_GF(2^m) from * Chang-Shantz, S. "From Euclid's GCD to Montgomery Multiplication to the * Great Divide". */ int BN_GF2m_mod_div(BIGNUM *r, const BIGNUM *y, const BIGNUM *x, const BIGNUM *p, BN_CTX *ctx) { BIGNUM *a, *b, *u, *v; int ret = 0; bn_check_top(y); bn_check_top(x); bn_check_top(p); BN_CTX_start(ctx); a = BN_CTX_get(ctx); b = BN_CTX_get(ctx); u = BN_CTX_get(ctx); v = BN_CTX_get(ctx); if (v == NULL) goto err; /* reduce x and y mod p */ if (!BN_GF2m_mod(u, y, p)) goto err; if (!BN_GF2m_mod(a, x, p)) goto err; if (!BN_copy(b, p)) goto err; while (!BN_is_odd(a)) { if (!BN_rshift1(a, a)) goto err; if (BN_is_odd(u)) if (!BN_GF2m_add(u, u, p)) goto err; if (!BN_rshift1(u, u)) goto err; } do { if (BN_GF2m_cmp(b, a) > 0) { if (!BN_GF2m_add(b, b, a)) goto err; if (!BN_GF2m_add(v, v, u)) goto err; do { if (!BN_rshift1(b, b)) goto err; if (BN_is_odd(v)) if (!BN_GF2m_add(v, v, p)) goto err; if (!BN_rshift1(v, v)) goto err; } while (!BN_is_odd(b)); } else if (BN_abs_is_word(a, 1)) break; else { if (!BN_GF2m_add(a, a, b)) goto err; if (!BN_GF2m_add(u, u, v)) goto err; do { if (!BN_rshift1(a, a)) goto err; if (BN_is_odd(u)) if (!BN_GF2m_add(u, u, p)) goto err; if (!BN_rshift1(u, u)) goto err; } while (!BN_is_odd(a)); } } while (1); if (!BN_copy(r, u)) goto err; bn_check_top(r); ret = 1; err: BN_CTX_end(ctx); return ret; } # endif /* * Divide yy by xx, reduce modulo p, and store the result in r. r could be xx * * or yy, xx could equal yy. This function calls down to the * BN_GF2m_mod_div implementation; this wrapper function is only provided for * convenience; for best performance, use the BN_GF2m_mod_div function. */ int BN_GF2m_mod_div_arr(BIGNUM *r, const BIGNUM *yy, const BIGNUM *xx, const int p[], BN_CTX *ctx) { BIGNUM *field; int ret = 0; bn_check_top(yy); bn_check_top(xx); BN_CTX_start(ctx); if ((field = BN_CTX_get(ctx)) == NULL) goto err; if (!BN_GF2m_arr2poly(p, field)) goto err; ret = BN_GF2m_mod_div(r, yy, xx, field, ctx); bn_check_top(r); err: BN_CTX_end(ctx); return ret; } /* * Compute the bth power of a, reduce modulo p, and store the result in r. r * could be a. Uses simple square-and-multiply algorithm A.5.1 from IEEE * P1363. */ int BN_GF2m_mod_exp_arr(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const int p[], BN_CTX *ctx) { int ret = 0, i, n; BIGNUM *u; bn_check_top(a); bn_check_top(b); if (BN_is_zero(b)) return (BN_one(r)); if (BN_abs_is_word(b, 1)) return (BN_copy(r, a) != NULL); BN_CTX_start(ctx); if ((u = BN_CTX_get(ctx)) == NULL) goto err; if (!BN_GF2m_mod_arr(u, a, p)) goto err; n = BN_num_bits(b) - 1; for (i = n - 1; i >= 0; i--) { if (!BN_GF2m_mod_sqr_arr(u, u, p, ctx)) goto err; if (BN_is_bit_set(b, i)) { if (!BN_GF2m_mod_mul_arr(u, u, a, p, ctx)) goto err; } } if (!BN_copy(r, u)) goto err; bn_check_top(r); ret = 1; err: BN_CTX_end(ctx); return ret; } /* * Compute the bth power of a, reduce modulo p, and store the result in r. r * could be a. This function calls down to the BN_GF2m_mod_exp_arr * implementation; this wrapper function is only provided for convenience; * for best performance, use the BN_GF2m_mod_exp_arr function. */ int BN_GF2m_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *p, BN_CTX *ctx) { int ret = 0; const int max = BN_num_bits(p) + 1; int *arr = NULL; bn_check_top(a); bn_check_top(b); bn_check_top(p); if ((arr = OPENSSL_malloc(sizeof(*arr) * max)) == NULL) goto err; ret = BN_GF2m_poly2arr(p, arr, max); if (!ret || ret > max) { BNerr(BN_F_BN_GF2M_MOD_EXP, BN_R_INVALID_LENGTH); goto err; } ret = BN_GF2m_mod_exp_arr(r, a, b, arr, ctx); bn_check_top(r); err: OPENSSL_free(arr); return ret; } /* * Compute the square root of a, reduce modulo p, and store the result in r. * r could be a. Uses exponentiation as in algorithm A.4.1 from IEEE P1363. */ int BN_GF2m_mod_sqrt_arr(BIGNUM *r, const BIGNUM *a, const int p[], BN_CTX *ctx) { int ret = 0; BIGNUM *u; bn_check_top(a); if (!p[0]) { /* reduction mod 1 => return 0 */ BN_zero(r); return 1; } BN_CTX_start(ctx); if ((u = BN_CTX_get(ctx)) == NULL) goto err; if (!BN_set_bit(u, p[0] - 1)) goto err; ret = BN_GF2m_mod_exp_arr(r, a, u, p, ctx); bn_check_top(r); err: BN_CTX_end(ctx); return ret; } /* * Compute the square root of a, reduce modulo p, and store the result in r. * r could be a. This function calls down to the BN_GF2m_mod_sqrt_arr * implementation; this wrapper function is only provided for convenience; * for best performance, use the BN_GF2m_mod_sqrt_arr function. */ int BN_GF2m_mod_sqrt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { int ret = 0; const int max = BN_num_bits(p) + 1; int *arr = NULL; bn_check_top(a); bn_check_top(p); if ((arr = OPENSSL_malloc(sizeof(*arr) * max)) == NULL) goto err; ret = BN_GF2m_poly2arr(p, arr, max); if (!ret || ret > max) { BNerr(BN_F_BN_GF2M_MOD_SQRT, BN_R_INVALID_LENGTH); goto err; } ret = BN_GF2m_mod_sqrt_arr(r, a, arr, ctx); bn_check_top(r); err: OPENSSL_free(arr); return ret; } /* * Find r such that r^2 + r = a mod p. r could be a. If no r exists returns * 0. Uses algorithms A.4.7 and A.4.6 from IEEE P1363. */ int BN_GF2m_mod_solve_quad_arr(BIGNUM *r, const BIGNUM *a_, const int p[], BN_CTX *ctx) { int ret = 0, count = 0, j; BIGNUM *a, *z, *rho, *w, *w2, *tmp; bn_check_top(a_); if (!p[0]) { /* reduction mod 1 => return 0 */ BN_zero(r); return 1; } BN_CTX_start(ctx); a = BN_CTX_get(ctx); z = BN_CTX_get(ctx); w = BN_CTX_get(ctx); if (w == NULL) goto err; if (!BN_GF2m_mod_arr(a, a_, p)) goto err; if (BN_is_zero(a)) { BN_zero(r); ret = 1; goto err; } if (p[0] & 0x1) { /* m is odd */ /* compute half-trace of a */ if (!BN_copy(z, a)) goto err; for (j = 1; j <= (p[0] - 1) / 2; j++) { if (!BN_GF2m_mod_sqr_arr(z, z, p, ctx)) goto err; if (!BN_GF2m_mod_sqr_arr(z, z, p, ctx)) goto err; if (!BN_GF2m_add(z, z, a)) goto err; } } else { /* m is even */ rho = BN_CTX_get(ctx); w2 = BN_CTX_get(ctx); tmp = BN_CTX_get(ctx); if (tmp == NULL) goto err; do { if (!BN_rand(rho, p[0], 0, 0)) goto err; if (!BN_GF2m_mod_arr(rho, rho, p)) goto err; BN_zero(z); if (!BN_copy(w, rho)) goto err; for (j = 1; j <= p[0] - 1; j++) { if (!BN_GF2m_mod_sqr_arr(z, z, p, ctx)) goto err; if (!BN_GF2m_mod_sqr_arr(w2, w, p, ctx)) goto err; if (!BN_GF2m_mod_mul_arr(tmp, w2, a, p, ctx)) goto err; if (!BN_GF2m_add(z, z, tmp)) goto err; if (!BN_GF2m_add(w, w2, rho)) goto err; } count++; } while (BN_is_zero(w) && (count < MAX_ITERATIONS)); if (BN_is_zero(w)) { BNerr(BN_F_BN_GF2M_MOD_SOLVE_QUAD_ARR, BN_R_TOO_MANY_ITERATIONS); goto err; } } if (!BN_GF2m_mod_sqr_arr(w, z, p, ctx)) goto err; if (!BN_GF2m_add(w, z, w)) goto err; if (BN_GF2m_cmp(w, a)) { BNerr(BN_F_BN_GF2M_MOD_SOLVE_QUAD_ARR, BN_R_NO_SOLUTION); goto err; } if (!BN_copy(r, z)) goto err; bn_check_top(r); ret = 1; err: BN_CTX_end(ctx); return ret; } /* * Find r such that r^2 + r = a mod p. r could be a. If no r exists returns * 0. This function calls down to the BN_GF2m_mod_solve_quad_arr * implementation; this wrapper function is only provided for convenience; * for best performance, use the BN_GF2m_mod_solve_quad_arr function. */ int BN_GF2m_mod_solve_quad(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) { int ret = 0; const int max = BN_num_bits(p) + 1; int *arr = NULL; bn_check_top(a); bn_check_top(p); if ((arr = OPENSSL_malloc(sizeof(*arr) * max)) == NULL) goto err; ret = BN_GF2m_poly2arr(p, arr, max); if (!ret || ret > max) { BNerr(BN_F_BN_GF2M_MOD_SOLVE_QUAD, BN_R_INVALID_LENGTH); goto err; } ret = BN_GF2m_mod_solve_quad_arr(r, a, arr, ctx); bn_check_top(r); err: OPENSSL_free(arr); return ret; } /* * Convert the bit-string representation of a polynomial ( \sum_{i=0}^n a_i * * x^i) into an array of integers corresponding to the bits with non-zero * coefficient. Array is terminated with -1. Up to max elements of the array * will be filled. Return value is total number of array elements that would * be filled if array was large enough. */ int BN_GF2m_poly2arr(const BIGNUM *a, int p[], int max) { int i, j, k = 0; BN_ULONG mask; if (BN_is_zero(a)) return 0; for (i = a->top - 1; i >= 0; i--) { if (!a->d[i]) /* skip word if a->d[i] == 0 */ continue; mask = BN_TBIT; for (j = BN_BITS2 - 1; j >= 0; j--) { if (a->d[i] & mask) { if (k < max) p[k] = BN_BITS2 * i + j; k++; } mask >>= 1; } } if (k < max) { p[k] = -1; k++; } return k; } /* * Convert the coefficient array representation of a polynomial to a * bit-string. The array must be terminated by -1. */ int BN_GF2m_arr2poly(const int p[], BIGNUM *a) { int i; bn_check_top(a); BN_zero(a); for (i = 0; p[i] != -1; i++) { if (BN_set_bit(a, p[i]) == 0) return 0; } bn_check_top(a); return 1; } #endif
./CrossVul/dataset_final_sorted/CWE-399/c/good_1493_0
crossvul-cpp_data_good_1415_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS IIIII X X EEEEE L % % SS I X X E L % % SSS I X EEE L % % SS I X X E L % % SSSSS IIIII X X EEEEE LLLLL % % % % % % Read/Write DEC SIXEL Format % % % % Software Design % % Hayaki Saito % % September 2014 % % Based on kmiya's sixel (2014-03-28) % % % % % % Copyright 1999-2019 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://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.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/pixel-private.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/splay-tree.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/module.h" #include "MagickCore/threshold.h" #include "MagickCore/utility.h" /* Definitions */ #define SIXEL_PALETTE_MAX 256 #define SIXEL_OUTPUT_PACKET_SIZE 1024 /* Macros */ #define SIXEL_RGB(r, g, b) ((int) (((ssize_t) (r) << 16) + ((g) << 8) + (b))) #define SIXEL_PALVAL(n,a,m) ((int) (((ssize_t) (n) * (a) + ((m) / 2)) / (m))) #define SIXEL_XRGB(r,g,b) SIXEL_RGB(SIXEL_PALVAL(r, 255, 100), SIXEL_PALVAL(g, 255, 100), SIXEL_PALVAL(b, 255, 100)) /* Structure declarations. */ typedef struct sixel_node { struct sixel_node *next; int color; int left; int right; unsigned char *map; } sixel_node_t; typedef struct sixel_output { /* compatiblity flags */ /* 0: 7bit terminal, * 1: 8bit terminal */ unsigned char has_8bit_control; int save_pixel; int save_count; int active_palette; sixel_node_t *node_top; sixel_node_t *node_free; Image *image; int pos; unsigned char buffer[1]; } sixel_output_t; static int const sixel_default_color_table[] = { SIXEL_XRGB(0, 0, 0), /* 0 Black */ SIXEL_XRGB(20, 20, 80), /* 1 Blue */ SIXEL_XRGB(80, 13, 13), /* 2 Red */ SIXEL_XRGB(20, 80, 20), /* 3 Green */ SIXEL_XRGB(80, 20, 80), /* 4 Magenta */ SIXEL_XRGB(20, 80, 80), /* 5 Cyan */ SIXEL_XRGB(80, 80, 20), /* 6 Yellow */ SIXEL_XRGB(53, 53, 53), /* 7 Gray 50% */ SIXEL_XRGB(26, 26, 26), /* 8 Gray 25% */ SIXEL_XRGB(33, 33, 60), /* 9 Blue* */ SIXEL_XRGB(60, 26, 26), /* 10 Red* */ SIXEL_XRGB(33, 60, 33), /* 11 Green* */ SIXEL_XRGB(60, 33, 60), /* 12 Magenta* */ SIXEL_XRGB(33, 60, 60), /* 13 Cyan* */ SIXEL_XRGB(60, 60, 33), /* 14 Yellow* */ SIXEL_XRGB(80, 80, 80), /* 15 Gray 75% */ }; /* Forward declarations. */ static MagickBooleanType WriteSIXELImage(const ImageInfo *,Image *,ExceptionInfo *); static int hue_to_rgb(int n1, int n2, int hue) { const int HLSMAX = 100; if (hue < 0) { hue += HLSMAX; } if (hue > HLSMAX) { hue -= HLSMAX; } if (hue < (HLSMAX / 6)) { return (n1 + (((n2 - n1) * hue + (HLSMAX / 12)) / (HLSMAX / 6))); } if (hue < (HLSMAX / 2)) { return (n2); } if (hue < ((HLSMAX * 2) / 3)) { return (n1 + (((n2 - n1) * (((HLSMAX * 2) / 3) - hue) + (HLSMAX / 12))/(HLSMAX / 6))); } return (n1); } static int hls_to_rgb(int hue, int lum, int sat) { int R, G, B; int Magic1, Magic2; const int RGBMAX = 255; const int HLSMAX = 100; if (sat == 0) { R = G = B = (lum * RGBMAX) / HLSMAX; } else { if (lum <= (HLSMAX / 2)) { Magic2 = (int) (((ssize_t) lum * (HLSMAX + sat) + (HLSMAX / 2)) / HLSMAX); } else { Magic2 = (int) (lum + sat - (((ssize_t) lum * sat) + (HLSMAX / 2)) / HLSMAX); } Magic1 = 2 * lum - Magic2; R = (hue_to_rgb(Magic1, Magic2, hue + (HLSMAX / 3)) * RGBMAX + (HLSMAX / 2)) / HLSMAX; G = (hue_to_rgb(Magic1, Magic2, hue) * RGBMAX + (HLSMAX / 2)) / HLSMAX; B = (hue_to_rgb(Magic1, Magic2, hue - (HLSMAX / 3)) * RGBMAX + (HLSMAX/2)) / HLSMAX; } return SIXEL_RGB(R, G, B); } static unsigned char *get_params(unsigned char *p, int *param, int *len) { int n; *len = 0; while (*p != '\0') { while (*p == ' ' || *p == '\t') { p++; } if (isdigit((int) ((unsigned char) *p))) { for (n = 0; isdigit((int) ((unsigned char) *p)); p++) { n = (int) ((ssize_t) n * 10 + (*p - '0')); } if (*len < 10) { param[(*len)++] = n; } while (*p == ' ' || *p == '\t') { p++; } if (*p == ';') { p++; } } else if (*p == ';') { if (*len < 10) { param[(*len)++] = 0; } p++; } else break; } return p; } /* convert sixel data into indexed pixel bytes and palette data */ MagickBooleanType sixel_decode(Image *image, unsigned char /* in */ *p, /* sixel bytes */ unsigned char /* out */ **pixels, /* decoded pixels */ size_t /* out */ *pwidth, /* image width */ size_t /* out */ *pheight, /* image height */ unsigned char /* out */ **palette, /* ARGB palette */ size_t /* out */ *ncolors, /* palette size (<= 256) */ ExceptionInfo *exception) { int n, i, r, g, b, sixel_vertical_mask, c; int posision_x, posision_y; int max_x, max_y; int attributed_pan, attributed_pad; int attributed_ph, attributed_pv; int repeat_count, color_index, max_color_index = 2, background_color_index; int param[10]; int sixel_palet[SIXEL_PALETTE_MAX]; unsigned char *imbuf, *dmbuf; int imsx, imsy; int dmsx, dmsy; int y; size_t extent,offset; extent=strlen((char *) p); posision_x = posision_y = 0; max_x = max_y = 0; attributed_pan = 2; attributed_pad = 1; attributed_ph = attributed_pv = 0; repeat_count = 1; color_index = 0; background_color_index = 0; imsx = 2048; imsy = 2048; if (SetImageExtent(image,imsx,imsy,exception) == MagickFalse) return(MagickFalse); imbuf = (unsigned char *) AcquireQuantumMemory(imsx , imsy); if (imbuf == NULL) { return(MagickFalse); } for (n = 0; n < 16; n++) { sixel_palet[n] = sixel_default_color_table[n]; } /* colors 16-231 are a 6x6x6 color cube */ for (r = 0; r < 6; r++) { for (g = 0; g < 6; g++) { for (b = 0; b < 6; b++) { sixel_palet[n++] = SIXEL_RGB(r * 51, g * 51, b * 51); } } } /* colors 232-255 are a grayscale ramp, intentionally leaving out */ for (i = 0; i < 24; i++) { sixel_palet[n++] = SIXEL_RGB(i * 11, i * 11, i * 11); } for (; n < SIXEL_PALETTE_MAX; n++) { sixel_palet[n] = SIXEL_RGB(255, 255, 255); } (void) memset(imbuf, background_color_index, (size_t) imsx * imsy); while (*p != '\0') { if ((p[0] == '\033' && p[1] == 'P') || *p == 0x90) { if (*p == '\033') { p++; } p = get_params(++p, param, &n); if (*p == 'q') { p++; if (n > 0) { /* Pn1 */ switch(param[0]) { case 0: case 1: attributed_pad = 2; break; case 2: attributed_pad = 5; break; case 3: attributed_pad = 4; break; case 4: attributed_pad = 4; break; case 5: attributed_pad = 3; break; case 6: attributed_pad = 3; break; case 7: attributed_pad = 2; break; case 8: attributed_pad = 2; break; case 9: attributed_pad = 1; break; } } if (n > 2) { /* Pn3 */ if (param[2] == 0) { param[2] = 10; } attributed_pan = (int) (((ssize_t) attributed_pan * param[2]) / 10); attributed_pad = (int) (((ssize_t) attributed_pad * param[2]) / 10); if (attributed_pan <= 0) attributed_pan = 1; if (attributed_pad <= 0) attributed_pad = 1; } } } else if ((p[0] == '\033' && p[1] == '\\') || *p == 0x9C) { break; } else if (*p == '"') { /* DECGRA Set Raster Attributes " Pan; Pad; Ph; Pv */ p = get_params(++p, param, &n); if (n > 0) attributed_pad = param[0]; if (n > 1) attributed_pan = param[1]; if (n > 2 && param[2] > 0) attributed_ph = param[2]; if (n > 3 && param[3] > 0) attributed_pv = param[3]; if (attributed_pan <= 0) attributed_pan = 1; if (attributed_pad <= 0) attributed_pad = 1; if (imsx < attributed_ph || imsy < attributed_pv) { dmsx = imsx > attributed_ph ? imsx : attributed_ph; dmsy = imsy > attributed_pv ? imsy : attributed_pv; if (SetImageExtent(image,dmsx,dmsy,exception) == MagickFalse) break; dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx , dmsy); if (dmbuf == (unsigned char *) NULL) { imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); return (MagickFalse); } (void) memset(dmbuf, background_color_index, (size_t) dmsx * dmsy); for (y = 0; y < imsy; ++y) { (void) memcpy(dmbuf + dmsx * y, imbuf + imsx * y, imsx); } imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); imsx = dmsx; imsy = dmsy; imbuf = dmbuf; } } else if (*p == '!') { /* DECGRI Graphics Repeat Introducer ! Pn Ch */ p = get_params(++p, param, &n); if ((n > 0) && (param[0] > 0)) { repeat_count = param[0]; if (repeat_count > (ssize_t) extent) break; } } else if (*p == '#') { /* DECGCI Graphics Color Introducer # Pc; Pu; Px; Py; Pz */ p = get_params(++p, param, &n); if (n > 0) { if ((color_index = param[0]) < 0) { color_index = 0; } else if (color_index >= SIXEL_PALETTE_MAX) { color_index = SIXEL_PALETTE_MAX - 1; } } if (n > 4) { if (param[1] == 1) { /* HLS */ if (param[2] > 360) param[2] = 360; if (param[3] > 100) param[3] = 100; if (param[4] > 100) param[4] = 100; sixel_palet[color_index] = hls_to_rgb(param[2] * 100 / 360, param[3], param[4]); } else if (param[1] == 2) { /* RGB */ if (param[2] > 100) param[2] = 100; if (param[3] > 100) param[3] = 100; if (param[4] > 100) param[4] = 100; sixel_palet[color_index] = SIXEL_XRGB(param[2], param[3], param[4]); } } } else if (*p == '$') { /* DECGCR Graphics Carriage Return */ p++; posision_x = 0; repeat_count = 1; } else if (*p == '-') { /* DECGNL Graphics Next Line */ p++; posision_x = 0; posision_y += 6; repeat_count = 1; } else if (*p >= '?' && *p <= '\177') { if (imsx < (posision_x + repeat_count) || imsy < (posision_y + 6)) { int nx = imsx * 2; int ny = imsy * 2; while (nx < (posision_x + repeat_count) || ny < (posision_y + 6)) { nx *= 2; ny *= 2; } dmsx = nx; dmsy = ny; if (SetImageExtent(image,dmsx,dmsy,exception) == MagickFalse) break; dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx , dmsy); if (dmbuf == (unsigned char *) NULL) { imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); return (MagickFalse); } (void) memset(dmbuf, background_color_index, (size_t) dmsx * dmsy); for (y = 0; y < imsy; ++y) { (void) memcpy(dmbuf + dmsx * y, imbuf + imsx * y, imsx); } imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); imsx = dmsx; imsy = dmsy; imbuf = dmbuf; } if (color_index > max_color_index) { max_color_index = color_index; } if ((b = *(p++) - '?') == 0) { posision_x += repeat_count; } else { sixel_vertical_mask = 0x01; if (repeat_count <= 1) { for (i = 0; i < 6; i++) { if ((b & sixel_vertical_mask) != 0) { offset=(size_t) imsx * (posision_y + i) + posision_x; if (offset >= (size_t) imsx * imsy) { imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); return (MagickFalse); } imbuf[offset] = color_index; if (max_x < posision_x) { max_x = posision_x; } if (max_y < (posision_y + i)) { max_y = posision_y + i; } } sixel_vertical_mask <<= 1; } posision_x += 1; } else { /* repeat_count > 1 */ for (i = 0; i < 6; i++) { if ((b & sixel_vertical_mask) != 0) { c = sixel_vertical_mask << 1; for (n = 1; (i + n) < 6; n++) { if ((b & c) == 0) { break; } c <<= 1; } for (y = posision_y + i; y < posision_y + i + n; ++y) { offset=(size_t) imsx * y + posision_x; if (offset + repeat_count >= (size_t) imsx * imsy) { imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); return (MagickFalse); } (void) memset(imbuf + offset, color_index, repeat_count); } if (max_x < (posision_x + repeat_count - 1)) { max_x = posision_x + repeat_count - 1; } if (max_y < (posision_y + i + n - 1)) { max_y = posision_y + i + n - 1; } i += (n - 1); sixel_vertical_mask <<= (n - 1); } sixel_vertical_mask <<= 1; } posision_x += repeat_count; } } repeat_count = 1; } else { p++; } } if (++max_x < attributed_ph) { max_x = attributed_ph; } if (++max_y < attributed_pv) { max_y = attributed_pv; } if (imsx > max_x || imsy > max_y) { dmsx = max_x; dmsy = max_y; if (SetImageExtent(image,dmsx,dmsy,exception) == MagickFalse) { imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); return (MagickFalse); } if ((dmbuf = (unsigned char *) AcquireQuantumMemory(dmsx , dmsy)) == NULL) { imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); return (MagickFalse); } for (y = 0; y < dmsy; ++y) { (void) memcpy(dmbuf + dmsx * y, imbuf + imsx * y, dmsx); } imbuf = (unsigned char *) RelinquishMagickMemory(imbuf); imsx = dmsx; imsy = dmsy; imbuf = dmbuf; } *pixels = imbuf; *pwidth = imsx; *pheight = imsy; *ncolors = max_color_index + 1; *palette = (unsigned char *) AcquireQuantumMemory(*ncolors,4); if (*palette == (unsigned char *) NULL) return(MagickFalse); for (n = 0; n < (ssize_t) *ncolors; ++n) { (*palette)[n * 4 + 0] = sixel_palet[n] >> 16 & 0xff; (*palette)[n * 4 + 1] = sixel_palet[n] >> 8 & 0xff; (*palette)[n * 4 + 2] = sixel_palet[n] & 0xff; (*palette)[n * 4 + 3] = 0xff; } return(MagickTrue); } sixel_output_t *sixel_output_create(Image *image) { sixel_output_t *output; output = (sixel_output_t *) AcquireQuantumMemory(sizeof(sixel_output_t) + SIXEL_OUTPUT_PACKET_SIZE * 2, 1); if (output == (sixel_output_t *) NULL) return((sixel_output_t *) NULL); output->has_8bit_control = 0; output->save_pixel = 0; output->save_count = 0; output->active_palette = (-1); output->node_top = NULL; output->node_free = NULL; output->image = image; output->pos = 0; return output; } static void sixel_advance(sixel_output_t *context, int nwrite) { if ((context->pos += nwrite) >= SIXEL_OUTPUT_PACKET_SIZE) { WriteBlob(context->image,SIXEL_OUTPUT_PACKET_SIZE,context->buffer); memmove(context->buffer, context->buffer + SIXEL_OUTPUT_PACKET_SIZE, (context->pos -= SIXEL_OUTPUT_PACKET_SIZE)); } } static int sixel_put_flash(sixel_output_t *const context) { int n; int nwrite; #if defined(USE_VT240) /* VT240 Max 255 ? */ while (context->save_count > 255) { nwrite = spritf((char *)context->buffer + context->pos, "!255%c", context->save_pixel); if (nwrite <= 0) { return (-1); } sixel_advance(context, nwrite); context->save_count -= 255; } #endif /* defined(USE_VT240) */ if (context->save_count > 3) { /* DECGRI Graphics Repeat Introducer ! Pn Ch */ nwrite = sprintf((char *)context->buffer + context->pos, "!%d%c", context->save_count, context->save_pixel); if (nwrite <= 0) { return (-1); } sixel_advance(context, nwrite); } else { for (n = 0; n < context->save_count; n++) { context->buffer[context->pos] = (char)context->save_pixel; sixel_advance(context, 1); } } context->save_pixel = 0; context->save_count = 0; return 0; } static void sixel_put_pixel(sixel_output_t *const context, int pix) { if (pix < 0 || pix > '?') { pix = 0; } pix += '?'; if (pix == context->save_pixel) { context->save_count++; } else { sixel_put_flash(context); context->save_pixel = pix; context->save_count = 1; } } static void sixel_node_del(sixel_output_t *const context, sixel_node_t *np) { sixel_node_t *tp; if ((tp = context->node_top) == np) { context->node_top = np->next; } else { while (tp->next != NULL) { if (tp->next == np) { tp->next = np->next; break; } tp = tp->next; } } np->next = context->node_free; context->node_free = np; } static int sixel_put_node(sixel_output_t *const context, int x, sixel_node_t *np, int ncolors, int keycolor) { int nwrite; if (ncolors != 2 || keycolor == -1) { /* designate palette index */ if (context->active_palette != np->color) { nwrite = sprintf((char *)context->buffer + context->pos, "#%d", np->color); sixel_advance(context, nwrite); context->active_palette = np->color; } } for (; x < np->left; x++) { sixel_put_pixel(context, 0); } for (; x < np->right; x++) { sixel_put_pixel(context, np->map[x]); } sixel_put_flash(context); return x; } static MagickBooleanType sixel_encode_impl(unsigned char *pixels, size_t width,size_t height, unsigned char *palette, size_t ncolors, int keycolor, sixel_output_t *context) { #define RelinquishNodesAndMap \ while ((np = context->node_free) != NULL) { \ context->node_free = np->next; \ np=(sixel_node_t *) RelinquishMagickMemory(np); \ } \ map = (unsigned char *) RelinquishMagickMemory(map) int x, y, i, n, c; int left, right; int pix; unsigned char *map; sixel_node_t *np, *tp, top; int nwrite; size_t len; context->pos = 0; if (ncolors < 1) { return (MagickFalse); } len = ncolors * width; context->active_palette = (-1); if ((map = (unsigned char *)AcquireQuantumMemory(len, sizeof(unsigned char))) == NULL) { return (MagickFalse); } (void) memset(map, 0, len); if (context->has_8bit_control) { nwrite = sprintf((char *)context->buffer, "\x90" "0;0;0" "q"); } else { nwrite = sprintf((char *)context->buffer, "\x1bP" "0;0;0" "q"); } if (nwrite <= 0) { return (MagickFalse); } sixel_advance(context, nwrite); nwrite = sprintf((char *)context->buffer + context->pos, "\"1;1;%d;%d", (int) width, (int) height); if (nwrite <= 0) { RelinquishNodesAndMap; return (MagickFalse); } sixel_advance(context, nwrite); if (ncolors != 2 || keycolor == -1) { for (n = 0; n < (ssize_t) ncolors; n++) { /* DECGCI Graphics Color Introducer # Pc ; Pu; Px; Py; Pz */ nwrite = sprintf((char *)context->buffer + context->pos, "#%d;2;%d;%d;%d", n, (palette[n * 3 + 0] * 100 + 127) / 255, (palette[n * 3 + 1] * 100 + 127) / 255, (palette[n * 3 + 2] * 100 + 127) / 255); if (nwrite <= 0) { RelinquishNodesAndMap; return (MagickFalse); } sixel_advance(context, nwrite); if (nwrite <= 0) { RelinquishNodesAndMap; return (MagickFalse); } } } for (y = i = 0; y < (ssize_t) height; y++) { for (x = 0; x < (ssize_t) width; x++) { pix = pixels[y * width + x]; if (pix >= 0 && pix < (ssize_t) ncolors && pix != keycolor) { map[pix * width + x] |= (1 << i); } } if (++i < 6 && (y + 1) < (ssize_t) height) { continue; } for (c = 0; c < (ssize_t) ncolors; c++) { for (left = 0; left < (ssize_t) width; left++) { if (*(map + c * width + left) == 0) { continue; } for (right = left + 1; right < (ssize_t) width; right++) { if (*(map + c * width + right) != 0) { continue; } for (n = 1; (right + n) < (ssize_t) width; n++) { if (*(map + c * width + right + n) != 0) { break; } } if (n >= 10 || right + n >= (ssize_t) width) { break; } right = right + n - 1; } if ((np = context->node_free) != NULL) { context->node_free = np->next; } else if ((np = (sixel_node_t *)AcquireMagickMemory(sizeof(sixel_node_t))) == NULL) { RelinquishNodesAndMap; return (MagickFalse); } np->color = c; np->left = left; np->right = right; np->map = map + c * width; top.next = context->node_top; tp = &top; while (tp->next != NULL) { if (np->left < tp->next->left) { break; } if (np->left == tp->next->left && np->right > tp->next->right) { break; } tp = tp->next; } np->next = tp->next; tp->next = np; context->node_top = top.next; left = right - 1; } } for (x = 0; (np = context->node_top) != NULL;) { if (x > np->left) { /* DECGCR Graphics Carriage Return */ context->buffer[context->pos] = '$'; sixel_advance(context, 1); x = 0; } x = sixel_put_node(context, x, np, (int) ncolors, keycolor); sixel_node_del(context, np); np = context->node_top; while (np != NULL) { if (np->left < x) { np = np->next; continue; } x = sixel_put_node(context, x, np, (int) ncolors, keycolor); sixel_node_del(context, np); np = context->node_top; } } /* DECGNL Graphics Next Line */ context->buffer[context->pos] = '-'; sixel_advance(context, 1); if (nwrite <= 0) { RelinquishNodesAndMap; return (MagickFalse); } i = 0; (void) memset(map, 0, len); } if (context->has_8bit_control) { context->buffer[context->pos] = 0x9c; sixel_advance(context, 1); } else { context->buffer[context->pos] = 0x1b; context->buffer[context->pos + 1] = '\\'; sixel_advance(context, 2); } if (nwrite <= 0) { RelinquishNodesAndMap; return (MagickFalse); } /* flush buffer */ if (context->pos > 0) { WriteBlob(context->image,context->pos,context->buffer); } RelinquishNodesAndMap; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s S I X E L % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsSIXEL() returns MagickTrue if the image format type, identified by the % magick string, is SIXEL. % % The format of the IsSIXEL method is: % % MagickBooleanType IsSIXEL(const unsigned char *magick, % const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. or % blob. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsSIXEL(const unsigned char *magick, const size_t length) { const unsigned char *end = magick + length; if (length < 3) return(MagickFalse); if (*magick == 0x90 || (*magick == 0x1b && *++magick == 'P')) { while (++magick != end) { if (*magick == 'q') return(MagickTrue); if (!(*magick >= '0' && *magick <= '9') && *magick != ';') return(MagickFalse); } } return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d S I X E L I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadSIXELImage() reads an X11 pixmap 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 ReadSIXELImage method is: % % Image *ReadSIXELImage(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 *ReadSIXELImage(const ImageInfo *image_info,ExceptionInfo *exception) { char *sixel_buffer; Image *image; MagickBooleanType status; register char *p; register ssize_t x; register Quantum *q; size_t length; ssize_t i, j, y; unsigned char *sixel_pixels, *sixel_palette; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read SIXEL file. */ length=MagickPathExtent; sixel_buffer=(char *) AcquireQuantumMemory((size_t) length+MagickPathExtent, sizeof(*sixel_buffer)); p=sixel_buffer; if (sixel_buffer != (char *) NULL) while (ReadBlobString(image,p) != (char *) NULL) { if ((*p == '#') && ((p == sixel_buffer) || (*(p-1) == '\n'))) continue; if ((*p == '}') && (*(p+1) == ';')) break; p+=strlen(p); if ((size_t) (p-sixel_buffer+MagickPathExtent+1) < length) continue; length<<=1; sixel_buffer=(char *) ResizeQuantumMemory(sixel_buffer,length+ MagickPathExtent+1,sizeof(*sixel_buffer)); if (sixel_buffer == (char *) NULL) break; p=sixel_buffer+strlen(sixel_buffer); } if (sixel_buffer == (char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); sixel_buffer[length]='\0'; /* Decode SIXEL */ if (sixel_decode(image,(unsigned char *) sixel_buffer,&sixel_pixels,&image->columns,&image->rows,&sixel_palette,&image->colors,exception) == MagickFalse) { sixel_buffer=(char *) RelinquishMagickMemory(sixel_buffer); sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels); ThrowReaderException(CorruptImageError,"CorruptImage"); } sixel_buffer=(char *) RelinquishMagickMemory(sixel_buffer); image->depth=24; image->storage_class=PseudoClass; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) { sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels); sixel_palette=(unsigned char *) RelinquishMagickMemory(sixel_palette); return(DestroyImageList(image)); } if (AcquireImageColormap(image,image->colors, exception) == MagickFalse) { sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels); sixel_palette=(unsigned char *) RelinquishMagickMemory(sixel_palette); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } for (i = 0; i < (ssize_t) image->colors; ++i) { image->colormap[i].red = ScaleCharToQuantum(sixel_palette[i * 4 + 0]); image->colormap[i].green = ScaleCharToQuantum(sixel_palette[i * 4 + 1]); image->colormap[i].blue = ScaleCharToQuantum(sixel_palette[i * 4 + 2]); } j=0; if (image_info->ping == MagickFalse) { /* Read image pixels. */ for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { j=(ssize_t) sixel_pixels[y * image->columns + x]; SetPixelIndex(image,j,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } if (y < (ssize_t) image->rows) { sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels); sixel_palette=(unsigned char *) RelinquishMagickMemory(sixel_palette); ThrowReaderException(CorruptImageError,"NotEnoughPixelData"); } } /* Relinquish resources. */ sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels); sixel_palette=(unsigned char *) RelinquishMagickMemory(sixel_palette); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r S I X E L I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterSIXELImage() adds attributes for the SIXEL 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 RegisterSIXELImage method is: % % size_t RegisterSIXELImage(void) % */ ModuleExport size_t RegisterSIXELImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("SIXEL","SIXEL","DEC SIXEL Graphics Format"); entry->decoder=(DecodeImageHandler *) ReadSIXELImage; entry->encoder=(EncodeImageHandler *) WriteSIXELImage; entry->magick=(IsImageFormatHandler *) IsSIXEL; entry->flags^=CoderAdjoinFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("SIXEL","SIX","DEC SIXEL Graphics Format"); entry->decoder=(DecodeImageHandler *) ReadSIXELImage; entry->encoder=(EncodeImageHandler *) WriteSIXELImage; entry->magick=(IsImageFormatHandler *) IsSIXEL; entry->flags^=CoderAdjoinFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r S I X E L I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterSIXELImage() removes format registrations made by the % SIXEL module from the list of supported formats. % % The format of the UnregisterSIXELImage method is: % % UnregisterSIXELImage(void) % */ ModuleExport void UnregisterSIXELImage(void) { (void) UnregisterMagickInfo("SIXEL"); (void) UnregisterMagickInfo("SIX"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e S I X E L I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteSIXELImage() writes an image to a file in the X pixmap format. % % The format of the WriteSIXELImage method is: % % MagickBooleanType WriteSIXELImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteSIXELImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { MagickBooleanType status; register const Quantum *q; register ssize_t i, x; ssize_t opacity, y; sixel_output_t *output; unsigned char sixel_palette[256*3], *sixel_pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace(image,sRGBColorspace,exception); opacity=(-1); if (image->alpha_trait == UndefinedPixelTrait) { if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) SetImageType(image,PaletteType,exception); } else { MagickRealType alpha, beta; /* Identify transparent colormap index. */ if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) SetImageType(image,PaletteBilevelAlphaType,exception); for (i=0; i < (ssize_t) image->colors; i++) if (image->colormap[i].alpha != OpaqueAlpha) { if (opacity < 0) { opacity=i; continue; } alpha=image->colormap[i].alpha; beta=image->colormap[opacity].alpha; if (alpha < beta) opacity=i; } if (opacity == -1) { (void) SetImageType(image,PaletteBilevelAlphaType,exception); for (i=0; i < (ssize_t) image->colors; i++) if (image->colormap[i].alpha != OpaqueAlpha) { if (opacity < 0) { opacity=i; continue; } alpha=image->colormap[i].alpha; beta=image->colormap[opacity].alpha; if (alpha < beta) opacity=i; } } if (opacity >= 0) { image->colormap[opacity].red=image->transparent_color.red; image->colormap[opacity].green=image->transparent_color.green; image->colormap[opacity].blue=image->transparent_color.blue; } } /* SIXEL header. */ for (i=0; i < (ssize_t) image->colors; i++) { sixel_palette[3*i+0]=ScaleQuantumToChar(image->colormap[i].red); sixel_palette[3*i+1]=ScaleQuantumToChar(image->colormap[i].green); sixel_palette[3*i+2]=ScaleQuantumToChar(image->colormap[i].blue); } /* Define SIXEL pixels. */ output = sixel_output_create(image); if (output == (sixel_output_t *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); sixel_pixels=(unsigned char *) AcquireQuantumMemory(image->columns, image->rows*sizeof(*sixel_pixels)); if (sixel_pixels == (unsigned char *) NULL) { output = (sixel_output_t *) RelinquishMagickMemory(output); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } for (y=0; y < (ssize_t) image->rows; y++) { q=GetVirtualPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { sixel_pixels[y*image->columns+x]= ((ssize_t) GetPixelIndex(image,q)); q+=GetPixelChannels(image); } } status = sixel_encode_impl(sixel_pixels,image->columns,image->rows, sixel_palette,image->colors,-1,output); sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels); output=(sixel_output_t *) RelinquishMagickMemory(output); (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-399/c/good_1415_0
crossvul-cpp_data_good_5721_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. * * The User Datagram Protocol (UDP). * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Arnt Gulbrandsen, <agulbra@nvg.unit.no> * Alan Cox, <alan@lxorguk.ukuu.org.uk> * Hirokazu Takahashi, <taka@valinux.co.jp> * * Fixes: * Alan Cox : verify_area() calls * Alan Cox : stopped close while in use off icmp * messages. Not a fix but a botch that * for udp at least is 'valid'. * Alan Cox : Fixed icmp handling properly * Alan Cox : Correct error for oversized datagrams * Alan Cox : Tidied select() semantics. * Alan Cox : udp_err() fixed properly, also now * select and read wake correctly on errors * Alan Cox : udp_send verify_area moved to avoid mem leak * Alan Cox : UDP can count its memory * Alan Cox : send to an unknown connection causes * an ECONNREFUSED off the icmp, but * does NOT close. * Alan Cox : Switched to new sk_buff handlers. No more backlog! * Alan Cox : Using generic datagram code. Even smaller and the PEEK * bug no longer crashes it. * Fred Van Kempen : Net2e support for sk->broadcast. * Alan Cox : Uses skb_free_datagram * Alan Cox : Added get/set sockopt support. * Alan Cox : Broadcasting without option set returns EACCES. * Alan Cox : No wakeup calls. Instead we now use the callbacks. * Alan Cox : Use ip_tos and ip_ttl * Alan Cox : SNMP Mibs * Alan Cox : MSG_DONTROUTE, and 0.0.0.0 support. * Matt Dillon : UDP length checks. * Alan Cox : Smarter af_inet used properly. * Alan Cox : Use new kernel side addressing. * Alan Cox : Incorrect return on truncated datagram receive. * Arnt Gulbrandsen : New udp_send and stuff * Alan Cox : Cache last socket * Alan Cox : Route cache * Jon Peatfield : Minor efficiency fix to sendto(). * Mike Shaver : RFC1122 checks. * Alan Cox : Nonblocking error fix. * Willy Konynenberg : Transparent proxying support. * Mike McLagan : Routing by source * David S. Miller : New socket lookup architecture. * Last socket cache retained as it * does have a high hit rate. * Olaf Kirch : Don't linearise iovec on sendmsg. * Andi Kleen : Some cleanups, cache destination entry * for connect. * Vitaly E. Lavrov : Transparent proxy revived after year coma. * Melvin Smith : Check msg_name not msg_namelen in sendto(), * return ENOTCONN for unconnected sockets (POSIX) * Janos Farkas : don't deliver multi/broadcasts to a different * bound-to-device socket * Hirokazu Takahashi : HW checksumming for outgoing UDP * datagrams. * Hirokazu Takahashi : sendfile() on UDP works now. * Arnaldo C. Melo : convert /proc/net/udp to seq_file * YOSHIFUJI Hideaki @USAGI and: Support IPV6_V6ONLY socket option, which * Alexey Kuznetsov: allow both IPv4 and IPv6 sockets to bind * a single port at the same time. * Derek Atkins <derek@ihtfp.com>: Add Encapulation Support * James Chapman : Add L2TP encapsulation type. * * * 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) "UDP: " fmt #include <asm/uaccess.h> #include <asm/ioctls.h> #include <linux/bootmem.h> #include <linux/highmem.h> #include <linux/swap.h> #include <linux/types.h> #include <linux/fcntl.h> #include <linux/module.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/igmp.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 <linux/slab.h> #include <net/tcp_states.h> #include <linux/skbuff.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <net/net_namespace.h> #include <net/icmp.h> #include <net/route.h> #include <net/checksum.h> #include <net/xfrm.h> #include <trace/events/udp.h> #include <linux/static_key.h> #include <trace/events/skb.h> #include <net/ll_poll.h> #include "udp_impl.h" struct udp_table udp_table __read_mostly; EXPORT_SYMBOL(udp_table); long sysctl_udp_mem[3] __read_mostly; EXPORT_SYMBOL(sysctl_udp_mem); int sysctl_udp_rmem_min __read_mostly; EXPORT_SYMBOL(sysctl_udp_rmem_min); int sysctl_udp_wmem_min __read_mostly; EXPORT_SYMBOL(sysctl_udp_wmem_min); atomic_long_t udp_memory_allocated; EXPORT_SYMBOL(udp_memory_allocated); #define MAX_UDP_PORTS 65536 #define PORTS_PER_CHAIN (MAX_UDP_PORTS / UDP_HTABLE_SIZE_MIN) static int udp_lib_lport_inuse(struct net *net, __u16 num, const struct udp_hslot *hslot, unsigned long *bitmap, struct sock *sk, int (*saddr_comp)(const struct sock *sk1, const struct sock *sk2), unsigned int log) { struct sock *sk2; struct hlist_nulls_node *node; kuid_t uid = sock_i_uid(sk); sk_nulls_for_each(sk2, node, &hslot->head) if (net_eq(sock_net(sk2), net) && sk2 != sk && (bitmap || udp_sk(sk2)->udp_port_hash == num) && (!sk2->sk_reuse || !sk->sk_reuse) && (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if || sk2->sk_bound_dev_if == sk->sk_bound_dev_if) && (!sk2->sk_reuseport || !sk->sk_reuseport || !uid_eq(uid, sock_i_uid(sk2))) && (*saddr_comp)(sk, sk2)) { if (bitmap) __set_bit(udp_sk(sk2)->udp_port_hash >> log, bitmap); else return 1; } return 0; } /* * Note: we still hold spinlock of primary hash chain, so no other writer * can insert/delete a socket with local_port == num */ static int udp_lib_lport_inuse2(struct net *net, __u16 num, struct udp_hslot *hslot2, struct sock *sk, int (*saddr_comp)(const struct sock *sk1, const struct sock *sk2)) { struct sock *sk2; struct hlist_nulls_node *node; kuid_t uid = sock_i_uid(sk); int res = 0; spin_lock(&hslot2->lock); udp_portaddr_for_each_entry(sk2, node, &hslot2->head) if (net_eq(sock_net(sk2), net) && sk2 != sk && (udp_sk(sk2)->udp_port_hash == num) && (!sk2->sk_reuse || !sk->sk_reuse) && (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if || sk2->sk_bound_dev_if == sk->sk_bound_dev_if) && (!sk2->sk_reuseport || !sk->sk_reuseport || !uid_eq(uid, sock_i_uid(sk2))) && (*saddr_comp)(sk, sk2)) { res = 1; break; } spin_unlock(&hslot2->lock); return res; } /** * udp_lib_get_port - UDP/-Lite port lookup for IPv4 and IPv6 * * @sk: socket struct in question * @snum: port number to look up * @saddr_comp: AF-dependent comparison of bound local IP addresses * @hash2_nulladdr: AF-dependent hash value in secondary hash chains, * with NULL address */ int udp_lib_get_port(struct sock *sk, unsigned short snum, int (*saddr_comp)(const struct sock *sk1, const struct sock *sk2), unsigned int hash2_nulladdr) { struct udp_hslot *hslot, *hslot2; struct udp_table *udptable = sk->sk_prot->h.udp_table; int error = 1; struct net *net = sock_net(sk); if (!snum) { int low, high, remaining; unsigned int rand; unsigned short first, last; DECLARE_BITMAP(bitmap, PORTS_PER_CHAIN); inet_get_local_port_range(&low, &high); remaining = (high - low) + 1; rand = net_random(); first = (((u64)rand * remaining) >> 32) + low; /* * force rand to be an odd multiple of UDP_HTABLE_SIZE */ rand = (rand | 1) * (udptable->mask + 1); last = first + udptable->mask + 1; do { hslot = udp_hashslot(udptable, net, first); bitmap_zero(bitmap, PORTS_PER_CHAIN); spin_lock_bh(&hslot->lock); udp_lib_lport_inuse(net, snum, hslot, bitmap, sk, saddr_comp, udptable->log); snum = first; /* * Iterate on all possible values of snum for this hash. * Using steps of an odd multiple of UDP_HTABLE_SIZE * give us randomization and full range coverage. */ do { if (low <= snum && snum <= high && !test_bit(snum >> udptable->log, bitmap) && !inet_is_reserved_local_port(snum)) goto found; snum += rand; } while (snum != first); spin_unlock_bh(&hslot->lock); } while (++first != last); goto fail; } else { hslot = udp_hashslot(udptable, net, snum); spin_lock_bh(&hslot->lock); if (hslot->count > 10) { int exist; unsigned int slot2 = udp_sk(sk)->udp_portaddr_hash ^ snum; slot2 &= udptable->mask; hash2_nulladdr &= udptable->mask; hslot2 = udp_hashslot2(udptable, slot2); if (hslot->count < hslot2->count) goto scan_primary_hash; exist = udp_lib_lport_inuse2(net, snum, hslot2, sk, saddr_comp); if (!exist && (hash2_nulladdr != slot2)) { hslot2 = udp_hashslot2(udptable, hash2_nulladdr); exist = udp_lib_lport_inuse2(net, snum, hslot2, sk, saddr_comp); } if (exist) goto fail_unlock; else goto found; } scan_primary_hash: if (udp_lib_lport_inuse(net, snum, hslot, NULL, sk, saddr_comp, 0)) goto fail_unlock; } found: inet_sk(sk)->inet_num = snum; udp_sk(sk)->udp_port_hash = snum; udp_sk(sk)->udp_portaddr_hash ^= snum; if (sk_unhashed(sk)) { sk_nulls_add_node_rcu(sk, &hslot->head); hslot->count++; sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1); hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash); spin_lock(&hslot2->lock); hlist_nulls_add_head_rcu(&udp_sk(sk)->udp_portaddr_node, &hslot2->head); hslot2->count++; spin_unlock(&hslot2->lock); } error = 0; fail_unlock: spin_unlock_bh(&hslot->lock); fail: return error; } EXPORT_SYMBOL(udp_lib_get_port); static int ipv4_rcv_saddr_equal(const struct sock *sk1, const struct sock *sk2) { struct inet_sock *inet1 = inet_sk(sk1), *inet2 = inet_sk(sk2); return (!ipv6_only_sock(sk2) && (!inet1->inet_rcv_saddr || !inet2->inet_rcv_saddr || inet1->inet_rcv_saddr == inet2->inet_rcv_saddr)); } static unsigned int udp4_portaddr_hash(struct net *net, __be32 saddr, unsigned int port) { return jhash_1word((__force u32)saddr, net_hash_mix(net)) ^ port; } int udp_v4_get_port(struct sock *sk, unsigned short snum) { unsigned int hash2_nulladdr = udp4_portaddr_hash(sock_net(sk), htonl(INADDR_ANY), snum); unsigned int hash2_partial = udp4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, 0); /* precompute partial secondary hash */ udp_sk(sk)->udp_portaddr_hash = hash2_partial; return udp_lib_get_port(sk, snum, ipv4_rcv_saddr_equal, hash2_nulladdr); } static inline int compute_score(struct sock *sk, struct net *net, __be32 saddr, unsigned short hnum, __be16 sport, __be32 daddr, __be16 dport, int dif) { int score = -1; if (net_eq(sock_net(sk), net) && udp_sk(sk)->udp_port_hash == hnum && !ipv6_only_sock(sk)) { struct inet_sock *inet = inet_sk(sk); score = (sk->sk_family == PF_INET ? 2 : 1); if (inet->inet_rcv_saddr) { if (inet->inet_rcv_saddr != daddr) return -1; score += 4; } if (inet->inet_daddr) { if (inet->inet_daddr != saddr) return -1; score += 4; } if (inet->inet_dport) { if (inet->inet_dport != sport) return -1; score += 4; } if (sk->sk_bound_dev_if) { if (sk->sk_bound_dev_if != dif) return -1; score += 4; } } return score; } /* * In this second variant, we check (daddr, dport) matches (inet_rcv_sadd, inet_num) */ static inline int compute_score2(struct sock *sk, struct net *net, __be32 saddr, __be16 sport, __be32 daddr, unsigned int hnum, int dif) { int score = -1; if (net_eq(sock_net(sk), net) && !ipv6_only_sock(sk)) { struct inet_sock *inet = inet_sk(sk); if (inet->inet_rcv_saddr != daddr) return -1; if (inet->inet_num != hnum) return -1; score = (sk->sk_family == PF_INET ? 2 : 1); if (inet->inet_daddr) { if (inet->inet_daddr != saddr) return -1; score += 4; } if (inet->inet_dport) { if (inet->inet_dport != sport) return -1; score += 4; } if (sk->sk_bound_dev_if) { if (sk->sk_bound_dev_if != dif) return -1; score += 4; } } return score; } /* called with read_rcu_lock() */ static struct sock *udp4_lib_lookup2(struct net *net, __be32 saddr, __be16 sport, __be32 daddr, unsigned int hnum, int dif, struct udp_hslot *hslot2, unsigned int slot2) { struct sock *sk, *result; struct hlist_nulls_node *node; int score, badness, matches = 0, reuseport = 0; u32 hash = 0; begin: result = NULL; badness = 0; udp_portaddr_for_each_entry_rcu(sk, node, &hslot2->head) { score = compute_score2(sk, net, saddr, sport, daddr, hnum, dif); if (score > badness) { result = sk; badness = score; reuseport = sk->sk_reuseport; if (reuseport) { hash = inet_ehashfn(net, daddr, hnum, saddr, sport); matches = 1; } } else if (score == badness && reuseport) { matches++; if (((u64)hash * matches) >> 32 == 0) result = sk; hash = next_pseudo_random32(hash); } } /* * if the nulls value we got at the end of this lookup is * not the expected one, we must restart lookup. * We probably met an item that was moved to another chain. */ if (get_nulls_value(node) != slot2) goto begin; if (result) { if (unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2))) result = NULL; else if (unlikely(compute_score2(result, net, saddr, sport, daddr, hnum, dif) < badness)) { sock_put(result); goto begin; } } return result; } /* UDP is nearly always wildcards out the wazoo, it makes no sense to try * harder than this. -DaveM */ struct sock *__udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport, __be32 daddr, __be16 dport, int dif, struct udp_table *udptable) { struct sock *sk, *result; struct hlist_nulls_node *node; unsigned short hnum = ntohs(dport); unsigned int hash2, slot2, slot = udp_hashfn(net, hnum, udptable->mask); struct udp_hslot *hslot2, *hslot = &udptable->hash[slot]; int score, badness, matches = 0, reuseport = 0; u32 hash = 0; rcu_read_lock(); if (hslot->count > 10) { hash2 = udp4_portaddr_hash(net, daddr, hnum); slot2 = hash2 & udptable->mask; hslot2 = &udptable->hash2[slot2]; if (hslot->count < hslot2->count) goto begin; result = udp4_lib_lookup2(net, saddr, sport, daddr, hnum, dif, hslot2, slot2); if (!result) { hash2 = udp4_portaddr_hash(net, htonl(INADDR_ANY), hnum); slot2 = hash2 & udptable->mask; hslot2 = &udptable->hash2[slot2]; if (hslot->count < hslot2->count) goto begin; result = udp4_lib_lookup2(net, saddr, sport, htonl(INADDR_ANY), hnum, dif, hslot2, slot2); } rcu_read_unlock(); return result; } begin: result = NULL; badness = 0; sk_nulls_for_each_rcu(sk, node, &hslot->head) { score = compute_score(sk, net, saddr, hnum, sport, daddr, dport, dif); if (score > badness) { result = sk; badness = score; reuseport = sk->sk_reuseport; if (reuseport) { hash = inet_ehashfn(net, daddr, hnum, saddr, sport); matches = 1; } } else if (score == badness && reuseport) { matches++; if (((u64)hash * matches) >> 32 == 0) result = sk; hash = next_pseudo_random32(hash); } } /* * if the nulls value we got at the end of this lookup is * not the expected one, we must restart lookup. * We probably met an item that was moved to another chain. */ if (get_nulls_value(node) != slot) goto begin; if (result) { if (unlikely(!atomic_inc_not_zero_hint(&result->sk_refcnt, 2))) result = NULL; else if (unlikely(compute_score(result, net, saddr, hnum, sport, daddr, dport, dif) < badness)) { sock_put(result); goto begin; } } rcu_read_unlock(); return result; } EXPORT_SYMBOL_GPL(__udp4_lib_lookup); static inline struct sock *__udp4_lib_lookup_skb(struct sk_buff *skb, __be16 sport, __be16 dport, struct udp_table *udptable) { struct sock *sk; const struct iphdr *iph = ip_hdr(skb); if (unlikely(sk = skb_steal_sock(skb))) return sk; else return __udp4_lib_lookup(dev_net(skb_dst(skb)->dev), iph->saddr, sport, iph->daddr, dport, inet_iif(skb), udptable); } struct sock *udp4_lib_lookup(struct net *net, __be32 saddr, __be16 sport, __be32 daddr, __be16 dport, int dif) { return __udp4_lib_lookup(net, saddr, sport, daddr, dport, dif, &udp_table); } EXPORT_SYMBOL_GPL(udp4_lib_lookup); static inline struct sock *udp_v4_mcast_next(struct net *net, struct sock *sk, __be16 loc_port, __be32 loc_addr, __be16 rmt_port, __be32 rmt_addr, int dif) { struct hlist_nulls_node *node; struct sock *s = sk; unsigned short hnum = ntohs(loc_port); sk_nulls_for_each_from(s, node) { struct inet_sock *inet = inet_sk(s); if (!net_eq(sock_net(s), net) || udp_sk(s)->udp_port_hash != hnum || (inet->inet_daddr && inet->inet_daddr != rmt_addr) || (inet->inet_dport != rmt_port && inet->inet_dport) || (inet->inet_rcv_saddr && inet->inet_rcv_saddr != loc_addr) || ipv6_only_sock(s) || (s->sk_bound_dev_if && s->sk_bound_dev_if != dif)) continue; if (!ip_mc_sf_allow(s, loc_addr, rmt_addr, dif)) continue; goto found; } s = NULL; found: return s; } /* * This routine is called by the ICMP module when it gets some * sort of error condition. If err < 0 then the socket should * be closed and the error returned to the user. If err > 0 * it's just the icmp type << 8 | icmp code. * Header points to the ip header of the error packet. We move * on past this. Then (as it used to claim before adjustment) * header points to the first 8 bytes of the udp header. We need * to find the appropriate port. */ void __udp4_lib_err(struct sk_buff *skb, u32 info, struct udp_table *udptable) { struct inet_sock *inet; const struct iphdr *iph = (const struct iphdr *)skb->data; struct udphdr *uh = (struct udphdr *)(skb->data+(iph->ihl<<2)); const int type = icmp_hdr(skb)->type; const int code = icmp_hdr(skb)->code; struct sock *sk; int harderr; int err; struct net *net = dev_net(skb->dev); sk = __udp4_lib_lookup(net, iph->daddr, uh->dest, iph->saddr, uh->source, skb->dev->ifindex, udptable); if (sk == NULL) { ICMP_INC_STATS_BH(net, ICMP_MIB_INERRORS); return; /* No socket for error */ } err = 0; harderr = 0; inet = inet_sk(sk); switch (type) { default: case ICMP_TIME_EXCEEDED: err = EHOSTUNREACH; break; case ICMP_SOURCE_QUENCH: goto out; 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->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: ipv4_sk_redirect(skb, sk); break; } /* * RFC1122: OK. Passes ICMP errors back to application, as per * 4.1.3.3. */ if (!inet->recverr) { if (!harderr || sk->sk_state != TCP_ESTABLISHED) goto out; } else ip_icmp_error(sk, skb, err, uh->dest, info, (u8 *)(uh+1)); sk->sk_err = err; sk->sk_error_report(sk); out: sock_put(sk); } void udp_err(struct sk_buff *skb, u32 info) { __udp4_lib_err(skb, info, &udp_table); } /* * Throw away all pending data and cancel the corking. Socket is locked. */ void udp_flush_pending_frames(struct sock *sk) { struct udp_sock *up = udp_sk(sk); if (up->pending) { up->len = 0; up->pending = 0; ip_flush_pending_frames(sk); } } EXPORT_SYMBOL(udp_flush_pending_frames); /** * udp4_hwcsum - handle outgoing HW checksumming * @skb: sk_buff containing the filled-in UDP header * (checksum field must be zeroed out) * @src: source IP address * @dst: destination IP address */ static void udp4_hwcsum(struct sk_buff *skb, __be32 src, __be32 dst) { struct udphdr *uh = udp_hdr(skb); struct sk_buff *frags = skb_shinfo(skb)->frag_list; int offset = skb_transport_offset(skb); int len = skb->len - offset; int hlen = len; __wsum csum = 0; if (!frags) { /* * Only one fragment on the socket. */ skb->csum_start = skb_transport_header(skb) - skb->head; skb->csum_offset = offsetof(struct udphdr, check); uh->check = ~csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, 0); } else { /* * HW-checksum won't work as there are two or more * fragments on the socket so that all csums of sk_buffs * should be together */ do { csum = csum_add(csum, frags->csum); hlen -= frags->len; } while ((frags = frags->next)); csum = skb_checksum(skb, offset, hlen, csum); skb->ip_summed = CHECKSUM_NONE; uh->check = csum_tcpudp_magic(src, dst, len, IPPROTO_UDP, csum); if (uh->check == 0) uh->check = CSUM_MANGLED_0; } } static int udp_send_skb(struct sk_buff *skb, struct flowi4 *fl4) { struct sock *sk = skb->sk; struct inet_sock *inet = inet_sk(sk); struct udphdr *uh; int err = 0; int is_udplite = IS_UDPLITE(sk); int offset = skb_transport_offset(skb); int len = skb->len - offset; __wsum csum = 0; /* * Create a UDP header */ uh = udp_hdr(skb); uh->source = inet->inet_sport; uh->dest = fl4->fl4_dport; uh->len = htons(len); uh->check = 0; if (is_udplite) /* UDP-Lite */ csum = udplite_csum(skb); else if (sk->sk_no_check == UDP_CSUM_NOXMIT) { /* UDP csum disabled */ skb->ip_summed = CHECKSUM_NONE; goto send; } else if (skb->ip_summed == CHECKSUM_PARTIAL) { /* UDP hardware csum */ udp4_hwcsum(skb, fl4->saddr, fl4->daddr); goto send; } else csum = udp_csum(skb); /* add protocol-dependent pseudo-header */ uh->check = csum_tcpudp_magic(fl4->saddr, fl4->daddr, len, sk->sk_protocol, csum); if (uh->check == 0) uh->check = CSUM_MANGLED_0; send: err = ip_send_skb(sock_net(sk), skb); if (err) { if (err == -ENOBUFS && !inet->recverr) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_SNDBUFERRORS, is_udplite); err = 0; } } else UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_OUTDATAGRAMS, is_udplite); return err; } /* * Push out all pending data as one UDP datagram. Socket is locked. */ int udp_push_pending_frames(struct sock *sk) { struct udp_sock *up = udp_sk(sk); struct inet_sock *inet = inet_sk(sk); struct flowi4 *fl4 = &inet->cork.fl.u.ip4; struct sk_buff *skb; int err = 0; skb = ip_finish_skb(sk, fl4); if (!skb) goto out; err = udp_send_skb(skb, fl4); out: up->len = 0; up->pending = 0; return err; } EXPORT_SYMBOL(udp_push_pending_frames); int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len) { struct inet_sock *inet = inet_sk(sk); struct udp_sock *up = udp_sk(sk); struct flowi4 fl4_stack; struct flowi4 *fl4; int ulen = len; struct ipcm_cookie ipc; struct rtable *rt = NULL; int free = 0; int connected = 0; __be32 daddr, faddr, saddr; __be16 dport; u8 tos; int err, is_udplite = IS_UDPLITE(sk); int corkreq = up->corkflag || msg->msg_flags&MSG_MORE; int (*getfrag)(void *, char *, int, int, int, struct sk_buff *); struct sk_buff *skb; struct ip_options_data opt_copy; if (len > 0xFFFF) return -EMSGSIZE; /* * Check the flags. */ if (msg->msg_flags & MSG_OOB) /* Mirror BSD error message compatibility */ return -EOPNOTSUPP; ipc.opt = NULL; ipc.tx_flags = 0; getfrag = is_udplite ? udplite_getfrag : ip_generic_getfrag; fl4 = &inet->cork.fl.u.ip4; if (up->pending) { /* * There are pending frames. * The socket lock must be held while it's corked. */ lock_sock(sk); if (likely(up->pending)) { if (unlikely(up->pending != AF_INET)) { release_sock(sk); return -EINVAL; } goto do_append_data; } release_sock(sk); } ulen += sizeof(struct udphdr); /* * 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) { if (usin->sin_family != AF_UNSPEC) return -EAFNOSUPPORT; } daddr = usin->sin_addr.s_addr; dport = usin->sin_port; if (dport == 0) return -EINVAL; } else { if (sk->sk_state != TCP_ESTABLISHED) return -EDESTADDRREQ; daddr = inet->inet_daddr; dport = inet->inet_dport; /* Open fast path for connected socket. Route will not be used, if at least one option is set. */ connected = 1; } ipc.addr = inet->inet_saddr; ipc.oif = sk->sk_bound_dev_if; 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; connected = 0; } 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; connected = 0; } tos = RT_TOS(inet->tos); if (sock_flag(sk, SOCK_LOCALROUTE) || (msg->msg_flags & MSG_DONTROUTE) || (ipc.opt && ipc.opt->opt.is_strictroute)) { tos |= RTO_ONLINK; connected = 0; } if (ipv4_is_multicast(daddr)) { if (!ipc.oif) ipc.oif = inet->mc_index; if (!saddr) saddr = inet->mc_addr; connected = 0; } else if (!ipc.oif) ipc.oif = inet->uc_index; if (connected) rt = (struct rtable *)sk_dst_check(sk, 0); if (rt == NULL) { struct net *net = sock_net(sk); fl4 = &fl4_stack; flowi4_init_output(fl4, ipc.oif, sk->sk_mark, tos, RT_SCOPE_UNIVERSE, sk->sk_protocol, inet_sk_flowi_flags(sk)|FLOWI_FLAG_CAN_SLEEP, faddr, saddr, dport, inet->inet_sport); 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 (connected) sk_dst_set(sk, dst_clone(&rt->dst)); } if (msg->msg_flags&MSG_CONFIRM) goto do_confirm; back_from_confirm: saddr = fl4->saddr; if (!ipc.addr) daddr = ipc.addr = fl4->daddr; /* Lockless fast path for the non-corking case. */ if (!corkreq) { skb = ip_make_skb(sk, fl4, getfrag, msg->msg_iov, ulen, sizeof(struct udphdr), &ipc, &rt, msg->msg_flags); err = PTR_ERR(skb); if (!IS_ERR_OR_NULL(skb)) err = udp_send_skb(skb, fl4); goto out; } lock_sock(sk); if (unlikely(up->pending)) { /* The socket is already corked while preparing it. */ /* ... which is an evident application bug. --ANK */ release_sock(sk); LIMIT_NETDEBUG(KERN_DEBUG pr_fmt("cork app bug 2\n")); err = -EINVAL; goto out; } /* * Now cork the socket to pend data. */ fl4 = &inet->cork.fl.u.ip4; fl4->daddr = daddr; fl4->saddr = saddr; fl4->fl4_dport = dport; fl4->fl4_sport = inet->inet_sport; up->pending = AF_INET; do_append_data: up->len += ulen; err = ip_append_data(sk, fl4, getfrag, msg->msg_iov, ulen, sizeof(struct udphdr), &ipc, &rt, corkreq ? msg->msg_flags|MSG_MORE : msg->msg_flags); if (err) udp_flush_pending_frames(sk); else if (!corkreq) err = udp_push_pending_frames(sk); else if (unlikely(skb_queue_empty(&sk->sk_write_queue))) up->pending = 0; release_sock(sk); out: ip_rt_put(rt); if (free) kfree(ipc.opt); if (!err) return len; /* * ENOBUFS = no kernel mem, SOCK_NOSPACE = no sndbuf space. Reporting * ENOBUFS might not be good (it's not tunable per se), but otherwise * we don't have a good statistic (IpOutDiscards but it can be too many * things). We could add another new stat but at least for now that * seems like overkill. */ if (err == -ENOBUFS || test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_SNDBUFERRORS, is_udplite); } return err; do_confirm: dst_confirm(&rt->dst); if (!(msg->msg_flags&MSG_PROBE) || len) goto back_from_confirm; err = 0; goto out; } EXPORT_SYMBOL(udp_sendmsg); int udp_sendpage(struct sock *sk, struct page *page, int offset, size_t size, int flags) { struct inet_sock *inet = inet_sk(sk); struct udp_sock *up = udp_sk(sk); int ret; if (!up->pending) { struct msghdr msg = { .msg_flags = flags|MSG_MORE }; /* Call udp_sendmsg to specify destination address which * sendpage interface can't pass. * This will succeed only when the socket is connected. */ ret = udp_sendmsg(NULL, sk, &msg, 0); if (ret < 0) return ret; } lock_sock(sk); if (unlikely(!up->pending)) { release_sock(sk); LIMIT_NETDEBUG(KERN_DEBUG pr_fmt("udp cork app bug 3\n")); return -EINVAL; } ret = ip_append_page(sk, &inet->cork.fl.u.ip4, page, offset, size, flags); if (ret == -EOPNOTSUPP) { release_sock(sk); return sock_no_sendpage(sk->sk_socket, page, offset, size, flags); } if (ret < 0) { udp_flush_pending_frames(sk); goto out; } up->len += size; if (!(up->corkflag || (flags&MSG_MORE))) ret = udp_push_pending_frames(sk); if (!ret) ret = size; out: release_sock(sk); return ret; } /** * first_packet_length - return length of first packet in receive queue * @sk: socket * * Drops all bad checksum frames, until a valid one is found. * Returns the length of found skb, or 0 if none is found. */ static unsigned int first_packet_length(struct sock *sk) { struct sk_buff_head list_kill, *rcvq = &sk->sk_receive_queue; struct sk_buff *skb; unsigned int res; __skb_queue_head_init(&list_kill); spin_lock_bh(&rcvq->lock); while ((skb = skb_peek(rcvq)) != NULL && udp_lib_checksum_complete(skb)) { UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_CSUMERRORS, IS_UDPLITE(sk)); UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, IS_UDPLITE(sk)); atomic_inc(&sk->sk_drops); __skb_unlink(skb, rcvq); __skb_queue_tail(&list_kill, skb); } res = skb ? skb->len : 0; spin_unlock_bh(&rcvq->lock); if (!skb_queue_empty(&list_kill)) { bool slow = lock_sock_fast(sk); __skb_queue_purge(&list_kill); sk_mem_reclaim_partial(sk); unlock_sock_fast(sk, slow); } return res; } /* * IOCTL requests applicable to the UDP protocol */ int udp_ioctl(struct sock *sk, int cmd, unsigned long arg) { switch (cmd) { case SIOCOUTQ: { int amount = sk_wmem_alloc_get(sk); return put_user(amount, (int __user *)arg); } case SIOCINQ: { unsigned int amount = first_packet_length(sk); if (amount) /* * We will only return the amount * of this packet since that is all * that will be read. */ amount -= sizeof(struct udphdr); return put_user(amount, (int __user *)arg); } default: return -ENOIOCTLCMD; } return 0; } EXPORT_SYMBOL(udp_ioctl); /* * This should be easy, if there is something there we * return it, otherwise we block. */ int udp_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *inet = inet_sk(sk); struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name; struct sk_buff *skb; unsigned int ulen, copied; int peeked, off = 0; int err; int is_udplite = IS_UDPLITE(sk); bool slow; /* * Check any passed addresses */ if (addr_len) *addr_len = sizeof(*sin); if (flags & MSG_ERRQUEUE) return ip_recv_error(sk, msg, len); try_again: skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0), &peeked, &off, &err); if (!skb) goto out; ulen = skb->len - sizeof(struct udphdr); copied = len; if (copied > ulen) copied = ulen; else if (copied < ulen) msg->msg_flags |= MSG_TRUNC; /* * If checksum is needed at all, try to do it while copying the * data. If the data is truncated, or if we only want a partial * coverage checksum (UDP-Lite), do it before the copy. */ if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) { if (udp_lib_checksum_complete(skb)) goto csum_copy_err; } if (skb_csum_unnecessary(skb)) err = skb_copy_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov, copied); else { err = skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov); if (err == -EINVAL) goto csum_copy_err; } if (unlikely(err)) { trace_kfree_skb(skb, udp_recvmsg); if (!peeked) { atomic_inc(&sk->sk_drops); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } goto out_free; } if (!peeked) UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); sock_recv_ts_and_drops(msg, sk, skb); /* Copy the address. */ if (sin) { sin->sin_family = AF_INET; sin->sin_port = udp_hdr(skb)->source; sin->sin_addr.s_addr = ip_hdr(skb)->saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); } if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); err = copied; if (flags & MSG_TRUNC) err = ulen; out_free: skb_free_datagram_locked(sk, skb); out: return err; csum_copy_err: slow = lock_sock_fast(sk); if (!skb_kill_datagram(sk, skb, flags)) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } unlock_sock_fast(sk, slow); if (noblock) return -EAGAIN; /* starting over for a new packet */ msg->msg_flags &= ~MSG_TRUNC; goto try_again; } int udp_disconnect(struct sock *sk, int flags) { struct inet_sock *inet = inet_sk(sk); /* * 1003.1g - break association. */ sk->sk_state = TCP_CLOSE; inet->inet_daddr = 0; inet->inet_dport = 0; sock_rps_reset_rxhash(sk); sk->sk_bound_dev_if = 0; if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK)) inet_reset_saddr(sk); if (!(sk->sk_userlocks & SOCK_BINDPORT_LOCK)) { sk->sk_prot->unhash(sk); inet->inet_sport = 0; } sk_dst_reset(sk); return 0; } EXPORT_SYMBOL(udp_disconnect); void udp_lib_unhash(struct sock *sk) { if (sk_hashed(sk)) { struct udp_table *udptable = sk->sk_prot->h.udp_table; struct udp_hslot *hslot, *hslot2; hslot = udp_hashslot(udptable, sock_net(sk), udp_sk(sk)->udp_port_hash); hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash); spin_lock_bh(&hslot->lock); if (sk_nulls_del_node_init_rcu(sk)) { hslot->count--; inet_sk(sk)->inet_num = 0; sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1); spin_lock(&hslot2->lock); hlist_nulls_del_init_rcu(&udp_sk(sk)->udp_portaddr_node); hslot2->count--; spin_unlock(&hslot2->lock); } spin_unlock_bh(&hslot->lock); } } EXPORT_SYMBOL(udp_lib_unhash); /* * inet_rcv_saddr was changed, we must rehash secondary hash */ void udp_lib_rehash(struct sock *sk, u16 newhash) { if (sk_hashed(sk)) { struct udp_table *udptable = sk->sk_prot->h.udp_table; struct udp_hslot *hslot, *hslot2, *nhslot2; hslot2 = udp_hashslot2(udptable, udp_sk(sk)->udp_portaddr_hash); nhslot2 = udp_hashslot2(udptable, newhash); udp_sk(sk)->udp_portaddr_hash = newhash; if (hslot2 != nhslot2) { hslot = udp_hashslot(udptable, sock_net(sk), udp_sk(sk)->udp_port_hash); /* we must lock primary chain too */ spin_lock_bh(&hslot->lock); spin_lock(&hslot2->lock); hlist_nulls_del_init_rcu(&udp_sk(sk)->udp_portaddr_node); hslot2->count--; spin_unlock(&hslot2->lock); spin_lock(&nhslot2->lock); hlist_nulls_add_head_rcu(&udp_sk(sk)->udp_portaddr_node, &nhslot2->head); nhslot2->count++; spin_unlock(&nhslot2->lock); spin_unlock_bh(&hslot->lock); } } } EXPORT_SYMBOL(udp_lib_rehash); static void udp_v4_rehash(struct sock *sk) { u16 new_hash = udp4_portaddr_hash(sock_net(sk), inet_sk(sk)->inet_rcv_saddr, inet_sk(sk)->inet_num); udp_lib_rehash(sk, new_hash); } static int __udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { int rc; if (inet_sk(sk)->inet_daddr) sock_rps_save_rxhash(sk, skb); rc = sock_queue_rcv_skb(sk, skb); if (rc < 0) { int is_udplite = IS_UDPLITE(sk); /* Note that an ENOMEM error is charged twice */ if (rc == -ENOMEM) UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS, is_udplite); UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite); kfree_skb(skb); trace_udp_fail_queue_rcv_skb(rc, sk); return -1; } return 0; } static struct static_key udp_encap_needed __read_mostly; void udp_encap_enable(void) { if (!static_key_enabled(&udp_encap_needed)) static_key_slow_inc(&udp_encap_needed); } EXPORT_SYMBOL(udp_encap_enable); /* returns: * -1: error * 0: success * >0: "udp encap" protocol resubmission * * Note that in the success and error cases, the skb is assumed to * have either been requeued or freed. */ int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) { struct udp_sock *up = udp_sk(sk); int rc; int is_udplite = IS_UDPLITE(sk); /* * Charge it to the socket, dropping if the queue is full. */ if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) goto drop; nf_reset(skb); if (static_key_false(&udp_encap_needed) && up->encap_type) { int (*encap_rcv)(struct sock *sk, struct sk_buff *skb); /* * This is an encapsulation socket so pass the skb to * the socket's udp_encap_rcv() hook. Otherwise, just * fall through and pass this up the UDP socket. * up->encap_rcv() returns the following value: * =0 if skb was successfully passed to the encap * handler or was discarded by it. * >0 if skb should be passed on to UDP. * <0 if skb should be resubmitted as proto -N */ /* if we're overly short, let UDP handle it */ encap_rcv = ACCESS_ONCE(up->encap_rcv); if (skb->len > sizeof(struct udphdr) && encap_rcv != NULL) { int ret; ret = encap_rcv(sk, skb); if (ret <= 0) { UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); return -ret; } } /* FALLTHROUGH -- it's a UDP Packet */ } /* * UDP-Lite specific tests, ignored on UDP sockets */ if ((is_udplite & UDPLITE_RECV_CC) && UDP_SKB_CB(skb)->partial_cov) { /* * MIB statistics other than incrementing the error count are * disabled for the following two types of errors: these depend * on the application settings, not on the functioning of the * protocol stack as such. * * RFC 3828 here recommends (sec 3.3): "There should also be a * way ... to ... at least let the receiving application block * delivery of packets with coverage values less than a value * provided by the application." */ if (up->pcrlen == 0) { /* full coverage was set */ LIMIT_NETDEBUG(KERN_WARNING "UDPLite: partial coverage %d while full coverage %d requested\n", UDP_SKB_CB(skb)->cscov, skb->len); goto drop; } /* The next case involves violating the min. coverage requested * by the receiver. This is subtle: if receiver wants x and x is * greater than the buffersize/MTU then receiver will complain * that it wants x while sender emits packets of smaller size y. * Therefore the above ...()->partial_cov statement is essential. */ if (UDP_SKB_CB(skb)->cscov < up->pcrlen) { LIMIT_NETDEBUG(KERN_WARNING "UDPLite: coverage %d too small, need min %d\n", UDP_SKB_CB(skb)->cscov, up->pcrlen); goto drop; } } if (rcu_access_pointer(sk->sk_filter) && udp_lib_checksum_complete(skb)) goto csum_error; if (sk_rcvqueues_full(sk, skb, sk->sk_rcvbuf)) goto drop; rc = 0; ipv4_pktinfo_prepare(skb); bh_lock_sock(sk); if (!sock_owned_by_user(sk)) rc = __udp_queue_rcv_skb(sk, skb); else if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) { bh_unlock_sock(sk); goto drop; } bh_unlock_sock(sk); return rc; csum_error: UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); drop: UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite); atomic_inc(&sk->sk_drops); kfree_skb(skb); return -1; } static void flush_stack(struct sock **stack, unsigned int count, struct sk_buff *skb, unsigned int final) { unsigned int i; struct sk_buff *skb1 = NULL; struct sock *sk; for (i = 0; i < count; i++) { sk = stack[i]; if (likely(skb1 == NULL)) skb1 = (i == final) ? skb : skb_clone(skb, GFP_ATOMIC); if (!skb1) { atomic_inc(&sk->sk_drops); UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS, IS_UDPLITE(sk)); UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, IS_UDPLITE(sk)); } if (skb1 && udp_queue_rcv_skb(sk, skb1) <= 0) skb1 = NULL; } if (unlikely(skb1)) kfree_skb(skb1); } /* * Multicasts and broadcasts go to each listener. * * Note: called only from the BH handler context. */ static int __udp4_lib_mcast_deliver(struct net *net, struct sk_buff *skb, struct udphdr *uh, __be32 saddr, __be32 daddr, struct udp_table *udptable) { struct sock *sk, *stack[256 / sizeof(struct sock *)]; struct udp_hslot *hslot = udp_hashslot(udptable, net, ntohs(uh->dest)); int dif; unsigned int i, count = 0; spin_lock(&hslot->lock); sk = sk_nulls_head(&hslot->head); dif = skb->dev->ifindex; sk = udp_v4_mcast_next(net, sk, uh->dest, daddr, uh->source, saddr, dif); while (sk) { stack[count++] = sk; sk = udp_v4_mcast_next(net, sk_nulls_next(sk), uh->dest, daddr, uh->source, saddr, dif); if (unlikely(count == ARRAY_SIZE(stack))) { if (!sk) break; flush_stack(stack, count, skb, ~0); count = 0; } } /* * before releasing chain lock, we must take a reference on sockets */ for (i = 0; i < count; i++) sock_hold(stack[i]); spin_unlock(&hslot->lock); /* * do the slow work with no lock held */ if (count) { flush_stack(stack, count, skb, count - 1); for (i = 0; i < count; i++) sock_put(stack[i]); } else { kfree_skb(skb); } return 0; } /* Initialize UDP checksum. If exited with zero value (success), * CHECKSUM_UNNECESSARY means, that no more checks are required. * Otherwise, csum completion requires chacksumming packet body, * including udp header and folding it to skb->csum. */ static inline int udp4_csum_init(struct sk_buff *skb, struct udphdr *uh, int proto) { const struct iphdr *iph; int err; UDP_SKB_CB(skb)->partial_cov = 0; UDP_SKB_CB(skb)->cscov = skb->len; if (proto == IPPROTO_UDPLITE) { err = udplite_checksum_init(skb, uh); if (err) return err; } iph = ip_hdr(skb); if (uh->check == 0) { skb->ip_summed = CHECKSUM_UNNECESSARY; } else if (skb->ip_summed == CHECKSUM_COMPLETE) { if (!csum_tcpudp_magic(iph->saddr, iph->daddr, skb->len, proto, skb->csum)) skb->ip_summed = CHECKSUM_UNNECESSARY; } if (!skb_csum_unnecessary(skb)) skb->csum = csum_tcpudp_nofold(iph->saddr, iph->daddr, skb->len, proto, 0); /* Probably, we should checksum udp header (it should be in cache * in any case) and data in tiny packets (< rx copybreak). */ return 0; } /* * All we need to do is get the socket, and then do a checksum. */ int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable, int proto) { struct sock *sk; struct udphdr *uh; unsigned short ulen; struct rtable *rt = skb_rtable(skb); __be32 saddr, daddr; struct net *net = dev_net(skb->dev); /* * Validate the packet. */ if (!pskb_may_pull(skb, sizeof(struct udphdr))) goto drop; /* No space for header. */ uh = udp_hdr(skb); ulen = ntohs(uh->len); saddr = ip_hdr(skb)->saddr; daddr = ip_hdr(skb)->daddr; if (ulen > skb->len) goto short_packet; if (proto == IPPROTO_UDP) { /* UDP validates ulen. */ if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen)) goto short_packet; uh = udp_hdr(skb); } if (udp4_csum_init(skb, uh, proto)) goto csum_error; if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST)) return __udp4_lib_mcast_deliver(net, skb, uh, saddr, daddr, udptable); sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable); if (sk != NULL) { int ret; sk_mark_ll(sk, skb); ret = udp_queue_rcv_skb(sk, skb); sock_put(sk); /* a return value > 0 means to resubmit the input, but * it wants the return to be -protocol, or 0 */ if (ret > 0) return -ret; return 0; } if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) goto drop; nf_reset(skb); /* No socket. Drop packet silently, if checksum is wrong */ if (udp_lib_checksum_complete(skb)) goto csum_error; UDP_INC_STATS_BH(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE); icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0); /* * Hmm. We got an UDP packet to a port to which we * don't wanna listen. Ignore it. */ kfree_skb(skb); return 0; short_packet: LIMIT_NETDEBUG(KERN_DEBUG "UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n", proto == IPPROTO_UDPLITE ? "Lite" : "", &saddr, ntohs(uh->source), ulen, skb->len, &daddr, ntohs(uh->dest)); goto drop; csum_error: /* * RFC1122: OK. Discards the bad packet silently (as far as * the network is concerned, anyway) as per 4.1.3.4 (MUST). */ LIMIT_NETDEBUG(KERN_DEBUG "UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n", proto == IPPROTO_UDPLITE ? "Lite" : "", &saddr, ntohs(uh->source), &daddr, ntohs(uh->dest), ulen); UDP_INC_STATS_BH(net, UDP_MIB_CSUMERRORS, proto == IPPROTO_UDPLITE); drop: UDP_INC_STATS_BH(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE); kfree_skb(skb); return 0; } int udp_rcv(struct sk_buff *skb) { return __udp4_lib_rcv(skb, &udp_table, IPPROTO_UDP); } void udp_destroy_sock(struct sock *sk) { struct udp_sock *up = udp_sk(sk); bool slow = lock_sock_fast(sk); udp_flush_pending_frames(sk); unlock_sock_fast(sk, slow); if (static_key_false(&udp_encap_needed) && up->encap_type) { void (*encap_destroy)(struct sock *sk); encap_destroy = ACCESS_ONCE(up->encap_destroy); if (encap_destroy) encap_destroy(sk); } } /* * Socket option code for UDP */ int udp_lib_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen, int (*push_pending_frames)(struct sock *)) { struct udp_sock *up = udp_sk(sk); int val; int err = 0; int is_udplite = IS_UDPLITE(sk); if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *)optval)) return -EFAULT; switch (optname) { case UDP_CORK: if (val != 0) { up->corkflag = 1; } else { up->corkflag = 0; lock_sock(sk); (*push_pending_frames)(sk); release_sock(sk); } break; case UDP_ENCAP: switch (val) { case 0: case UDP_ENCAP_ESPINUDP: case UDP_ENCAP_ESPINUDP_NON_IKE: up->encap_rcv = xfrm4_udp_encap_rcv; /* FALLTHROUGH */ case UDP_ENCAP_L2TPINUDP: up->encap_type = val; udp_encap_enable(); break; default: err = -ENOPROTOOPT; break; } break; /* * UDP-Lite's partial checksum coverage (RFC 3828). */ /* The sender sets actual checksum coverage length via this option. * The case coverage > packet length is handled by send module. */ case UDPLITE_SEND_CSCOV: if (!is_udplite) /* Disable the option on UDP sockets */ return -ENOPROTOOPT; if (val != 0 && val < 8) /* Illegal coverage: use default (8) */ val = 8; else if (val > USHRT_MAX) val = USHRT_MAX; up->pcslen = val; up->pcflag |= UDPLITE_SEND_CC; break; /* The receiver specifies a minimum checksum coverage value. To make * sense, this should be set to at least 8 (as done below). If zero is * used, this again means full checksum coverage. */ case UDPLITE_RECV_CSCOV: if (!is_udplite) /* Disable the option on UDP sockets */ return -ENOPROTOOPT; if (val != 0 && val < 8) /* Avoid silly minimal values. */ val = 8; else if (val > USHRT_MAX) val = USHRT_MAX; up->pcrlen = val; up->pcflag |= UDPLITE_RECV_CC; break; default: err = -ENOPROTOOPT; break; } return err; } EXPORT_SYMBOL(udp_lib_setsockopt); int udp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { if (level == SOL_UDP || level == SOL_UDPLITE) return udp_lib_setsockopt(sk, level, optname, optval, optlen, udp_push_pending_frames); return ip_setsockopt(sk, level, optname, optval, optlen); } #ifdef CONFIG_COMPAT int compat_udp_setsockopt(struct sock *sk, int level, int optname, char __user *optval, unsigned int optlen) { if (level == SOL_UDP || level == SOL_UDPLITE) return udp_lib_setsockopt(sk, level, optname, optval, optlen, udp_push_pending_frames); return compat_ip_setsockopt(sk, level, optname, optval, optlen); } #endif int udp_lib_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { struct udp_sock *up = udp_sk(sk); int val, len; if (get_user(len, optlen)) return -EFAULT; len = min_t(unsigned int, len, sizeof(int)); if (len < 0) return -EINVAL; switch (optname) { case UDP_CORK: val = up->corkflag; break; case UDP_ENCAP: val = up->encap_type; break; /* The following two cannot be changed on UDP sockets, the return is * always 0 (which corresponds to the full checksum coverage of UDP). */ case UDPLITE_SEND_CSCOV: val = up->pcslen; break; case UDPLITE_RECV_CSCOV: val = up->pcrlen; break; default: return -ENOPROTOOPT; } if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; return 0; } EXPORT_SYMBOL(udp_lib_getsockopt); int udp_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { if (level == SOL_UDP || level == SOL_UDPLITE) return udp_lib_getsockopt(sk, level, optname, optval, optlen); return ip_getsockopt(sk, level, optname, optval, optlen); } #ifdef CONFIG_COMPAT int compat_udp_getsockopt(struct sock *sk, int level, int optname, char __user *optval, int __user *optlen) { if (level == SOL_UDP || level == SOL_UDPLITE) return udp_lib_getsockopt(sk, level, optname, optval, optlen); return compat_ip_getsockopt(sk, level, optname, optval, optlen); } #endif /** * udp_poll - wait for a UDP event. * @file - file struct * @sock - socket * @wait - poll table * * This is same as datagram poll, except for the special case of * blocking sockets. If application is using a blocking fd * and a packet with checksum error is in the queue; * then it could get return from select indicating data available * but then block when reading it. Add special case code * to work around these arguably broken applications. */ unsigned int udp_poll(struct file *file, struct socket *sock, poll_table *wait) { unsigned int mask = datagram_poll(file, sock, wait); struct sock *sk = sock->sk; sock_rps_record_flow(sk); /* Check for false positives due to checksum errors */ if ((mask & POLLRDNORM) && !(file->f_flags & O_NONBLOCK) && !(sk->sk_shutdown & RCV_SHUTDOWN) && !first_packet_length(sk)) mask &= ~(POLLIN | POLLRDNORM); return mask; } EXPORT_SYMBOL(udp_poll); struct proto udp_prot = { .name = "UDP", .owner = THIS_MODULE, .close = udp_lib_close, .connect = ip4_datagram_connect, .disconnect = udp_disconnect, .ioctl = udp_ioctl, .destroy = udp_destroy_sock, .setsockopt = udp_setsockopt, .getsockopt = udp_getsockopt, .sendmsg = udp_sendmsg, .recvmsg = udp_recvmsg, .sendpage = udp_sendpage, .backlog_rcv = __udp_queue_rcv_skb, .release_cb = ip4_datagram_release_cb, .hash = udp_lib_hash, .unhash = udp_lib_unhash, .rehash = udp_v4_rehash, .get_port = udp_v4_get_port, .memory_allocated = &udp_memory_allocated, .sysctl_mem = sysctl_udp_mem, .sysctl_wmem = &sysctl_udp_wmem_min, .sysctl_rmem = &sysctl_udp_rmem_min, .obj_size = sizeof(struct udp_sock), .slab_flags = SLAB_DESTROY_BY_RCU, .h.udp_table = &udp_table, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_udp_setsockopt, .compat_getsockopt = compat_udp_getsockopt, #endif .clear_sk = sk_prot_clear_portaddr_nulls, }; EXPORT_SYMBOL(udp_prot); /* ------------------------------------------------------------------------ */ #ifdef CONFIG_PROC_FS static struct sock *udp_get_first(struct seq_file *seq, int start) { struct sock *sk; struct udp_iter_state *state = seq->private; struct net *net = seq_file_net(seq); for (state->bucket = start; state->bucket <= state->udp_table->mask; ++state->bucket) { struct hlist_nulls_node *node; struct udp_hslot *hslot = &state->udp_table->hash[state->bucket]; if (hlist_nulls_empty(&hslot->head)) continue; spin_lock_bh(&hslot->lock); sk_nulls_for_each(sk, node, &hslot->head) { if (!net_eq(sock_net(sk), net)) continue; if (sk->sk_family == state->family) goto found; } spin_unlock_bh(&hslot->lock); } sk = NULL; found: return sk; } static struct sock *udp_get_next(struct seq_file *seq, struct sock *sk) { struct udp_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) || sk->sk_family != state->family)); if (!sk) { if (state->bucket <= state->udp_table->mask) spin_unlock_bh(&state->udp_table->hash[state->bucket].lock); return udp_get_first(seq, state->bucket + 1); } return sk; } static struct sock *udp_get_idx(struct seq_file *seq, loff_t pos) { struct sock *sk = udp_get_first(seq, 0); if (sk) while (pos && (sk = udp_get_next(seq, sk)) != NULL) --pos; return pos ? NULL : sk; } static void *udp_seq_start(struct seq_file *seq, loff_t *pos) { struct udp_iter_state *state = seq->private; state->bucket = MAX_UDP_PORTS; return *pos ? udp_get_idx(seq, *pos-1) : SEQ_START_TOKEN; } static void *udp_seq_next(struct seq_file *seq, void *v, loff_t *pos) { struct sock *sk; if (v == SEQ_START_TOKEN) sk = udp_get_idx(seq, 0); else sk = udp_get_next(seq, v); ++*pos; return sk; } static void udp_seq_stop(struct seq_file *seq, void *v) { struct udp_iter_state *state = seq->private; if (state->bucket <= state->udp_table->mask) spin_unlock_bh(&state->udp_table->hash[state->bucket].lock); } int udp_seq_open(struct inode *inode, struct file *file) { struct udp_seq_afinfo *afinfo = PDE_DATA(inode); struct udp_iter_state *s; int err; err = seq_open_net(inode, file, &afinfo->seq_ops, sizeof(struct udp_iter_state)); if (err < 0) return err; s = ((struct seq_file *)file->private_data)->private; s->family = afinfo->family; s->udp_table = afinfo->udp_table; return err; } EXPORT_SYMBOL(udp_seq_open); /* ------------------------------------------------------------------------ */ int udp_proc_register(struct net *net, struct udp_seq_afinfo *afinfo) { struct proc_dir_entry *p; int rc = 0; afinfo->seq_ops.start = udp_seq_start; afinfo->seq_ops.next = udp_seq_next; afinfo->seq_ops.stop = udp_seq_stop; p = proc_create_data(afinfo->name, S_IRUGO, net->proc_net, afinfo->seq_fops, afinfo); if (!p) rc = -ENOMEM; return rc; } EXPORT_SYMBOL(udp_proc_register); void udp_proc_unregister(struct net *net, struct udp_seq_afinfo *afinfo) { remove_proc_entry(afinfo->name, net->proc_net); } EXPORT_SYMBOL(udp_proc_unregister); /* ------------------------------------------------------------------------ */ static void udp4_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 %5d %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); } int udp4_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 udp_iter_state *state = seq->private; int len; udp4_format_sock(v, seq, state->bucket, &len); seq_printf(seq, "%*s\n", 127 - len, ""); } return 0; } static const struct file_operations udp_afinfo_seq_fops = { .owner = THIS_MODULE, .open = udp_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net }; /* ------------------------------------------------------------------------ */ static struct udp_seq_afinfo udp4_seq_afinfo = { .name = "udp", .family = AF_INET, .udp_table = &udp_table, .seq_fops = &udp_afinfo_seq_fops, .seq_ops = { .show = udp4_seq_show, }, }; static int __net_init udp4_proc_init_net(struct net *net) { return udp_proc_register(net, &udp4_seq_afinfo); } static void __net_exit udp4_proc_exit_net(struct net *net) { udp_proc_unregister(net, &udp4_seq_afinfo); } static struct pernet_operations udp4_net_ops = { .init = udp4_proc_init_net, .exit = udp4_proc_exit_net, }; int __init udp4_proc_init(void) { return register_pernet_subsys(&udp4_net_ops); } void udp4_proc_exit(void) { unregister_pernet_subsys(&udp4_net_ops); } #endif /* CONFIG_PROC_FS */ static __initdata unsigned long uhash_entries; static int __init set_uhash_entries(char *str) { ssize_t ret; if (!str) return 0; ret = kstrtoul(str, 0, &uhash_entries); if (ret) return 0; if (uhash_entries && uhash_entries < UDP_HTABLE_SIZE_MIN) uhash_entries = UDP_HTABLE_SIZE_MIN; return 1; } __setup("uhash_entries=", set_uhash_entries); void __init udp_table_init(struct udp_table *table, const char *name) { unsigned int i; table->hash = alloc_large_system_hash(name, 2 * sizeof(struct udp_hslot), uhash_entries, 21, /* one slot per 2 MB */ 0, &table->log, &table->mask, UDP_HTABLE_SIZE_MIN, 64 * 1024); table->hash2 = table->hash + (table->mask + 1); for (i = 0; i <= table->mask; i++) { INIT_HLIST_NULLS_HEAD(&table->hash[i].head, i); table->hash[i].count = 0; spin_lock_init(&table->hash[i].lock); } for (i = 0; i <= table->mask; i++) { INIT_HLIST_NULLS_HEAD(&table->hash2[i].head, i); table->hash2[i].count = 0; spin_lock_init(&table->hash2[i].lock); } } void __init udp_init(void) { unsigned long limit; udp_table_init(&udp_table, "UDP"); limit = nr_free_buffer_pages() / 8; limit = max(limit, 128UL); sysctl_udp_mem[0] = limit / 4 * 3; sysctl_udp_mem[1] = limit; sysctl_udp_mem[2] = sysctl_udp_mem[0] * 2; sysctl_udp_rmem_min = SK_MEM_QUANTUM; sysctl_udp_wmem_min = SK_MEM_QUANTUM; } struct sk_buff *skb_udp_tunnel_segment(struct sk_buff *skb, netdev_features_t features) { struct sk_buff *segs = ERR_PTR(-EINVAL); int mac_len = skb->mac_len; int tnl_hlen = skb_inner_mac_header(skb) - skb_transport_header(skb); __be16 protocol = skb->protocol; netdev_features_t enc_features; int outer_hlen; if (unlikely(!pskb_may_pull(skb, tnl_hlen))) goto out; skb->encapsulation = 0; __skb_pull(skb, tnl_hlen); skb_reset_mac_header(skb); skb_set_network_header(skb, skb_inner_network_offset(skb)); skb->mac_len = skb_inner_network_offset(skb); skb->protocol = htons(ETH_P_TEB); /* segment inner packet. */ enc_features = skb->dev->hw_enc_features & netif_skb_features(skb); segs = skb_mac_gso_segment(skb, enc_features); if (!segs || IS_ERR(segs)) goto out; outer_hlen = skb_tnl_header_len(skb); skb = segs; do { struct udphdr *uh; int udp_offset = outer_hlen - tnl_hlen; skb->mac_len = mac_len; skb_push(skb, outer_hlen); skb_reset_mac_header(skb); skb_set_network_header(skb, mac_len); skb_set_transport_header(skb, udp_offset); uh = udp_hdr(skb); uh->len = htons(skb->len - udp_offset); /* csum segment if tunnel sets skb with csum. */ if (unlikely(uh->check)) { struct iphdr *iph = ip_hdr(skb); uh->check = ~csum_tcpudp_magic(iph->saddr, iph->daddr, skb->len - udp_offset, IPPROTO_UDP, 0); uh->check = csum_fold(skb_checksum(skb, udp_offset, skb->len - udp_offset, 0)); if (uh->check == 0) uh->check = CSUM_MANGLED_0; } skb->ip_summed = CHECKSUM_NONE; skb->protocol = protocol; } while ((skb = skb->next)); out: return segs; }
./CrossVul/dataset_final_sorted/CWE-399/c/good_5721_1